gpt4 book ai didi

java - 对话框中的 EditText 值

转载 作者:行者123 更新时间:2023-11-30 01:17:31 26 4
gpt4 key购买 nike

我不明白,对话框和一切正常,但一旦我从 EditText 获取值并将其分配给 val,运行应用程序它就会在 onClick 中崩溃。

我收到一个错误:尝试在空对象引用上调用虚方法“android.text.Editable android.widget.EditText.getText()”

public void createDialogBox() {

AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Get the layout inflater
LayoutInflater inflater = this.getLayoutInflater();

// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
//


builder.setView(R.layout.custom_dialog)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// On success

EditText text = (EditText) findViewById(R.id.shopping_list_recycler_view);
String val = text.getText().toString();

adapter = new ShoppingListViewAdapter(test, MainShoppingListViewActivity.this);
recyclerView.setAdapter(adapter);

adapter.addTest(new Data(val, "Created by: Me"));
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// On failure
Toast.makeText(MainShoppingListViewActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
})
// Desired icon for the dialog box
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}

日志

06-03 22:37:29.778 21364-21364/familyshopshare.com.familyshopshare E/AndroidRuntime: FATAL EXCEPTION: main
Process: familyshopshare.com.familyshopshare, PID: 21364
java.lang.ClassCastException: android.support.v7.widget.RecyclerView cannot be cast to android.widget.EditText
at familyshopshare.com.familyshopshare.MainShoppingListViewActivity$3.onClick(MainShoppingListViewActivity.java:93)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:157)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

最佳答案

如果你想获得对话框内的 View ,那么你必须像这样膨胀布局 -

  View rootView = inflater.inflate(R.layout.custom_dialog, null);

然后初始化你的 View -

final EditText text = (EditText)rootView.findViewById(R.id.shopping_list_recycler_view);

并将其设置为对话框中的 View -

builder.setView(rootView);

然后您可以像这样在 onClick() 中访问您的 EditText -

public void onClick(DialogInterface dialog, int which) {
// On success
String val = text.getText().toString();

}

从崩溃中可以看出,您显然错误地对 View ID 进行了类型转换。您将 shopping_list_recycler_view 类型转换为 EditText,这是不正确的。请检查您的 xml 并使用正确的 View ID。

关于java - 对话框中的 EditText 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37624291/

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