Android开发小结Part7:LayoutInflater自定义布局

LayoutInflater的作用类似于 findViewById(),不同点是LayoutInflater是用来找layout文件夹下的xml布局文件,并且实例化!而 findViewById()是找具体某一个xml下的具体 widget控件(如:Button,TextView等)。

自定义Dialog时,通过LayoutInflater实例化layout文件夹下的布局文件的方法有2种。
第1种:

case R.id.button4:
    LayoutInflater inflater = (LayoutInflater)getApplicationContext()
                                .getSystemService(LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.course_custom_dialog, null);
    AlertDialog.Builder builder2=new AlertDialog.Builder(MainDialogActivity.this);
    builder2.setView(view);
    builder2.setTitle("添加课程")
            .setPositiveButton("保存", new DialogInterface.OnClickListener() {
                @Override
		public void onClick(DialogInterface dialog, int which) {
		    dialog.cancel();
		}
	    })
            .setNegativeButton("取消", null)
            .create().show();
    break;
第2种:
case R.id.button4:
    LayoutInflater inflater = (LayoutInflater)LayoutInflater.from(getApplicationContext());
    View view = inflater.inflate(R.layout.course_custom_dialog,null);
    				
    AlertDialog.Builder builder2=new AlertDialog.Builder(MainDialogActivity.this);
    builder2.setView(view);
    builder2.setTitle("添加课程")
            .setPositiveButton("保存", new DialogInterface.OnClickListener() {
	        @Override
                public void onClick(DialogInterface dialog, int which) {
		    dialog.cancel();
		}    					
    })
            .setNegativeButton("取消", null)
            .create().show();
    break;


你可能感兴趣的:(android,LayoutInflater,自定义布局)