此博客用于给自己做笔记,仿微信评论弹出键盘,功能如下: 点击评论 按钮弹出键盘和布局,点击发送与其他地方或者物理返回键 关闭键盘与布局 整体代码: public class CommentActivity extends AppCompatActivity { private LinearLayout mLayout; private EditText mEdit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_comment); mLayout = (LinearLayout) findViewById(R.id.layout); mEdit = (EditText) findViewById(R.id.et_discuss); } public void onButtonClick(View view){ switch (view.getId()){ case R.id.comment: ShowKeyboard(); break; case R.id.tv_confirm: hideKeyboard(); break; case R.id.relativeLayout: hideKeyboard(); break; } } //显示布局与键盘 private void ShowKeyboard(){ mLayout.setVisibility(View.VISIBLE);//显示布局 InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0); } //隐藏键盘与布局 private void hideKeyboard(){ mLayout.setVisibility(View.GONE);//隐藏布局 mEdit.setText("");//清空输入 View view = getWindow().peekDecorView(); if (view != null) { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); } } // 捕获返回键的方法 @Override public boolean onKeyDown(int keyCode, KeyEvent event) { //隐藏键盘与布局 hideKeyboard(); return true; } }
布局代码:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.admin.newdemo.CommentActivity"> <Button android:id="@+id/comment" android:layout_width="90dp" android:layout_height="50dp" android:text="评论" android:onClick="onButtonClick" /> <RelativeLayout android:id="@+id/relativeLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:onClick="onButtonClick"> <LinearLayout android:id="@+id/layout" android:layout_width="match_parent" android:layout_height="45dp" android:background="#ffffff" android:gravity="center_vertical" android:orientation="horizontal" android:layout_alignParentBottom="true" android:visibility="gone"> <EditText android:id="@+id/et_discuss" android:layout_width="0dp" android:layout_height="30dp" android:layout_weight="1" android:hint="说点什么" android:textSize="14sp" android:textColor="#666666" android:singleLine="true" android:layout_marginRight="10dp" android:layout_marginLeft="10dp" android:paddingLeft="10dp" android:background="@drawable/comment_back" /> <TextView android:id="@+id/tv_confirm" android:text="发送" android:textSize="14sp" android:textColor="#666666" android:layout_marginRight="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="onButtonClick" > </TextView> </LinearLayout> </RelativeLayout> </RelativeLayout>
转载请标注。