NullPointerException-当我尝试使用按钮切换活动时

时间:2018-09-27 19:26:47

标签: android android-button

我确实在试图解决这个问题,但是我找不到答案。 我检查了XML文件,对我来说看起来不错。尝试了此代码的多个版本,每次都收到相同的结果:

'Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener 
(android.view.View$OnClickListener)' on a null object reference at com.example.owner.androidlab01.StartActivity.onCreate(StartActivity.java:25)

活动分类:

public class StartActivity extends Activity {

    protected static final String ACTIVITY_NAME = "StartActivity";

    private Button imaButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_items);
        Log.i(ACTIVITY_NAME, "In onCreate()");

        imaButton = findViewById(R.id.imbutton);
        imaButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(StartActivity.this , ListItemsActivity.class);
                startActivityForResult(intent ,50);
            }
        });
    }

这是XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".StartActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_message"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/imbutton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/ButtonText" />

</LinearLayout>

1 个答案:

答案 0 :(得分:0)

您是否尝试投射此对象?

imaButton = findViewById(R.id.imbutton);

我认为将其强制转换为Button

imaButton = (Button) findViewById(R.id.imbutton);