Android學習筆記(十六)——片段之間進行互動(附源碼)

來源:互聯網
上載者:User

片段之間進行互動


點擊下載源碼


很多時候,一個活動中包含一個或者多個片段,它們彼此協作,向使用者展示一個一致的UI。在這種情況下,片段之間能進行通訊並交換資料十分重要。


1、使用上一篇中建立的同一個項目,在fragment.xml中添加TextView的標識id:

        android:id="@+id/lblFragment1"

2、在fragment2.xml中添加一個Button,用於與fragment1進行互動:

    

3、將兩個片段重新添加到main.xml中:

        

4、在FragmentsActivity.java中,注釋掉上一篇中添加的代碼,修改後如下:

@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);/*FragmentManager fragmentManager = getSupportFragmentManager();FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();//WindowManager windowManager = getWindowManager();Display display = windowManager.getDefaultDisplay();if (display.getWidth() > display.getHeight()) {//Fragment1 fragment1 = new Fragment1();fragmentTransaction.replace(android.R.id.content, fragment1);} else {//Fragment2 fragment2 = new Fragment2();fragmentTransaction.replace(android.R.id.content, fragment2);}fragmentTransaction.commit();*/}

5、在Fragment2.java中添加如下代碼,實現與Fragment1的互動:

@Overridepublic void onStart() {// TODO Auto-generated method stubsuper.onStart();Button btnGetText = (Button) getActivity().findViewById(R.id.btnGetText);btnGetText.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubTextView lbl = (TextView) getActivity().findViewById(R.id.lblFragment1);//通過getActivity()方法獲得當前嵌入了該片段的活動,再使用findViewById()定位該片段中包含的視圖Toast.makeText(getActivity(), lbl.getText(), Toast.LENGTH_SHORT).show();}});}

6、按F11調試應用程式,在右側的第二個片段中單擊按鈕,可以看到彈出一個訊息框,內容正是片段1中TextView的內容,說明擷取成功~



聯繫我們

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