Android 兩個Fragment之間傳遞資料執行個體詳解_Android

來源:互聯網
上載者:User

 Android 兩個Fragment之間如何傳遞資料

FragmentA啟動FragmentB,做一些選擇操作後,返回FragmentA,需要把FragmentB裡面選擇的資料傳回來。有什麼辦法?

Fragment之間不能直接通訊,必須通過Activity來完成,具體步驟。

1. 在FragmentA中定義通訊介面,通過該介面向Activity發送資料。

public class FragmentA extends Fragment {  private onButtonPressListener mListener;  @Override  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {    View view = inflater.inflate(R.layout.fragment_linmo_select_beitie, container, false);    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {      @Override      public void onItemClick(AdapterView<?> parent, View view, int position, long id) {        mListener.onOKButtonPressed(selectedBeitie);      }    });    return view;  }  @Override  public void onAttach(Activity activity) {    super.onAttach(activity);    try {      mListener = (onButtonPressListener) activity;    } catch (ClassCastException e) {      throw new ClassCastException(activity.toString() + " must implement onOkButtonPressed");    }  }  public interface onButtonPressListener {    void onOKButtonPressed(LinmoBeitieItem item);  }}

2. 在Activity中實現該介面,並通過該介面向FragmentB傳遞資料。

public class MainActivity extends Activity implements FragmentA.onButtonPressListener {  @Override  public void onOKButtonPressed(LinmoBeitieItem item) {    FragmentB fragmentB = (FragmentB)getFragmentManager().findFragmentById(R.id.container);    fragmentB.onBeitieSelected(item);  }}

3. FragmentB接收到資料並處理。

public class FragmentA extends Fragment {  public void onBeitieSelected(LinmoBeitieItem item) {    // ...  }}

感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!

聯繫我們

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