android (13) Fragment使用下

來源:互聯網
上載者:User

標籤:hid   保持資料   this   沒有   contain   資料   interface   tran   size   

一.Fragment使用:

    要在你的activity中管理Fragment,須要使用FragmentManager,能夠通過getFragmentManager(),這裡注意要是在v4包要用getSupportFragmentManager()方法。

FragmentManager能夠開一個事物調用beginTransaction()方法返回FragmentTransaction對象,這是我們能夠用FragmentTransaction去運行刪除添加Fragment的一些操作:

(1).add():往activity加入一個Fragment。


(2).remove():從Activity移除一個Fragment,當這個Fragment沒有加入進回退棧,則會被銷毀。

當加入進入回退棧之後則會銷毀視圖層,在顯示這個Fragment則會調用onDestoryView和onCreateView。


(3).replace():使用還有一個Fragment替換當前的Fragment,也就是remove操作和add合體運行。


(4).hide():隱藏當前的Fragment,不過設為不可見,並不會銷毀。


(5).show():顯示之前隱藏的Fragment。


(6).detach():會將view從UI中移除,和remove()不同,此時fragment的狀態依舊由FragmentManager維護。


(7).attach():重建view視圖。附加到UI上並顯示。


(8).addToBackStack():加入Fragment事務到回退棧中。

傳null表示當前Fragment。


(9).commit():提交事務。


注意當以使用了add加入Fragment之後,你不過想隱藏Fragment,並且保持當前Fragment輸入的資料,你只須要用hide(),假設你不想使用者在看到資料,直接使用replace()比使用add()在remove()方便的多。

二.怎樣使用回退棧保持資料:

實現效果,當進入第一個Fragment後點擊改變文字button,會把顯示在螢幕中央的TextView內容改變,然後點擊進入第二個Fragment,在點擊返回button,螢幕中央的TextView內容會還原成未改變前的,這就是說明了退回棧把Fragment的視圖銷毀了,可是執行個體並沒有銷毀。假設你想要不把資料也銷毀,則就像上面說的使用hide()和show().

圖片就不上傳了。大家但是自行測試原始碼(要原始碼留下郵箱,這個是在上篇文章基礎上改動的):

主Activity:

public class MainActivity extends Activity  {RelativeLayout r1;RelativeLayout r2;RelativeLayout r3;RelativeLayout view = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.bottom_layout);r1 = (RelativeLayout) findViewById(R.id.layout1);r2 = (RelativeLayout) findViewById(R.id.layout2);r3 = (RelativeLayout) findViewById(R.id.layout3);setDefaultFragment();}private void setDefaultFragment() {FragmentManager fm = getFragmentManager();FragmentTransaction transaction = fm.beginTransaction();MyFragment my = new MyFragment();transaction.add(R.id.frame_layout1, my,"ONE");transaction.addToBackStack(null);transaction.commit();}}

Fragment1:

public class MyFragment extends Fragment implements OnClickListener {private Button button1;private Button button2;private TextView textView1;@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {System.out.println("onCreateView");View view = inflater.inflate(R.layout.fragment_1, container, false);button1 = (Button) view.findViewById(R.id.button1);button1.setOnClickListener(this);button2 = (Button) view.findViewById(R.id.button2);button2.setOnClickListener(this);textView1 = (TextView) view.findViewById(R.id.textView1);return view;}@Overridepublic void onClick(View arg0) {switch (arg0.getId()) {case R.id.button1:textView1.append("哈");break;case R.id.button2:MyFragment2 f2 = new MyFragment2();FragmentManager fm = getFragmentManager();FragmentTransaction tx = fm.beginTransaction();tx.replace(R.id.frame_layout1, f2, "TWO");tx.addToBackStack(null);tx.commit();break;}}}

Fragment2:

public class MyFragment2 extends Fragment implements OnClickListener {private Button button1;private Button button2;private TextView textView1;@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {System.out.println("onCreateView");View view = inflater.inflate(R.layout.fragment_2, container, false);button1 = (Button) view.findViewById(R.id.button11);button1.setOnClickListener(this);button2 = (Button) view.findViewById(R.id.button21);button2.setOnClickListener(this);textView1 = (TextView) view.findViewById(R.id.textView2);return view;}@Overridepublic void onClick(View arg0) {switch (arg0.getId()) {case R.id.button11:textView1.append("哈");break;case R.id.button21:MyFragment3 f3 = new MyFragment3();FragmentManager fm = getFragmentManager();FragmentTransaction tx = fm.beginTransaction();tx.hide(this);tx.add(R.id.frame_layout1, f3, "THREE");// tx.replace(R.id.id_content, fThree, "THREE");tx.addToBackStack(null);tx.commit();break;}}}
Fragment1布局:

<?xml version="1.0" encoding="utf-8"?

><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="第一個頁面" /> <Button android:id="@+id/button1" android:layout_width="fill_parent" android:layout_height="40dp" android:text="改變文字" /> <Button android:id="@+id/button2" android:layout_width="fill_parent" android:layout_height="40dp" android:layout_below="@id/button1" android:text="跳轉第二個介面" /> </RelativeLayout>


Fragment3:

public class MyFragment3 extends Fragment{    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,    Bundle savedInstanceState) {    return inflater.inflate(R.layout.fragment_3, container, false);    }}

這樣就ok了。


三.Activity與Fragment之間的回調:

由於要考慮Fragment的反覆使用,所以必須減少Fragment與Activity的耦合,並且Fragment更不應該直接操作別的Fragment,畢竟Fragment操作應該由它的管理者Activity來決定。


就用上邊的範例,第一種回調:

public class MyFragment extends Fragment implements OnClickListener {private Button button1;private Button button2;private TextView textView1;@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {System.out.println("onCreateView");View view = inflater.inflate(R.layout.fragment_1, container, false);button1 = (Button) view.findViewById(R.id.button1);button1.setOnClickListener(this);button2 = (Button) view.findViewById(R.id.button2);button2.setOnClickListener(this);textView1 = (TextView) view.findViewById(R.id.textView1);return view;}public interface MyFragmentOneClick{void onMyOneBtnClick();  }@Overridepublic void onClick(View arg0) {switch (arg0.getId()) {case R.id.button1:textView1.append("哈");break;case R.id.button2://第一種回調方式if (getActivity() instanceof MyFragmentOneClick)          {              ((MyFragmentOneClick) getActivity()).onMyOneBtnClick();          }  break;}}}


另外一種回調:

public class MyFragment2 extends Fragment implements OnClickListener {private Button button1;private Button button2;private TextView textView1;private MyFragmentTwoClick myFragmentTwoClick ;@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {System.out.println("onCreateView");View view = inflater.inflate(R.layout.fragment_2, container, false);button1 = (Button) view.findViewById(R.id.button11);button1.setOnClickListener(this);button2 = (Button) view.findViewById(R.id.button21);button2.setOnClickListener(this);textView1 = (TextView) view.findViewById(R.id.textView2);return view;}public interface MyFragmentTwoClick{void onMyTwoBtnClick();  }//另外一種回調方式。設定回調介面      public void setMyTwoBtnClickListener(MyFragmentTwoClick myFragmentTwoClick)      {          this.myFragmentTwoClick = myFragmentTwoClick;      }  @Overridepublic void onClick(View arg0) {switch (arg0.getId()) {case R.id.button11:textView1.append("哈");break;case R.id.button21:if(myFragmentTwoClick != null)          {  myFragmentTwoClick.onMyTwoBtnClick();          }  break;}}}

主Activity實現:


public class MainActivity extends Activity implements MyFragmentOneClick,MyFragmentTwoClick {RelativeLayout r1;RelativeLayout r2;RelativeLayout r3;RelativeLayout view = null;MyFragment f1; MyFragment2 f2 ;MyFragment3 f3; @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.bottom_layout);r1 = (RelativeLayout) findViewById(R.id.layout1);r2 = (RelativeLayout) findViewById(R.id.layout2);r3 = (RelativeLayout) findViewById(R.id.layout3);setDefaultFragment();}private void setDefaultFragment() {FragmentManager fm = getFragmentManager();FragmentTransaction transaction = fm.beginTransaction();f1 = new MyFragment();transaction.add(R.id.frame_layout1, f1,"ONE");transaction.addToBackStack(null);transaction.commit();}@Overridepublic void onMyOneBtnClick() {if (f2 == null)          {  f2 = new MyFragment2();  f2.setMyTwoBtnClickListener(this);          }  FragmentManager fm = getFragmentManager();FragmentTransaction tx = fm.beginTransaction();tx.replace(R.id.frame_layout1, f2, "TWO");tx.addToBackStack(null);tx.commit();}@Overridepublic void onMyTwoBtnClick() {if (f3 == null)          {  f3 = new MyFragment3();            }  FragmentManager fm = getFragmentManager();FragmentTransaction tx = fm.beginTransaction();tx.hide(f2);tx.add(R.id.frame_layout1, f3, "THREE");tx.addToBackStack(null);tx.commit();}}
這樣也實現了上述的功能。




    


   

android (13) Fragment使用下

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.