我想用视图构建一个alertdialog并访问TextView来设置它的文本值。这是代码:
private void ShowLogDialog() {
AlertDialog ad = new AlertDialog.Builder(this).create();
ad.setIcon(R.drawable.icon);
ad.setTitle("Ultimate Logs");
ad.setView(LayoutInflater.from(this).inflate(R.layout.log_layout, null));
TextView text = (TextView)ad.findViewById(R.id.logTextView_log); // RETURNS NULL
//Log.i(TAG, "Into ShowLogDialog : GoT TextView = " + text);
//String logsText = "";
//text.setText(logsText);
ad.setButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ad.show();
}
log_layout.xml
<LinearLayout android:id="@+id/linearLayout1" android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical" android:scrollbars="vertical" android:scrollbarAlwaysDrawVerticalTrack="true" xmlns:android="http://schemas.android.com/apk/res/android">
<TextView android:layout_height="wrap_content" android:text="TextView" android:id="@+id/**logTextView_log**" android:layout_width="wrap_content"></TextView>
</LinearLayout>
为什么我无法访问TextView?它返回null并抛出NullPointerException。我无法使用findBiewById直接访问,所以我使用的是ad.findViewById,但我只收到null。任何人都可以帮我知道我哪里错了!
由于
答案 0 :(得分:2)
这似乎有效。玩得开心!
AlertDialog.Builder builder= new AlertDialog.Builder(this);
LayoutInflater inflater= getLayoutInflater();
final View myView= inflater.inflate(R.layout.alert_dialog_text_entry, null);
builder.setTitle("About");
builder.setMessage("Test");
builder.setView(myView);
AlertDialog alert= builder.create();
TextView stateful= (TextView)myView.findViewById(R.id.TextView01);
stateful.setText("More Testing");
Log.d(Utilities.TAG,stateful.toString());
alert.show();
答案 1 :(得分:0)
这是什么意思..?
android:id="@+id/**logTextView_log**
**意味着......?
答案 2 :(得分:0)
为什么不首先将LayoutInflater.from(this).inflate(R.layout.log_layout, null)
返回到View
变量? (以下代码未经测试)
ad.setTitle("Ultimate Logs");
View inflatedView = LayoutInflater.from(this).inflate(R.layout.log_layout, null);
TextView text = (TextView)inflatedView.findViewById(R.id.logTextView_log); // RETURNS NULL
Log.i(TAG, "Into ShowLogDialog : GoT TextView = " + text);
String logsText = "";
text.setText(logsText);
ad.setView(inflatedView );
ad.setButton("Ok", new DialogInterface.OnClickListener() {