Android開發筆記(10)——使用Fragment傳遞,androidfragment
轉載請註明:http://www.cnblogs.com/igoslly/p/6911165.html
由於最近廢寢忘食地在開發App,沒來得及及時做總結,沒有用很進階的組件,勉強也使用一些功能完成了自己的第一個App,撒花~~~
接下來都是自己在開發中使用後的一些經驗,也是和他人學習實踐後的成果,主要是關於Fragment。
/* 添加Fragment有靜態添加 & 動態添加兩種方式 * 靜態是在Layout布局中添加<Fragment>控制項 * 由於可以設定id,則可通過id尋找 */<Fragment android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/fragment1"/>/* 動態添加fragment則完全在程式中定義添加 * 添加同時設定TAG,通過TAG尋找執行個體(見後Transaction) */// 對activity中的Fragment進行管理,需要通過Fragment ManagerFragmentManager manager = getFragmentManager();manager.findFragmentById(); //根據ID尋找manager.findFragmentByTag();//根據TAG尋找manager.getFragments();//擷取所有被ADD進Activity中的Fragment /*對當前的Fragment進行管理,使用FragmentTransaction *Transcation則控制Fragment的顯示、添加、替換等等,如add/remove/replace *commit()對操作的Fragemnt提交到系統,進行顯示 */
replace(R.id.content_frame,fragment).commit(); //替換——刪除添加操作
add(R.id.container,fragment1,String tag); //添加fragment,並設定動態尋找TAG
remove(fragment1); //刪除
/* 故而Fragment常被用於導覽列的切換內容 * 每點擊導覽列不同表徵圖,系統便調用響應的Fragment布局和內容,較為方便
========================================================================================================== * Activity或Fragment向Fragment之間的參數傳遞*/Bundle args = new Bundle();args.put("value_key",value);//value_key是在傳輸讀取中約定的關鍵詞//傳輸值可以為多種類型,int,String,Array等等Fragment fragment = new Fragment();fragment.setArguments(args); //將bundle傳給fragment//fragment讀取值red = getArguments().getInt("value_key1");yellow = getArguments().getString("value_key2");//==========================================================================================================
//當需要從Fragment返回原活動時,需要設定fragment串連aheadDialogue.setTargetFragment(CompetitionFragment.this,REQUEST_CODE);getFragmentManager().beginTransaction().replace(R.id.content_frame, fragment1).addToBackStack(null).commit();getFragmentManager().popBackStack(); //返回//原Fragment接收傳回值,在onActivityResult進行定義//request_code是使用者自訂integer//resultCode通常是活動狀況,是否正常結束public void onActivityResult(int requestCode, int resultCode, Intent data) {// super.onActivityResult(requestCode, resultCode, data);// 可判斷不同requestCode接受不同傳回值操作 if (requestCode==0x1001) { if (resultCode != Activity.RESULT_OK) { //這裡再對activity狀態進行判斷 return; } else { hitPlayer = data.getStringExtra("hitplayer"); hitNumber = data.getIntExtra("hitnumber", 0); } } if (requestCode==0x1111) { //blablabla } }
推薦介紹Fragment挺詳細的blog:http://blog.csdn.net/harvic880925/article/details/44927375
本筆記內容均為個人學習整理,轉載請註明部落格園-igoslly