android自定义dialog对话框,android的自定义dialog对话框实现

Android自定义dialog对话框

一:自定义dialog 如何填充布局

①自定MyDialog类,在类里关联布局

public class MyDialog extends AlertDialog {

Context context;

public MyDialog(Context context) {

super(context);

this.context = context;

}

public MyDialog(Context context, int theme){

super(context, theme);

this.context = context;

}

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

this.setContentView(R.layout.layout_dialog);

}

}

然后,再在外面类MainActivity引用这个自定义类

Dialog dialog = new MyDialog(ActivityB.this,R.style.MyDialog);

dialog.show();

②在代码里填充布局

//在MainActivity类里直接填充

AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this);

AlertDialog dialog1 = b.create();

LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);

View view = inflater.inflate(R.layout.layout_dialog, null);

dialog1.setView(view, 0, 0, 0, 0);

dialog1.show();

二:自定义dialog 的按钮的事件

系统的dialog ,在给对话框上的button设置事件的时候可以通过setPositiveButton()、setNegativeButton()这两个方法来实现。但是自定义的dialog就不能再用这两个方法了,可以换成setOnClickListener()方法。//setOnClickListener(android.view.View.OnClickListener object);

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_b);

btn_ctrl = (Button) findViewById(R.id.btn_ctrl);

tv_ticket = (TextView)findViewById(R.id.tv_ticket);

btn_ctrl.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

//初始化一个自定义的Dialog

Dialog dialog = new MyDialog(ActivityB.this,R.style.MyDialog);

dialog.show();

}

});

tv_ticket.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

AlertDialog.Builder dialog1 = new AlertDialog.Builder(ActivityB.this);

dialog1.getWindow().setLayout(450, 330);

LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);

View view = inflater.inflate(R.layout.dialog_reconn, null);

dialog1.setView(view);

dialog1.show();

}

});

}

点完按钮之后,默认对话框不隐藏,调用dialog.dismiss()方法就可以隐藏对话框

0818b9ca8b590ca3270a3433284dd417.png

你可能感兴趣的:(android自定义dialog对话框,android的自定义dialog对话框实现)