【Android基础篇】AlertDialog自定义setView方法的控件响应方法

Android使用AlertDialog弹出对话框时,如果需要自定义对话框界面,就需要用到setView来设置界面,此时,界面上一般都会有需响应或需记录结果的控件,这就需要查找控件了。下面就是一个在自定义对话框中查找控件并进行响应的实例:

LayoutInflater layoutInflater = LayoutInflater.from(mContext);
View newPlanDialog = layoutInflater.inflate(R.layout.new_plan_dialog, 
                        (ViewGroup)findViewById(R.id.LinearLayout_newplan));

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this)
    .setTitle("添加新计划")
    .setIcon(R.drawable.ic_launcher)
    .setView(newPlanDialog)
;

builder.setPositiveButton("确定", new android.content.DialogInterface.OnClickListener(){

    @Override
    public void onClick(DialogInterface dialog, int which) {
        // TODO Auto-generated method stub
        //Toast.makeText(getApplicationContext(), 
        start.toString()+":"+end.toString(), 2000).show();
        String content = text.getText().toString();
        Log.d("Content",content);
        Integer.toString(start.getCurrentHour())+
        ":"+Integer.toString(start.getCurrentMinute()));

        Log.d("EndTime",
        Integer.toString(end.getCurrentHour())+
        ":"+Integer.toString(end.getCurrentMinute()));
        dialog.dismiss();
    }

});
builder.setNegativeButton("取消", new android.content.DialogInterface.OnClickListener(){
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // TODO Auto-generated method stub
        dialog.dismiss(); 
    }               
});
AlertDialog ad = builder.create(); //创建对话框
ad.show(); //需先显示,然后才能查找控件
start =(TimePicker)ad.findViewById(R.id.timepicker_start);
end = (TimePicker)ad.findViewById(R.id.timepicker_end);
text = (EditText)ad.findViewById(R.id.editText_content);

界面的xml文件就是两个时间控件和一个编辑框。
需注意,必须show对话框,然后才能查找控件。

你可能感兴趣的:(android,dialog,setView)