我已经设置了一个按钮,我试图在用户点击它时显示 toast 辞。这是我的 Java 代码 -
file = (Button) findViewById(R.id.file);
file.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Display the file chooser dialog
//showChooser();
Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)", Toast.LENGTH_LONG).show();
}
});
这是我设置按钮的 XML 代码 -
<Button
android:id="@+id/file"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/plt"
android:text="File" />
这会在 file.setOnClickListener(new OnClickListener() {
行上引发 NullPointerException。我做错了什么?
最佳答案
您是否在 Activity 的 onCreate() 方法中初始化 Button?
如果是这样,请检查您是否正在打电话
setContentView(R.id.yourlayoutfile);
在使用 findViewById(R.id.file); 初始化 Button 之前
您的错误发生是因为您的 Button"file"是 null
,这意味着 findViewById(...)
没有找到任何具有该 ID 的 View . 因此,原因可能是在展开的布局中没有这样的 ID,或者您没有调用 setContentView(...)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourlayoutfile);
// initialize your button here
}
关于java - Onclick 监听器抛出 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18296530/