1

我已经设置了一个按钮,当用户点击它时,我试图显示一个 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" />

这会在行上引发 NullPointerException file.setOnClickListener(new OnClickListener() {。我究竟做错了什么?

4

3 回答 3

3

您是否在 Activity 的 onCreate() 方法中初始化 Button?

如果是,请检查您是否正在拨打电话

setContentView(R.id.yourlayoutfile);

在初始化按钮之前findViewById(R.id.file);

发生错误是因为您的按钮“文件”是null,这意味着findViewById(...)没有找到任何具有该 ID 的视图。因此,原因可能是膨胀的布局中没有这样的 ID,或者您没有调用setContentView(...)

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yourlayoutfile);

        // initialize your button here  
    }
于 2013-08-18T07:01:22.257 回答
1

尝试清理项目

项目-->清理-->选择你的项目-->确定,然后再次运行。

如果您仍然面临同样的问题,您可以使用另一种方式来设置点击操作

在你的 XML

<Button
        android:id="@+id/file"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/plt"

        <!--added line-->            
        android:onClick="anyName"

        android:text="File" />

然后在您的活动中删除按钮的初始化并单击listner

并使代码看起来像这样

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.id.yourlayoutfile);
}

public void anyName(View v){
Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)",
   Toast.LENGTH_LONG).show();

}

希望这有帮助。

于 2013-08-18T10:15:42.920 回答
0

如果这一行出现空指针异常:

file.setOnClickListener(new OnClickListener() 

那么这意味着你的file对象是空的

确保在添加侦听器之前初始化文件对象。

于 2013-08-18T07:00:18.293 回答