[Android學習筆記]fragment配合RadioGroup實現點擊切換內容

來源:互聯網
上載者:User

這個主要是如何替換fragment的demo。如下(下面的tabhost和上面的bar不屬於這次的內容,這個是我做的一個應用程式架構的一部分,有需要的或者想研究研究的可以私下聯絡),主要是講解中間的內容怎麼實現,即點擊上面的RadioGroup,下面的內容一起改變(改變的是XML中的布局,這樣的話下面三個的布局完全可以自己定義)

1.首先在主介面的xml中添加一個RadioGroup,裡面添加三個RadioButton即可

<RadioGroup                android:id="@+id/radioGroup1"                style="@style/layout_full"                android:layout_margin="5dp"                android:background="@drawable/rounded_edittext"                android:orientation="horizontal"                android:padding="5dp" >                <RadioButton                    android:id="@+id/radio0"                    style="@style/layout_horizontal"                    android:layout_gravity="center_horizontal"                    android:layout_weight="1"                    android:checked="true"                    android:text="均分" />                <RadioButton                    android:id="@+id/radio1"                    style="@style/layout_horizontal"                    android:layout_gravity="center_horizontal"                    android:layout_weight="1"                    android:text="個人" />                <RadioButton                    android:id="@+id/radio2"                    style="@style/layout_horizontal"                    android:layout_gravity="center"                    android:layout_weight="1"                    android:text="借貸" />            </RadioGroup>

其中

android:background="@drawable/rounded_edittext"

這一句是給這個RadioGroup添加一個帶圓角的邊框 

rounded_edittext.xml的代碼如下

<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"    android:shape="rectangle" >    <solid android:color="#ffffff" />    <corners android:radius="7dip" />    <stroke        android:width="2px"        android:color="#000000" /></shape>

放置在drawable檔案夾下即可

2.下面的內容由三個xml定義好的布局來呈現,這三個xml的布局可以自己來寫 ,我就很簡單地建了三個,做例子用

speeddial_fragment_pay1.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:layout_margin="5dp"    android:background="@drawable/rounded_edittext"    android:orientation="vertical" >    <Button        android:id="@+id/Button04"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerHorizontal="true"        android:layout_centerVertical="true"        android:text="Button" /></RelativeLayout>

3.(重要)在主布局檔案中添加Fragment的載體,比如一個framlayout,負責承載fragment

在上面的RadioGroup的布局下增加:

<FrameLayout            android:id="@+id/fragment_container"            android:layout_width="match_parent"            android:layout_height="match_parent" />

這樣布局就完成了

4.由於Fragment的特性,我們要建立三個自己的Fragment,都繼承自Fragment 

SpeeddialFragmentOne.java

package com.gracker.fragment;import android.app.Fragment;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import com.gracker.tabactivity.R;public class SpeeddialFragmentOne extends Fragment {@Overridepublic void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// TODO Auto-generated method stubreturn inflater.inflate(R.layout.speeddial_fragment_pay1, container, false);}}

這個Fragment非常簡單,沒有添加任何的邏輯,僅僅只是在onCreateView的要布局然後以View返回。Fragment有很多方法,可以根據自己的需要進行重載,這裡就不多說了,自己到用的時候自然就知道了。

類似地,建立另外兩個Fragment ,改變的僅僅是

return inflater.inflate(R.layout.speeddial_fragment_pay1, container, false);

5.在主Activity中調用:

MainActivity.java

/** * 主Activity *  * @author Gracker Gao * @date 2012.8.15 */package com.gracker.hostactivity;import android.app.Activity;import android.app.FragmentTransaction;import android.os.Bundle;import android.util.Log;import android.widget.RadioGroup;import android.widget.RadioGroup.OnCheckedChangeListener;import com.gracker.fragment.SpeeddialFragmentOne;import com.gracker.fragment.SpeeddialFragmentThree;import com.gracker.fragment.SpeeddialFragmentTwo;import com.gracker.tabactivity.R;public class MainActivity extends Activity {private final String TAG = "SpeedDialActivity";private RadioGroup mRadioGroup;private SpeeddialFragmentTwo mSpeeddialFragmentTwo;private SpeeddialFragmentOne mSpeeddialFragmentOne;private SpeeddialFragmentThree mSpeeddialFragmentThree;private FragmentTransaction transaction;public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.speeddial);init_date();setupWidgets();}private void init_date(){transaction = getFragmentManager().beginTransaction();if (null == mSpeeddialFragmentOne) {mSpeeddialFragmentOne = new SpeeddialFragmentOne();}transaction.add(R.id.fragment_container,mSpeeddialFragmentOne);// Commit the transactiontransaction.commit();}private void setupWidgets() {mRadioGroup = (RadioGroup) findViewById(R.id.radioGroup1);mRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(RadioGroup group, int checkedId) {// TODO Auto-generated method stubswitch (checkedId) {case R.id.radio0:Log.v(TAG, "setupWidgets():radio0 clicked");if (null == mSpeeddialFragmentOne) {mSpeeddialFragmentOne = new SpeeddialFragmentOne();}transaction = getFragmentManager().beginTransaction();transaction.replace(R.id.fragment_container,mSpeeddialFragmentOne);// Commit the transactiontransaction.commit();break;case R.id.radio1:Log.v(TAG, "setupWidgets():radio1 clicked");if (null == mSpeeddialFragmentTwo) {mSpeeddialFragmentTwo = new SpeeddialFragmentTwo();}transaction = getFragmentManager().beginTransaction();transaction.replace(R.id.fragment_container,mSpeeddialFragmentTwo);// Commit the transactiontransaction.commit();break;case R.id.radio2:Log.v(TAG, "setupWidgets():radio2 clicked");if (null == mSpeeddialFragmentThree) {mSpeeddialFragmentThree = new SpeeddialFragmentThree();}transaction = getFragmentManager().beginTransaction();transaction.replace(R.id.fragment_container,mSpeeddialFragmentThree);// Commit the transactiontransaction.commit();break;default:break;}}});}@Overrideprotected void onResume() {// TODO Auto-generated method stubsuper.onResume();}@Overrideprotected void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();// dataEncapsulation.closeDataBase_speedDial();}}

init_data()函數中主要是初始化值,包括初始化使用者第一個看到的Fragment

在RadioGroup的onCheckedChangeLinsteer中,切換Fragment。關於Fragment的一些操作,比如增加,刪除,替換等等,可以參照這個文章:http://www.eoeandroid.com/thread-71642-1-1.html 講的很詳細,我也不想重複。

這個Demo就不提供下載了,畢竟不是很難,所有的東西都交代了,自己敲一遍收穫總是比開啟別人的代碼來研究要好的多。

例子中有什麼錯誤的地方歡迎指正。

聯繫我們

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