1. 程式人生 > 程式設計 >android 實現按鈕浮動在鍵盤上方的例項程式碼

android 實現按鈕浮動在鍵盤上方的例項程式碼

大家好,我是夢辛工作室的靈,最近在幫客戶修改安卓程式時,有要求到一個按鈕要浮動在鍵盤的上方,下面大概講一下實現方法:

其實很簡單,分三步走

第一步 獲取當前螢幕的高度

 Display defaultDisplay = mcontext.getWindowManager().getDefaultDisplay();
   Point point = new Point();
   defaultDisplay.getSize(point);
   height = point.y;

第二步 獲取當前螢幕可見區域的高度,用於判斷當前鍵盤是否隱藏或顯示

public void setFloatView(View root,View floatview){
  this.root = root; //根節點
  listener = new ViewTreeObserver.OnGlobalLayoutListener() {
   @Override
   public void onGlobalLayout() {
    Rect r = new Rect();
    mcontext.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
    int heightDifference = height - (r.bottom - r.top); // 實際高度減去可檢視高度即是鍵盤高度
    boolean isKeyboardShowing = heightDifference > height / 3;
    if(isKeyboardShowing){
     //鍵盤顯示 
    }else{
     //鍵盤隱藏 
    }
   }
  };
  root.getViewTreeObserver().addOnGlobalLayoutListener(listener);
 }

第三步 當鍵盤隱藏時讓按鈕 動畫移動至原有位置,當前鍵盤顯示時讓按鈕動畫移動至當前鍵盤的高度上方

 if(isKeyboardShowing){
     //鍵盤顯示
     floatview.animate().translationY(-heightDifference).setDuration(0).start();
    }else{
     //鍵盤隱藏
     floatview.animate().translationY(0).start();
    }

然後我為了方便封裝了一個工具類 FloatBtnUtil,很好用,下面是程式碼

/**
 * 夢辛靈 實現按鈕浮動工具
 */
public class FloatBtnUtil {

 private static int height = 0;
 private Activity mcontext;
 private ViewTreeObserver.OnGlobalLayoutListener listener;
 private View root;

 public FloatBtnUtil(Activity mcontext){
  this.mcontext = mcontext;
  if (height == 0){
   Display defaultDisplay = mcontext.getWindowManager().getDefaultDisplay();
   Point point = new Point();
   defaultDisplay.getSize(point);
   height = point.y;
  }
 }

 public void setFloatView(View root,View floatview){
  this.root = root; //檢視根節點 floatview // 需要顯示在鍵盤上的View元件
  listener = new ViewTreeObserver.OnGlobalLayoutListener() {
   @Override
   public void onGlobalLayout() {
    Rect r = new Rect();
    mcontext.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
    int heightDifference = height - (r.bottom - r.top);
    boolean isKeyboardShowing = heightDifference > height / 3;
    if(isKeyboardShowing){
     floatview.animate().translationY(-heightDifference).setDuration(0).start();
    }else{
     floatview.animate().translationY(0).start();
    }
   }
  };
  root.getViewTreeObserver().addOnGlobalLayoutListener(listener);
 }

 public void clearFloatView(){
  if (listener != null && root != null)
  root.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
 }

}

下面是使用程式碼:

 private void initFloatBtn() {
  FloatBtnUtil floatBtnUtil = new FloatBtnUtil(this);
  LinearLayout lin_bottom = (LinearLayout) this.findViewById(R.id.lin_bottom);
  LinearLayout lin_root = (LinearLayout)this.findViewById(R.id.lin_root);
  floatBtnUtil.setFloatView(lin_root,lin_bottom);
 }

總結

到此這篇關於android 實現按鈕浮動在鍵盤上方的文章就介紹到這了,更多相關android 實現按鈕浮動在鍵盤上方內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!