我想在用戶單擊圖像(可能很容易是一個按鈕)後更改textView的文本。我不斷得到一個關閉力量和nullpointerexception。我試圖編寫它爲Android 2.3.3NullPointerException當嘗試更改textview的文本點擊
該代碼是基於谷歌上找到的很多例子。
public class TestImagesActivity extends Activity {
private android.view.View.OnClickListener mCorkyListener = new android.view.View.OnClickListener() {
public void onClick(View v) {
final TextView txt = (TextView) findViewById(R.id.svariable);
txt.setText("new text"); // this line throws an exception
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView image = (ImageView) findViewById(R.id.test_image);
image.setOnClickListener(mCorkyListener);
}
我main.xml中看起來是這樣的:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android.id="@+id/svariable"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<ImageView
android:id="@+id/test_image"
android:src="@drawable/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
你嘗試過加入Anroid的:的onclick到ImageView的?然後調用該函數而不是使用偵聽器。也許是一種考驗。 – VicVu