Android編程使用Fragment介面向下跳轉並一級級返回的實現方法_Android

來源:互聯網
上載者:User

本文執行個體講述了Android編程使用Fragment介面向下跳轉並一級級返回的實現方法。分享給大家供大家參考,具體如下:

1.首先貼上項目結構圖:

2.先添加一個介面檔案BackHandledInterface.java,定義一個setSelectedFragment方法用於設定當前載入的Fragment在棧頂,主介面MainActivity須實現此介面,代碼如下:

package com.example.testdemo;public interface BackHandledInterface {  public abstract void setSelectedFragment(BackHandledFragment selectedFragment);}

3.定義一個抽象類別BackHandledFragment繼承自Fragment,後面跳轉的Fragment介面都要繼承自BackHandledFragment。抽象類別BackHandledFragment中定義一個傳回值為boolean類型的onBackPressed方法,用於處理點擊返回按鍵(物理Back鍵)時的邏輯,若該方法返回false,表示當前Fragment不消費返回事件,而由Fragment所屬的FragmentActivity來處理這個事件。代碼如下:

package com.example.testdemo;import android.os.Bundle;import android.support.v4.app.Fragment;public abstract class BackHandledFragment extends Fragment {  protected BackHandledInterface mBackHandledInterface;  /**   * 所有繼承BackHandledFragment的子類都將在這個方法中實現物理Back鍵按下後的邏輯   */  protected abstract boolean onBackPressed();  @Override  public void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    if (!(getActivity() instanceof BackHandledInterface)) {      throw new ClassCastException(          "Hosting Activity must implement BackHandledInterface");    } else {      this.mBackHandledInterface = (BackHandledInterface) getActivity();    }  }  @Override  public void onStart() {    super.onStart();    // 告訴FragmentActivity,當前Fragment在棧頂    mBackHandledInterface.setSelectedFragment(this);  }}

4.主介面MainActivity要繼承FragmentActivity才能調用getSupportFragmentManager()方法來處理Fragment。MainActivity還需重寫onBackPressed方法用來捕捉返回鍵(Back Key)事件,代碼如下:

package com.example.testdemo;import android.os.Bundle;import android.support.v4.app.FragmentActivity;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentTransaction;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends FragmentActivity implements    BackHandledInterface {  private static MainActivity mInstance;  private BackHandledFragment mBackHandedFragment;  private Button btnSecond;  @Override  public void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    btnSecond = (Button) findViewById(R.id.btnSecond);    btnSecond.setOnClickListener(new OnClickListener() {      @Override      public void onClick(View v) {        FirstFragment first = new FirstFragment();        loadFragment(first);        btnSecond.setVisibility(View.GONE);      }    });  }  public static MainActivity getInstance() {    if (mInstance == null) {      mInstance = new MainActivity();    }    return mInstance;  }  public void loadFragment(BackHandledFragment fragment) {    BackHandledFragment second = fragment;    FragmentManager fm = getSupportFragmentManager();    FragmentTransaction ft = fm.beginTransaction();    ft.replace(R.id.firstFragment, second, "other");    ft.addToBackStack("tag");    ft.commit();  }  @Override  public void setSelectedFragment(BackHandledFragment selectedFragment) {    this.mBackHandedFragment = selectedFragment;  }  @Override  public void onBackPressed() {    if (mBackHandedFragment == null || !mBackHandedFragment.onBackPressed()) {      if (getSupportFragmentManager().getBackStackEntryCount() == 0) {        super.onBackPressed();      } else {        if (getSupportFragmentManager().getBackStackEntryCount() == 1) {          btnSecond.setVisibility(View.VISIBLE);        }        getSupportFragmentManager().popBackStack();      }    }  }}

5.分別添加兩個子級Fragment,FirstFragment.java和SecondFragment.java,代碼分別如下:

FirstFragment.java:

package com.example.testdemo;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentTransaction;import android.view.LayoutInflater;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup;import android.widget.Button;public class FirstFragment extends BackHandledFragment {  private View myView;  private Button btnSecond;  @Override  public View onCreateView(LayoutInflater inflater,      @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {    myView = inflater.inflate(R.layout.fragment_first, null);    initView();    return myView;  }  private void initView() {    btnSecond = (Button) myView.findViewById(R.id.btnSecond);    btnSecond.setOnClickListener(new OnClickListener() {      @Override      public void onClick(View v) {        SecondFragment second = new SecondFragment();        FragmentManager fm = getFragmentManager();        FragmentTransaction ft = fm.beginTransaction();        ft.replace(R.id.firstFragment, second);        ft.addToBackStack("tag");        ft.commit();      }    });  }  @Override  protected boolean onBackPressed() {    return false;  }}

SecondFragment.java:

package com.example.testdemo;import android.os.Bundle;import android.support.annotation.Nullable;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class SecondFragment extends BackHandledFragment {  private View mView;  @Override  public View onCreateView(LayoutInflater inflater,      @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {    mView = inflater.inflate(R.layout.fragment_second, null);    return mView;  }  @Override  protected boolean onBackPressed() {    return false;  }}

6.三個布局檔案代碼如下:

activity_main.xml:

<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:orientation="vertical" >  <TextView    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_centerInParent="true"    android:text="FragmentActivity 父介面"    android:textSize="26sp" />  <Button    android:id="@+id/btnSecond"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_alignParentBottom="true"    android:text="跳轉到FirstFragment" />  <FrameLayout    android:id="@+id/firstFragment"    android:layout_width="match_parent"    android:layout_height="match_parent" >  </FrameLayout></RelativeLayout>

fragment_first.xml:

<?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:background="#e5e5e5"  android:orientation="vertical" >  <TextView    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_centerInParent="true"    android:text="FirstFragment"    android:textColor="#000000"    android:textSize="26sp" />  <Button    android:id="@+id/btnSecond"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_alignParentBottom="true"    android:text="開啟SecondFragment" /></RelativeLayout>

fragment_second.xml:

<?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:background="#e5e5e5"  android:orientation="vertical" >  <TextView    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_centerInParent="true"    android:text="SecondFragment"    android:textColor="#000000"    android:textSize="26sp" /></RelativeLayout>

7.最後奉上執行個體連結:

完整執行個體代碼代碼點擊此處本站下載。

希望本文所述對大家Android程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.