Chernobyl

<Android>自定义对话框

自定义对话框

  • 在layout中创建一个对话框布局文件*.xml
  • 创建一个CustomDialog类并继承Dialog类
  • 重写onCreate()方法
  • 在事件监听器中实例化CustomDialog类,并调用show()方法

custom.xml

1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3     android:layout_width="match_parent"
4     android:layout_height="match_parent"
5     android:orientation="vertical" >
6     
7     <!-- 自定义布局 -->
8     
9 </LinearLayout>

 

CustomDialog.java

 1 package com.example.customdialog;
 2 
 3 import android.app.Dialog;
 4 import android.content.Context;
 5 import android.os.Bundle;
 6 
 7 public class CustomDialog extends Dialog {
 8 
 9     public CustomDialog(Context context) {
10         super(context);
11     }
12 
13     @Override
14     protected void onCreate(Bundle savedInstanceState) {
15         super.onCreate(savedInstanceState);
16         this.setContentView(R.layout.custom);
17     }
18 
19 }

 

MainActivity.java

 1 Button button = (Button) findViewById(R.id.button);
 2         button.setOnClickListener(new OnClickListener() {
 3 
 4             @Override
 5             public void onClick(View v) {
 6                 CustomDialog customDialog = new CustomDialog(MainActivity.this);
 7                 customDialog.show();
 8             }
 9         });

 

  1. 注意context的用法
  2. import android.R会导致无法引用layout中的文件

posted on 2014-02-21 18:57  Chernobyl  阅读(241)  评论(0编辑  收藏  举报

导航