安卓通知的使用系列6:對話框通知的使用之自定義對話框

自定義對話框是使用對話框的一種高級形式,下面我們來介紹一下它的使用方式。

整體思路:首先定義一個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 stub
		dialog=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;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		button3=(Button)findViewById(R.id.button3);
		
		button3.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
//				顯示一個自定義對話框
				CustomDialog dialog=new CustomDialog(MainActivity.this);
				dialog.show();
			}
		});
		
	}

	@Override
	public 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;
	}

}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章