我试图创建一个警告对话框,顶部有一个图像标题,底部有两个按钮,我想从代码中间设置文本。但是,我无法在横幅下方获取设置文字。我想创建类似于this link上的内容。但是,文本总是在图像上方,因为我不知道如何在对话框构建器中引用textview。感谢
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
builder.setView(inflater.inflate(R.layout.custom_dialog, null))
.setMessage("Message" + message)
.setPositiveButton("Share", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (isNetworkAvailable()) {
if (...) {...}
else {...}
} else {...}
}
})
.setNegativeButton("Shake again!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
})
.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {}
});
AlertDialog alert = builder.create();
alert.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {}
});
alert.show();
布局xml文件是:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:src="@drawable/yo3"
android:layout_width="match_parent"
android:layout_height="64dp"
android:scaleType="center"
android:background="#FFFFBB33"
android:contentDescription="@string/app_name" />
<TextView
android:id="@+id/dialogtext"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>`
答案 0 :(得分:3)
请勿按照您的方式设置消息。
在您的自定义布局中,您必须设置的textview是&#34; dialogtext&#34; TextView中。 试试这个......看到我得到了我自动膨胀的自定义视图,从该视图中我得到了自定义对话框(之前你没有实际设置),并在构建完成后设置要显示的消息。 实际上你可以拥有你想要的任何自定义视图,并根据需要设置视图的每个元素,甚至可以处理它上面的事件
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View customView = inflater.inflate(R.layout.custom_dialog, null);
TextView messageView = (TextView)customView.findViewById(R.id.dialogtext);
builder.setView(customView)
.setPositiveButton("Share", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (isNetworkAvailable()){
if (......;
} else {
......
}
} else {
.......;
}
}
})
.setNegativeButton("Shake again!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
}).setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
}
});
messageView.SetText("Message" + message);
AlertDialog alert = builder.create();
alert.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
}
});
alert.show();