最近公司没什么项目做,大部分时间都是自己在学习,而且觉得有必要和各位园友分享、交流下自己的所学所得,所以呢,决定今天开始写博吧。
嗯嗯,步入正题,很多时候Android自带的控件样式不能满足我们多样化的需求,要自己去自定义才会给人耳目一新的感觉,今天就先拿AlertDialog开导,哈~先上效果图(比较喜欢柯南O(∩_∩)O):
点击enter按钮会关闭对话框,留在当前Activity,点击exit按钮则退出应用。
首先是main.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#FFFFFFFF" android:orientation="vertical" > <Button android:id="@+id/button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout>
主Activity代码CustomAlertDialogActivity.java:
package nbe.sense7.vinci.custom.alertdialog; import android.app.Activity; import android.app.AlertDialog; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.ImageButton; public class CustomAlertDialogActivity extends Activity { /** Called when the activity is first created. */ private Button button; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //点击弹出自定义对话框 button = (Button)findViewById(R.id.button); button.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub showCustomAlertDialog(); } }); } private void showCustomAlertDialog(){ final AlertDialog alertDialog = new AlertDialog.Builder(this).create(); alertDialog.show(); Window win = alertDialog.getWindow(); //设置自定义的对话框布局 win.setContentView(R.layout.custom_alertdialog); //关闭对话框按钮事件 ImageButton enterBtn = (ImageButton)win.findViewById(R.id.enter_btn); enterBtn.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub alertDialog.cancel(); } }); //退出程序 ImageButton exitBtn = (ImageButton)win.findViewById(R.id.exit_btn); exitBtn.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub CustomAlertDialogActivity.this.finish(); } }); } }
自定义对话框布局文件custom_alertdialog.xml:
<?xml version="1.0" encoding="UTF-8" ?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_margin="15dp" android:gravity="center_horizontal" android:orientation="horizontal" android:background="@drawable/dialog_bg"> <!-- enter button --> <ImageButton android:id="@+id/enter_btn" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_margin="15dp" android:layout_gravity="bottom" android:src="@drawable/enter_btn"/> <!-- quit button --> <ImageButton android:id="@+id/exit_btn" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_margin="15dp" android:layout_gravity="bottom" android:src="@drawable/exit_btn"/> </LinearLayout>