安卓通知的使用系列6:对话框通知的使用之自定义对话框

来源:互联网 发布:知柏地黄丸不良反应 编辑:程序博客网 时间:2024/06/05 00:20

自定义对话框是使用对话框的一种高级形式,下面我们来介绍一下它的使用方式。

整体思路:首先定义一个custom_dialog.xml文件,在这个文件中放置几个控件,作为自定义的对话框的界面,创建一个CustomDialog类,在这个类中定义它的构造方法和show方法,在show方法中绑定custom_dialog.xm文件,设置这个xml文件中控件的属性,并显示这个自定义对话框。

custom_dialog.xml文件:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/layout_root"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="horizontal"    android:padding="10dp"     >        <ImageView         android:id="@+id/image"        android:layout_width="wrap_content"        android:layout_height="fill_parent"        android:layout_marginRight="10dp"        />        <TextView         android:id="@+id/text"        android:layout_width="wrap_content"        android:layout_height="fill_parent"        android:textColor="#FFF"        /></LinearLayout>
CustomDialog.java文件:

public class CustomDialog {private Context context;private Dialog dialog;public CustomDialog(Context context) {this.context=context;// TODO Auto-generated constructor stubdialog=new Dialog(context);}public void show() {// TODO Auto-generated method stub//第二个参数为null,表示当前对话框是没有根布局的View view=LayoutInflater.from(context).inflate(R.layout.custom_dialog, null);//也可以采用这种方式来加载:setContentView(R.layout.custom_dialog);dialog.setContentView(view);dialog.setTitle("自定义对话框");TextView textview=(TextView)view.findViewById(R.id.text);textview.setText("你好,自定义对话框");textview.setTextColor(Color.BLACK);ImageView imageView=(ImageView)view.findViewById(R.id.image);imageView.setImageResource(R.drawable.ic_launcher);dialog.show();}}
MainActivity.java文件:

public class MainActivity extends Activity {    private Button button3;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);button3=(Button)findViewById(R.id.button3);button3.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stub//显示一个自定义对话框CustomDialog dialog=new CustomDialog(MainActivity.this);dialog.show();}});}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}




0 0