Android(安卓)软键盘顶起布局相关
16lz
2021-01-24
原文链接:http://blog.csdn.net/mr_liu_gege/article/details/53169359
拾人牙慧,感谢博主分享。试验了一下,确实有效果,收藏学习。
第一种情况:被键盘遮住的按钮没有位于布局的底部
代码:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width= "match_parent"
- android:layout_height= "wrap_content"
- android:orientation= "vertical"
- android:id= "@+id/parent_ll">
-
- <EditText
- android:id= "@+id/username"
- android:layout_width= "match_parent"
- android:layout_height= "wrap_content"
- android:layout_marginTop= "200dp"
- android:ems= "10" >
- EditText>
-
- <EditText
- android:id= "@+id/userpwd"
- android:layout_width= "match_parent"
- android:layout_height= "wrap_content"
- android:layout_marginTop= "30dp"
- android:ems= "10"
- android:inputType= "textPassword" />
-
- <Button
- android:id= "@+id/btn"
- android:layout_width= "wrap_content"
- android:layout_height= "wrap_content"
- android:layout_gravity= "center"
- android:layout_marginTop= "30dp"
- android:text= "Button" />
-
- LinearLayout>
- public class MainActivity extends Activity {
- private Button btn;
- private LinearLayout parent_ll;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.layout_login);
- /*ScrollView mScrollView = (ScrollView)findViewById(R.id.scrollContent);
- mScrollView.setVerticalScrollBarEnabled(false);
- mScrollView.setHorizontalScrollBarEnabled(false);*/
- parent_ll=(LinearLayout) findViewById(R.id.parent_ll);
- btn=(Button) findViewById(R.id.btn);
- addLayoutListener(parent_ll, btn);
- }
-
- /**
- * 1、获取parentView在窗体的可视区域
- * 2、获取parentView在窗体的不可视区域高度
- * 3、判断不可视区域高度
- * 1、大于100:键盘显示 获取childView的窗体坐标
- * 算出parentView需要滚动的高度,使childView显示。
- * 2、小于100:键盘隐藏
- *
- * @param parentView 根布局
- * @param childView 需要显示的最下方View
- */
- public void addLayoutListener(final View parentView, final View childView) {
- parentView.getViewTreeObserver().addOnGlobalLayoutListener( new ViewTreeObserver.OnGlobalLayoutListener() {
- @Override
- public void onGlobalLayout() {
- Rect rect = new Rect();
- parentView.getWindowVisibleDisplayFrame(rect);
- int mainInvisibleHeight = parentView.getRootView().getHeight() - rect.bottom;
- if (mainInvisibleHeight > 100) {
- int[] location = new int[ 2];
- childView.getLocationInWindow(location);
- int srollHeight = (location[ 1] + childView.getHeight()) - rect.bottom;
- parentView.scrollTo( 0, srollHeight);
- } else {
- parentView.scrollTo( 0, 0);
- }
- }
- });
- }
- }
addLayoutListener() 这个方法是关键。 第二种情况:被键盘遮住的按钮位于布局的底部
父布局需要是Relativelayout,按钮需要alignParentBottom,可能清单文件还需要设置android:windowSoftInputMode
更多相关文章
- 《Android(安卓)UI基础教程》之读书笔记
- [android]如何使LinearLayout布局从右向左水平排列,而不是从左向
- 【android】小知识点整理qwq(三)
- android夜间模式的实现
- Android键盘的显示与隐藏
- Android(安卓)Material Design(一)史上最全的材料设计控件大全
- 解决webview中输入框完成输入隐藏键盘后滑动界面又弹出软键盘问
- Android(安卓)M新控件知识整理
- Android(安卓)多点触控屏蔽