项目中需要出发带有EditText的Dialog显示,要求在编辑完EditText时,点击Dilog的空白处隐藏软键盘。但是Dialog不会消失。示例如下:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.panhouye.dialoginput"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".Main2Activity" android:theme="@style/Base.V7.Theme.AppCompat.Light.Dialog"></activity> </application> </manifest>
package com.panhouye.dialoginput; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.view.MotionEvent; import android.view.inputmethod.InputMethodManager; /** * Created by pamhouye on 2017/4/25 0025. */ public class BaseActivity extends AppCompatActivity { @Override public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub if(event.getAction() == MotionEvent.ACTION_DOWN){ if(getCurrentFocus()!=null && getCurrentFocus().getWindowToken()!=null){ InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } return super.onTouchEvent(event); } }
(2)MainActivity实现代码如下:
package com.panhouye.dialoginput; import android.content.Intent; import android.os.Bundle; import android.view.View; public class MainActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } //dialog按钮触发事件方法 public void dialog(View view){ Intent intent = new Intent(this,Main2Activity.class); startActivity(intent); } }
(3)Main2Activity作为dialog样式的Activity实现代码如下:
package com.panhouye.dialoginput; import android.os.Bundle; import android.view.Gravity; import android.view.Window; import android.view.WindowManager; public class Main2Activity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); //设置窗口对齐屏幕宽度 Window win = this.getWindow(); win.getDecorView().setPadding(0, 0, 0, 0); WindowManager.LayoutParams lp = win.getAttributes(); lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.height = WindowManager.LayoutParams.WRAP_CONTENT; lp.gravity = Gravity.CENTER;//设置对话框置顶显示 win.setAttributes(lp); //设置点击外部空白处可以关闭Activity this.setFinishOnTouchOutside(true); } }就这样一直肤浅下去喽,洗洗睡啦