【发布时间】:2019-03-03 18:35:50
【问题描述】:
我真的很想弄清楚这一点,但我找不到答案。 我检查了 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>
【问题讨论】:
-
按钮所在的 xml 布局文件的名称是什么?
-
只是为了确认,
activity_list_items.xml是您的问题中的 XML 名称? -
您需要转换 findViewById。像这样 imaButton = (Button) findViewById(R.id.imButton);
-
@UmangBurman - Activity_Start
-
@Deepakkaku- 我试过了。没解决