軟鍵盤
注釋:
原理就是根據當前布局所占屏幕總高度減去當前布局可視高度,一般剛進入Activity,這兩個高度相差不多,數值必定小於100,當軟鍵盤出現時,當前布局的可視高度會受到擠壓,兩者相減大於100(軟鍵盤一般大小差不多為總屏幕的4分之一,100是比較合適的數值)
但是有個問題就是,如果當前頁面可以滾動,在軟鍵盤消失后進行滾動,安卓會重新計算當前布局可視高度,默認為初始可視高度的值,如上的方法會連續閃現隱藏和show兩種不同狀態,可通過判斷只有走過show方法,才判斷hide方法為有效,可完美規避此類問題。
另外如果在fragment里需要對軟鍵盤消失監控,可通過在Activity里對hide和show的狀態發廣播,然后在需要的地方進行接收處理
1、配置文件中添加
<activity
android:name="com.resmanager.client.user.LoginActivity"
android:windowSoftInputMode="adjustResize"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:theme="@android:style/Theme.NoTitleBar" >
</activity>
2、Activity中
//該Activity的最外層Layout
final LinearLayout father = (LinearLayout) findViewById(R.id.father);// private LinearLayout activityRootView;
//給該layout設置監聽,監聽其布局發生變化事件
father.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
//比較Activity根布局與當前布局的大小
int heightDiff = father.getRootView().getHeight() - father.getHeight();
if (heightDiff > dpToPx(LoginActivity.this, 200)) { // if more than 200 dp, it's probably a keyboard...
// ... do something here
Log.d("TAG","aaaa");//顯示
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
lp.setMargins(0, 0, 0, 0);//left top right button
up.setLayoutParams(lp);
uptwo.setLayoutParams(lp);
hidden.setVisibility(View.GONE);
//上面代碼等價於:
//Android:layout_marginTop="0dip"
}else {
Log.d("TAG","bbbb");//消失
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
lp.setMargins(0,45, 0, 0);//left top right button
up.setLayoutParams(lp);
lp.setMargins(0, 50, 0, 0);
uptwo.setLayoutParams(lp);
hidden.setVisibility(View.VISIBLE);
}
}
});
public static float dpToPx(Context context, float valueInDp) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics);
}
3、Layout中
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="@+id/father"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="vertical"
android:layout_weight="12">
4、軟鍵盤出現后,即使沒操作也默認會把原來Activity的布局給頂上去了,感覺沒必要的話,可以配置文件中更改
android:windowSoftInputMode="adjustPan|stateHidden"
EditView
user_account_edit.setOnFocusChangeListener(new android.view.View.
OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
// 此處為得到焦點時的處理內容
} else {
// 此處為失去焦點時的處理內容
}
}
});
Android 如何在Java代碼中手動設置控件的marginleft
1、定義LayoutParams
|
1
|
LinearLayout.LayoutParams layoutParams =
new
LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//定義一個LayoutParams
|
2、在LayoutParams中設置marginLeft
|
1
|
layoutParams.setMargins(
20
,
0
,
0
,
0
);
//4個參數按順序分別是左上右下
|
3、把這個LayoutParams設置給控件
|
1
|
mView.setLayoutParams(layoutParams);
//mView是控件
|
