你應該設置的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