我非常感谢明确的指示。这是来自谷歌Android开发教程但是,我找不到显示(膨胀)它的方法。 alertDialog.show()导致程序在模拟器上崩溃。
public class HelloAndroidActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AlertDialog.Builder builder;
AlertDialog alertDialog;
Context mContext = getApplicationContext();
LayoutInflater inflater = (LayoutInflater)
mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog,
(ViewGroup) findViewById(R.id.layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Hello, this is a custom dialog!");
ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.android);
builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
alertDialog = builder.create();
}
}
答案 0 :(得分:0)
最后使用:
alertDialog.show();
答案 1 :(得分:0)
我认为最容易和更可定制的方法是通过膨胀DialogFragment。
您在活动中执行以下操作:
FragmentTransaction ft = getFragmentManager().beginTransaction();
DialogFragment dfrag = new CustomDFrag();
dfrag.show(ft,"dialog");
然后创建扩展DialogFragment的类CustomDFrag。然后你重写onCreateDialog并使用你到目前为止所做的,但现在使用自定义布局:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.my_layout,null);
//this is how you'd get a view from the inflated layout
data = (TextView) view.findViewById(R.id.evo_addhist_data);
data.setText("lol");
//tell the builder that you wan't that inflated layout to show
// and then set the button (negative/positive in this case) if you want
builder.setView(
view)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
})
.setNegativeButton("CANCEL",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
}
});
return builder.create();
}
ps。:我推荐这个,因为我觉得在不处理textview时会更好。