我想按 ID 選擇按鈕元素,但是當我運行程式時,我得到應用程式不斷停止錯誤。我在除錯模式下運行程式,錯誤原因如下:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.Button.findViewById(int)' on a null object reference
即使單擊R.id.button,按鈕元素也會顯示在 xml 檔案中。
主活動檔案:
package com.example.app;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity6 extends AppCompatActivity {
private Button btn;
private TextView txt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main6);
btn.findViewById(R.id.button);
txt.findViewById(R.id.txt);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
txt.setText("This is a new text.");
}
});
// Toast.makeText(this, "str", Toast.LENGTH_LONG).show();
}
}
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=".MainActivity6">
<TextView
android:id="@ id/txt"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:autoSizeTextType="uniform"
android:autoSizeMinTextSize="25sp"
android:autoSizeMaxTextSize="100dp"
android:autoSizeStepGranularity="2sp"
android:layout_height="wrap_content" />
<Button
android:id="@ id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
uj5u.com熱心網友回復:
btn.findViewById(R.id.button);
您不應該以這種方式使用它,因為此時btn為空。您必須執行以下操作:
btn = (Button)findViewById(R.id.button);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/531626.html
標籤:爪哇安卓xml
