Android側邊欄DrawerLayout實現問題筆記
阿新 • • 發佈:2019-01-26
關於DrawerLayout實現的側邊欄大家可以去Google官網查詢,已經很完善了。本章只記錄一些實現過程中遇到的問題,以後有時間會發布一篇複雜的DrawerLayout框架。
遇到的問題:
1.Fragment呼叫setArgyments(Bundle)的時候報錯:Fragment already active
原因:setArgyments在Fragment新增到FragmentManager後,再呼叫setArgyments會報錯。
例如:
fragment已經新增到FragmentManager中,此時再呼叫setArgyments則會報錯。fragment = new MyFragment(); Log.v("myu", "initView--->"+fragment.getId()); fragmentManager = getFragmentManager(); fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.add(R.id.content, fragment).commit(); fragment.setArguments(Bundle);
解決辦法:利用Getter和Setter方法,進行資料的獲取與儲存
例如:
public class MyFragment extends Fragment {
private TextView textView;
int data = 0;
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
...
}
在Activity中:
fragment.setData(position);
2.fragmentTransaction呼叫commit()的時候,報:commit already called
原因:一個FragmentTransaction物件,只能呼叫一次commit()。
解決:若需要再次提交實務,需要建立一個新的FragmentTransaction物件。用新的FragmentTransaction物件呼叫commit()方法。
3.關於ActionBar左上角按鈕:
4.不常用的Activity生命週期方法:onPostCreate(Bundle)//為ActionBar左上角圖示加上一個返回箭頭的圖示 getActionBar().setDisplayHomeAsUpEnabled(true); //使左上角圖示可以點選 getActionBar().setHomeButtonEnabled(true); //true:顯示左上角圖示 false:不顯示圖示,只顯示一個標題 getActionBar().setDisplayShowHomeEnabled(false);
Google文件解釋:
protected void onPostCreate (Bundle savedInstanceState)
Added in API level 1
Called when activity start-up is complete (after onStart() and onRestoreInstanceState(Bundle) have been called). Applications will generally not implement this method; it is intended for system classes to do final initialization after application code has run.
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
Parameters
savedInstanceState If the activity is being re-initialized after previously being shut down then this Bundle contains the data it most recently supplied in onSaveInstanceState(Bundle). Note: Otherwise it is null.
See Also
onCreate(Bundle)
不常用的生命週期方法,通常適用於應用程式執行後做最後的初始化。該方法在onStart( )和onRestoreInstanceState( )方法後執行。
5.關於onPrepareOptionsMenu(Menu menu):
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
當DrawerLayout的側邊欄需要和ActionBar的Menu相關聯時需要用到。例如側邊欄開啟/隱藏時,隱藏/顯示ActionBar的一些Item
它與onCreateOptionsMenu(Menu menu)的區別:
onCreateOptionsMenu只有在Menu剛建立的時候才呼叫,若以後向動態改變OptionMenu需要呼叫onPrepareOptionsMenu,而Android3.0以後如果要呼叫該方法需要呼叫
invalidateOptionsMenu(),然後系統會呼叫onPrepareOptionsMenu方法動態更新Menu