gpt4 book ai didi

android - findViewById 返回 null

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:56:02 26 4
gpt4 key购买 nike

我有代码:

public class HelloWorld extends Activity {

private Button buttonOk;
private Button buttonCancel;

private OnClickListener buttonOkListener = new OnClickListener() {
public void onClick(View v){
EditText editText = (EditText)findViewById(R.id.input);

CharSequence textFromInput = (CharSequence) editText.getText();
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context,textFromInput,duration);
toast.show();
}
};

private OnClickListener buttonCancelListener = new OnClickListener() {
public void onClick(View v){
EditText editText = (EditText)findViewById(R.id.input);

CharSequence textFromInput = (CharSequence) editText.getText();
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context,textFromInput,duration);
toast.show();
}
};

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// ToDo add your GUI initialization code here

setContentView(R.layout.main);

buttonOk = (Button)findViewById(R.id.buttonOk);
buttonCancel = (Button)findViewById(R.id.buttonCancel);

buttonOk.setOnClickListener(buttonOkListener);
buttonCancel.setOnClickListener(buttonCancelListener);
}
}

和布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Wpisz swoje imię:"/>
<EditText
android:id="@+id/input"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@android:drawable/editbox_background"
android:layout_below="@id/label"/>
<Button
android:id="@+id/buttonOk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/input"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dip"
android:text="OK" />
<Button
android:id="@+id/buttonCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/buttonOk"
android:layout_alignTop="@id/buttonOk"
android:text="Anuluj" />
</RelativeLayout>

符合buttonCancel.setOnClickListener(buttonCancelListener);抛出异常,因为 buttonCancel 为空。我做错了什么?

最佳答案

您的代码没有问题,一切正常。

通过 findViewById() 方法遇到 null 的最常见错误是您忘记调用 setContentView() 或为错误的布局调用它。

我建议清理您的项目并重试!!!!

关于android - findViewById 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5937962/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com