Android studio 中,设置三个按钮,两个按钮分别禁用和启用第三个按钮,同时改变第三个按钮的颜色。
点击按钮app就会闪退,log里报错如下。报错位置在代码注释里
FATAL EXCEPTION: main
Process: com.my.test, PID: 23639
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setEnabled(boolean)' on a null object reference
at com.my.test.MainActivity$MyOnClickListener.onClick(MainActivity.java:46)
具体运行java代码如下:
public class MainActivity extends AppCompatActivity {
private TextView test0;
private Button result1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
test0 = findViewById(R.id.test0);
Button enable1 = findViewById(R.id.enable1);
enable1.setOnClickListener(new MyOnClickListener());
Button disable1 = findViewById(R.id.disable1);
disable1.setOnClickListener(new MyOnClickListener());
Button result1 = findViewById(R.id.result1);
result1.setOnClickListener(new MyOnClickListener());
}
class MyOnClickListener implements View.OnClickListener {
public void onClick(View v) {
SimpleDateFormat time = new SimpleDateFormat("h:mm:ss");
if (v.getId() == R.id.enable1) {
result1.setTextColor(Color.BLACK);
result1.setEnabled(true);
} else if (v.getId() == R.id.disable1) {
result1.setTextColor(Color.GRAY);
result1.setEnabled(false);
} else if (v.getId() == R.id.result1) {
String desc = String.format("%s 你点了按钮: %s",
time.format(new Date()), ((Button) v).getText());
test0.setText(desc);
}
}
}
}
xml文件如下
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00aaff"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/enable1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="启用按钮" />
<Button
android:id="@+id/disable1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="禁用按钮" />
</LinearLayout>
<Button
android:id="@+id/result1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:enabled="false"
android:text="结果按钮" />
<TextView
android:id="@+id/test0"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="这里查看点击结果"
android:textColor="@color/black"/>
</LinearLayout>