你应该设置的TextView的id,听你的TargetTrainer触摸事件,并且在一个occures,您使用
final TextView tv = (TextView)TargetTrainer.this.findViewById(R.id.myTextView);
tv.setText(touchEvent.toString());
就是这样。
更新
这将是干净多了,如果你从一个XML源代码构建主布局。
你需要创建/ RES /布局,看起来像你的onCreate
方法内部创建一个内布置一新的xml:
RES /布局/ main.xml中
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/myTextView" android:text="Test"
android:layout_width="fill_parent" android:layout_height="wrap_content" />
<!-- change the your.package part to match the package declaration
of your TargetTrainer class -->
<your.package.TargetTrainer android:id="@+id/myTargetTrainer"
android:layout_width="fill_parent" android:layout_height="fill_parent" />
</LinearLayout>
这样一个新的条目将被放置在您的R类的静态layout
类中,名称为main
。
您可以通过R.layout.main
来引用它。
注意,在这个XML,你有两个
- 你的TextView定义ID属性:
myTextView
和
- 您TargetTrainer: 'myTargetTrainer'。
xml标签内的@ + id表示您正在用'/'符号后面的名称创建一个新的id。
这也将在您的R类的静态id
类中创建新成员,并提供您提供的名称:myTextView
和myTargetTrainer
,它们可以从您的代码的任何位置立即访问。
如果你已经建立了这个XML,你onCreate
方法是这样的:
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// attach the OnTouchListener to your TargetTrainer view:
(TargetTrainer)findViewById(R.id.myTargetTrainer).setOnTouchListener(this);
}
您还可以扩展您的主要活动类实现View.OnTouchListener
接口,并在末尾添加了必要的方法你的类:
@Override
public boolean onTouch(View view, MotionEvent event)
{
//note, that here the view parameter is the view the touch event has been dispatched to
final TextView tv = (TextView)findViewById(R.id.myTextView);
tv.setText(event.toString());
return true; //or false, if you are dealing further with this event in parent classes
}
我想我可能需要做一些与上下文也许,因为我们需要传递到一个视图,但是那是相当不清楚我也 – 2011-04-17 16:59:18