在实现一些IM页面,例如对话框,评论框时,常常会遇到键盘和表情panel显示/隐藏引起的闪屏问题。问题的根本原因是当键盘收起或弹出时,layout会发生变化,此时panel的高度的计算如果时机不对,那么会导致闪屏。
解决的办法有很多,这里提供一种重写onMeasure方法的实现:
使用方法:
mEditText = (EditText) findViewById(R.id.editText);
mPanel = (ViewGroup) findViewById(R.id.emotion_panel);
mCommentPanelLayout = (CommentPanelLayout) findViewById(R.id.comment_panel_layout);
mCommentPanelLayout.setListener(new CommentPanelLayout.SimpleListener() {
@Override
public void onKeyboardShow(View view) {
Log.d(TAG, "onKeyboardShow() called");
}
@Override
public void onKeyboardHide(View view) {
Log.d(TAG, "onKeyboardHide() called");
}
@Override
public void onPanelShow(View view) {
Log.d(TAG, "onPanelShow() called");
}
@Override
public void onPanelHide(View view) {
Log.d(TAG, "onPanelHide() called");
}
});
mCommentPanelLayout.setFocusTarget(mEditText); // 设定要监听的edittext
mCommentPanelLayout.setPanelView(mPanel); // 设定panel对象
findViewById(R.id.emotion_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mCommentPanelLayout.isKeyboardShown()) {
mCommentPanelLayout.switchToPanel();
} else if (mCommentPanelLayout.isPanelShown()){
mCommentPanelLayout.switchToKeyboard();
} else if (!mCommentPanelLayout.isKeyboardShown() && !mCommentPanelLayout.isPanelShown()){
mCommentPanelLayout.showPanel();
// mCommentPanelLayout.showKeyboard(); // 当什么都没弹起的时候,点击按钮显示panel或者keyboard
}
}
});
layout是这样的:
<your.package.CommentPanelLayout
app:layout_constraintBottom_toBottomOf="parent"
android:id="@+id/comment_panel_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/darker_gray">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="42dp"
android:gravity="center_vertical"
android:layout_toLeftOf="@+id/emotion_button"
android:hint="make a comment..."
android:paddingLeft="10dp"
android:paddingStart="10dp"/>
<Button
android:layout_alignParentEnd="true"
android:id="@+id/emotion_button"
android:text="emotion"
android:layout_width="wrap_content"
android:layout_height="42dp"/>
</RelativeLayout>
<RelativeLayout
android:visibility="gone"
android:id="@+id/emotion_panel"
android:layout_width="match_parent"
android:layout_height="150dp">
<Button
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a button"/>
</RelativeLayout>
</your.package.CommentPanelLayout>
源码如下所示: