最近因为项目需求,要在一个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. 从Alarm看Android上层UI到内核代码的流程分析
  2. Android toolbar overflow菜单 文字显示不全
  3. Android 中的WiFi学习笔记----WIFI启动 代码流程走读---网络连接
  4. 利用android proguard混淆代码
  5. Android Native代码中的status_t定义
  6. Android 混淆代码问题总结
  7. 在android中显示网络图片及查看页面源代码

随机推荐

  1. Android最佳实践之Material Design
  2. Android攻城狮—全套必备神级工具(开发,插
  3. Android简易聊天室软件(HTTP实现)
  4. Android(安卓)Hook框架Xposed详解:从源代
  5. Android数据储存——SharedPreferences储
  6. [Android(安卓)分享] APK权限大全
  7. RxJava漫谈-RxAndroid使用
  8. 修改最低版本minSdkVersion
  9. 解决NestedScrollView 嵌套 RecyclerView
  10. Android事件分发机制的探索与发现之总结