我使用此代码创建自定义AlertDialog:
val dialog = AlertDialog.Builder(context)
.setView(R.layout.layout)
.create()
问题是我无法获得膨胀的观点。 dialog.findViewById(R.id.a_view_in_the_layout)
返回null。
或者,我可以使用.setView(View.inflate(context, R.layout.layout, null)
但这有时会使对话框填满屏幕并占用比setView(int layoutResId)
更多的空间。
如果我没记错的话,create
会设置Dialog,但是在需要显示之前它的布局不会膨胀。首先尝试调用show
,然后找到您正在寻找的视图。
val dialog = AlertDialog.Builder(context)
.setView(R.layout.layout)
.create()
dialog.show() // Cause internal layout to inflate views
dialog.findViewById(...)
而不是使用alert dialog
使用simple Dialog
它简单而且非常简单
final Dialog dialog = new Dialog(context);
dialog.setContentView((R.layout.layout);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
TextView tvTitle = (TextView) dialog.findViewById(R.id.tvTitle);
tvTitle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
您无需为视图充气。
只是自己夸大布局(它的Java代码,但我想你知道该怎么做):
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE );
View view = inflater.inflate( R.layout.layout, null );
dialog.setView(view);
dialog.create().show();
您的膨胀视图现在是view
,您可以使用它来查找其中的其他视图,如:
EditText editText = view.findViewById(R.id.myEdittext);
试试这个;
View dialogView; //define this as a gobal field
dialogView = LayoutInflater.from(context).inflate(R.layout.your_view, null);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Title");
builder.setView(dialogView);
View yourView = dialogView.findViewById(R.id.a_view_in_the_layout);
TextView yourTextView = dialogView.findViewById(R.id.a_textView_in_the_layout);
Button yourButton = dialogView.findViewById(R.id.a_button_in_the_layout);