按钮初始化出现问题



每当我试图从物理设备运行我的应用程序时,它总是在"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" />

是否存在将错误的xml文件膨胀为MainActivity类的情况
onCreate()中有以下内容:

setContentView(R.layout.activity_main2);

也许你想要:

setContentView(R.layout.activity_main);

java代码和xml 不匹配

JAVArecord = findViewById(R.id.imageButton);

XMLandroid:id="@+id/imageButton2"

它应该是:record = findViewById(R.id.imageButton2);

或者XML 中没有android:id="@+id/imageButton"

最新更新