Android EditText隨輸入法一起移動并懸浮在輸入法之上的示例代碼
好習慣,先上圖
今天在做作業的時候有這樣一種需求,評論功能頁面需要仿QQ或者微博類似的頁面布局,Edittext固定底部,但是又能懸浮在輸入法之上。百度看了好多代碼,又是寫監聽改變布局,又是動態調整輸入框的位置,很高級,但是我嘗試都沒有效果,也不知道是我手機的原因還是不會用人家的代碼,沒辦法,自己動手研究。
研究結果:
一共三個點
1.文件AndroidManifest.xml里
當前頁面的activity標簽里加這個
android:windowSoftInputMode='adjustResize'
意思是Activity主窗口總是被調整屏幕的大小以便留出軟鍵盤的空間
例如
<activity android:name='.MainActivity' android:windowSoftInputMode='adjustResize'></activity>
2.布局里設置
加如下四句話在你的代碼里,至于添加位置,類比上面面的代碼塊,應該容易懂
(1)RelativeLayout
//根目錄需要相對布局,其他的沒嘗試
(2)android:fitsSystemWindows='true'
下面這是一位大佬的解釋,我粘過來方便理解
fitsSystemWindows屬性可以讓view根據系統窗口來調整自己的布局;簡單點說就是我們在設置應用布局時是否考慮系統窗口布局,這里系統窗口包括系統狀態欄、導航欄、輸入法等,包括一些手機系統帶有的底部虛擬按鍵。
android:fitsSystemWindows=”true” (觸發View的padding屬性來給系統窗口留出空間) 這個屬性可以給任何view設置,只要設置了這個屬性此view的其他所有padding屬性失效,同時該屬性的生效條件是只有在設置了透明狀態欄(StatusBar)或者導航欄(NavigationBar)此屬性才會生效
(3)android:layout_marginTop='-25dp' (注意是 負 25)
這解釋一下為什么要加這個,如果你應用的地方不需要沉浸式狀態欄,就可以去掉這句
如果你需要的是沉浸式狀態欄,上面的android:fitsSystemWindows='true'設置之后你的狀態欄就會變成一個白條,原來的效果會失效,我自己的小想法,直接讓根目錄延伸到屏幕頂部,充滿狀態欄,完事就可以了,經嘗試發現狀態欄高度為25dp,然后讓根布局往上延伸25dp,
這里想要延伸到狀態欄還是需要讓狀態欄透明,才能看見效果,所以在java代碼里需要加入一個小改動。
(4)android:layout_alignParentBottom='true'
將需要隨輸入法移動的控件固定根布局底部,究竟為啥,咱嘗試出來的也搞不懂,反正能用
//這里采用了相對布局作為根布局占滿全屏,其他都沒試過,想要其他布局直接放到這個里面,就不多說了//紅色標記的四個地方要有
<RelativeLayout xmlns:android='http://schemas.android.com/apk/res/android' xmlns:tools='http://schemas.android.com/tools' android:layout_width='match_parent' android:layout_height='match_parent' android:fitsSystemWindows='true' android:layout_marginTop='-25dp' tools:context='.MainActivity'> //這里的布局可以任意,也可以直接是控件,但是必須要有android:layout_alignParentBottom='true'固定在父布局底部 <RelativeLayoutandroid:id='@+id/lookm_bottombar'android:layout_width='match_parent'android:layout_height='50dp'android:layout_alignParentBottom='true'android:padding='5dp'><EditText android:id='@+id/lookm_chatedit' android:layout_width='match_parent' android:layout_height='match_parent' android:layout_marginRight='70dp' android:padding='5dp' android:hint='說點什么吧' android:textSize='13dp' android:maxLength='500' /><Button android:id='@+id/lookm_sendbutton' android:layout_width='65dp' android:layout_height='40dp' android:layout_alignParentRight='true' android:text='留言' /> </RelativeLayout></RelativeLayout>
3.java代碼里加入一個這小方法設置狀態欄透明,如果狀態欄不透明,那沉浸式狀態欄就不起作用了,狀態欄會采用應用默認顏色,很不舒服
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setStatusBar(); } //設置狀態欄為透明 protected void setStatusBar() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } }}
總結
到此這篇關于Android EditText隨輸入法一起移動并懸浮在輸入法之上的文章就介紹到這了,更多相關Android EditText懸浮在輸入法之上內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: