本文演示了如何创建一个悬浮对话框,即将activity以对话框的方式显示。
只要指定Activity的主题是dialog即可:
android:theme="@android:style/Theme.Dialog"
对于onTouchEvent方法:1、悬浮对话框(Activity) 单击屏幕上的任意地方都会触发
2、对话框 要想使用对话框的onTouchEvent方法。则必须继承AlertDialog类
本例先进入的是一个悬浮对话框(Activity),单击显示日期后弹出对话框,由于该对话框实现了AlertDialog的onTouchEvent方法,所以单击任意位置,对话框都会消失。
布局文件:
<?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:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:text="这是一个悬浮对话框" /> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_marginTop="20dp" android:gravity="center" android:orientation="horizontal" > <Button android:id="@+id/btnCurrentDate" android:layout_width="80dp" android:layout_height="wrap_content" android:text="当前日期" /> <Button android:id="@+id/btnFinish" android:layout_width="80dp" android:layout_height="wrap_content" android:text="关闭" /> </LinearLayout> </LinearLayout>
弹出对话框实现onTouchEvent:
public class DateDialog extends AlertDialog { public DateDialog(Context context) { super(context); } @Override public boolean onTouchEvent(MotionEvent event) { dismiss(); return super.onTouchEvent(event); } }
悬浮对话框风格的Activity:
public class Main extends Activity implements android.view.View.OnClickListener { private DateDialog dateDialog; public void onClick(View view) { switch (view.getId()) { case R.id.btnCurrentDate: SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd"); dateDialog.setIcon(R.drawable.date); dateDialog.setTitle("当前日期:" + simpleDateFormat.format(new Date())); dateDialog.setButton("确定", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { // } }); dateDialog.setOnDismissListener(new OnDismissListener() { public void onDismiss(DialogInterface dialog) { new DateDialog.Builder(Main.this) .setMessage("您已经关闭的当前对话框.").create().show(); } }); dateDialog.show(); break; case R.id.btnFinish: finish(); break; } } @Override public boolean onTouchEvent(MotionEvent event) { finish(); return true; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button btnCurrentDate = (Button) findViewById(R.id.btnCurrentDate); Button btnFinish = (Button) findViewById(R.id.btnFinish); btnCurrentDate.setOnClickListener(this); btnFinish.setOnClickListener(this); dateDialog = new DateDialog(this); } }
时间: 2024-10-26 17:07:17