最近因为项目需求,要在一个service上面弹出一个菜单,菜单响应select事件,所以花了点时间把android弹出Dialog的各种方式都看了一下。

目前学习到的android有三种方式弹出对话框:

1、AlertDialog

AlertDialog是非阻塞的,简单的记录一下创建的代码:

AlertDialog.Builder builder; AlertDialog alertDialog; Context mContext = getApplicationContext(); //mContext不可用 builder = new AlertDialog.Builder(mContext); builder.setTitle("测试菜单"); //builder.setView(view); alertDialog = builder.create(); alertDialog.show();

new AlertDialog.Builder所需要的参数,经过测试和网上查找,发现是要Activity才可以的

所以最后采用了这种方式

遇到一个问题,默认的对话框的大小是全屏的,改变大小的方法是

1)更改AlertDialog窗口大小的方法: AlertDialog dialog = new AlertDialog.Builder(this).create(); dialog.show(); WindowManager.LayoutParams params = dialog.getWindow().getAttributes(); params.width = 200; params.height = 200 ; dialog.getWindow().setAttributes(params); 2)去除边框 AlertDialog.setView(view,0,0,0,0);

2、PopupWindow

PopupWindow是阻塞的对话框,基本上满足要求,但是最后获取焦点,

进行onkey事件还是遇到了很多的问题。奇怪,还是把部分代码贴出来:

//创建PopupWindow

Context mContext = getApplicationContext(); LayoutInflater mflayout = getLayoutInflater(); View view = mflayout.inflate(R.layout.popupwindow, null); PopupWindow mPopupWindow = new PopupWindow(view, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); //mPopupWindow.setBackgroundDrawable(null); //mPopupWindow.setFocusable(true); //获得焦点 //不知道为什么,最后还是不响应onkey事件,用下面的方法可以 view.setFocusableInTouchMode(true);//view是创建pop的子view view.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { return false; } });

3、采用service上面,通过intent,弹出一个Activity菜单

这个也是我所使用的办法,直接上参考代码吧:

AndroidManifest.xml

<activity android:name="MainActivity" android:theme="@android:style/Theme.Dialog"> <intent-filter> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>

java代码:

Context mContext = getApplicationContext(); Intent activityIntent = new Intent(mContext, MainActivity.class); activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //activityIntent.putExtra("mCurKeyboard", mCurKeyboard); Bundle mBundle = new Bundle(); mBundle.putInt("mCurKeyboard", 1); activityIntent.putExtras(mBundle); mContext.startActivity(activityIntent);

只是简单的一个思路,具体的细节,在实现的时候可以上网看看例子。

更多相关文章

  1. Android(安卓)Studio 里搭建自动化测试框架Robotium
  2. Android(安卓)SQLite数据库应用技巧分享
  3. android:onClick都做了什么
  4. AutoCompleteTextView(自动完成文本框)
  5. Android中自定义SeekBar来控制音量,并与系统音量键的操作保持同步
  6. textview中加链接
  7. 从Alarm看Android上层UI到内核代码的流程分析
  8. Android(安卓)toolbar overflow菜单 文字显示不全
  9. Android(安卓)中的WiFi学习笔记----WIFI启动 代码流程走读---网

随机推荐

  1. Android常用的颜色列表,color.xml
  2. Android 通过广播获取网络状态
  3. android 获取HOME组件的Activity信息
  4. 手机服务方面的小技巧集合
  5. android中Sensor 工作流程
  6. SQLiteOpenHelper数据库操作
  7. android使用webview时按后退退出的问题
  8. android edittext获取选中文字
  9. 修改Android中Layout布局文件字体的大小
  10. [Android]判断当前界面是否是桌面