Button初始化出现问题

时间:2018-11-30 15:33:24

标签: java android

每当我尝试从物理设备运行我的应用程序时,它总是崩溃并在“ setEnabled”行或任何我尝试使用的方法上出现NullPointerException。

Java:

    public class MainActivity extends AppCompatActivity {

    TextView textView;
    ImageButton record;
    ImageButton stop;
    TextView textView2;
    TextView textView3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        textView = findViewById(R.id.textView);
        record = findViewById(R.id.imageButton);
        stop = findViewById(R.id.imageButton2);
        textView2 = findViewById(R.id.textView2);
        textView3 = findViewById(R.id.textView3);

        textView.setText("   Bienvenido a Bilder!");
        record.setEnabled(true);

XML:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout 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:background="@color/gris_claro"
    tools:context=".MainActivity">

    {...}

    <ImageButton
        android:id="@+id/imageButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@android:color/holo_orange_dark"
        android:paddingBottom="20dp"
        android:paddingLeft="66dp"
        android:paddingRight="65dp"
        android:paddingTop="20dp"
        app:srcCompat="@drawable/stop64"
        android:layout_alignParentRight="true" />

清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.santper.bilder">

    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

2 个答案:

答案 0 :(得分:0)

是否存在将错误的xml文件膨胀到MainActivity类的情况?
onCreate()中是这样的:

setContentView(R.layout.activity_main2);

也许你想要

setContentView(R.layout.activity_main);

答案 1 :(得分:0)

java代码和xml不匹配

JAVA record = findViewById(R.id.imageButton);

XML android:id="@+id/imageButton2"

应为: record = findViewById(R.id.imageButton2);

否则XML中没有android:id="@+id/imageButton"