我是 Android 编程的新手,可能我还不太了解 Java,所以我的程序遇到了这个问题。每次我按下菜单上的按钮时,我都会得到java.lang.NullPointerException。单击菜单上的item2时,是否有任何方法可以引用此 TextView 对象并更改其文本?
public class MainActivity extends Activity {
TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MainActivity.this.tv = (TextView) findViewById(R.id.tekst1);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mymenu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.item2) {
MainActivity.this.tv.setText("aaa");
}
return super.onOptionsItemSelected(item);
}
}
编辑:mymenu xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/item1"
android:icon="@android:drawable/ic_menu_week"
android:title="Option 1"/>
<item
android:id="@+id/item2"
android:icon="@android:drawable/ic_menu_month"
android:title="Option 2"/>
</menu>
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/tekst1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world"
tools:context=".MainActivity" />
</RelativeLayout>