Fragment解析建立和傳參,動態添加fragment,fragment

來源:互聯網
上載者:User

Fragment解析建立和傳參,動態添加fragment,fragment

一下是個人的一些總結。

為fragment建立XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              android:orientation="vertical"              android:layout_width="match_parent"              android:layout_height="match_parent">    <ListView            android:id="@+id/yulelist"            android:layout_width="match_parent"            android:layout_height="wrap_content"/></LinearLayout>
/然後建立一個類,這個類是繼承Fragment
public class Yule extends ListFragment {         @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {        return inflater.inflate(R.layout.yule,container,false);    }//主要就是載入我們剛剛寫好的fragment.xml布局檔案並返回


 

然後開啟或建立activity_main.xml作為主Activity的布局檔案,在裡面加入兩個Fragment的引用,使用android:name首碼來引用具體的Fragment:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:baselineAligned="false" >      <fragment         android:id="@+id/fragment1"         android:name="com.example.fragmentdemo.Fragment1"         android:layout_width="0dip"         android:layout_height="match_parent"         android:layout_weight="1" />      <fragment         android:id="@+id/fragment2"         android:name="com.example.fragmentdemo.Fragment2"         android:layout_width="0dip"         android:layout_height="match_parent"         android:layout_weight="1" />  </LinearLayout>  


 

動態添加fragment將activity_main.xml中的兩個fragmnet控制項刪除,只留下linearlayout布局。為這個布局設定一個id//將MainActivity中的代碼修改如下
public class MainActivity extends Activity {      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          //擷取螢幕尺寸        Display display = getWindowManager().getDefaultDisplay();          if (display.getWidth() > display.getHeight()) {             Fragment1 fragment1 = new Fragment1();             getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment1).commit();         } else {             Fragment2 fragment2 = new Fragment2();             getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment2).commit();         }     }  }

首先,我們要擷取螢幕的寬度和高度,然後進行判斷,如果螢幕寬度大於高度就添加fragment1,如果高度大於寬度就添加fragment2。動態添加Fragment主要分為4步:

1.擷取到FragmentManager,在Activity中可以直接通過getFragmentManager得到。

2.開啟一個事務,通過調用beginTransaction方法開啟。

3.向容器內加入Fragment,一般使用replace方法實現,需要傳入容器的id和Fragment的執行個體。

4.提交事務,調用commit方法提交。 //fragment的生命週期,與activity不同的onAttach方法:Fragment和Activity建立關聯的時候調用。
onCreateView方法:為Fragment載入布局時調用。
onActivityCreated方法:當Activity中的onCreate方法執行完後調用。
onDestroyView方法:Fragment中的布局被移除時調用。
onDetach方法:Fragment和Activity解除關聯的時候調用。


 

Fragment之間通訊:使用了介面傳參和getActivity兩種方式fragment1.xml布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              android:orientation="vertical"              android:layout_width="match_parent"              android:layout_height="match_parent">    <ListView            android:id="@+id/onelist"            android:layout_width="match_parent"            android:layout_height="wrap_content">    </ListView></LinearLayout>

fragment2.xml布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              android:orientation="vertical"              android:layout_width="match_parent"              android:layout_height="match_parent"              android:background="@android:color/holo_green_dark">    <TextView            android:layout_width="match_parent"            android:layout_height="match_parent"            android:text="555555555555555"            android:layout_weight="3"            android:id="@+id/one"/></LinearLayout>

fragment1:
public class Fragment1 extends Fragment implements AdapterView.OnItemClickListener{    private ListView listView;    private String str[]={"sssss","ddddd","ffffff","gggggg","hhhhhh","jj","mmmm"};//傳參介面    private OnHeadlineSelectedListener mOnHeadlineSelectedListener;    @Override    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {        mybaseAdapter = (MybaseAdapter) adapterView.getAdapter();        String item=mybaseAdapter.getItem(i).toString();     //使用介面傳參       // mOnHeadlineSelectedListener.onSelectItemClick(item);     //使用getActivity()擷取fragment2的TextView進行傳參        TextView textView=(TextView)getActivity().findViewById(R.id.one);        Log.e("getActivity()",getActivity()+"");        textView.setText(item);    }//定義傳參的介面    public interface OnHeadlineSelectedListener{        public void onSelectItemClick(String message);    }//和activity建立關係    @Override    public void onAttach(Activity activity) {        super.onAttach(activity);        mOnHeadlineSelectedListener=(OnHeadlineSelectedListener)activity;    }//為這個fragment載入布局    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {       View view= inflater.inflate(R.layout.fragment1,container,false);       listView=(ListView)view.findViewById(R.id.onelist);        return view;    }//當Activity載入完成後將資料用adapter存入    @Override    public void onActivityCreated(Bundle savedInstanceState) {        super.onActivityCreated(savedInstanceState);       ArrayAdapter arrayAdapter=new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1,str);    }

fragment2:
public class Fragment2 extends android.support.v4.app.Fragment{    private TextView mtext;    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {        View view=inflater.inflate(R.layout.fragment2,container,false);        mtext= (TextView) view.findViewById(R.id.one);        mtext.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_bright));       // mtext.setText("內容");        return  view;    }//寫個方法為text放入參數    public void setMtext(String message){        mtext.setText(message);    }}

MainActivity:
public class MyActivity extends FragmentActivity implements Fragment1.OnHeadlineSelectedListener{   Fragment2 fragment2;    Fragment1 fragment1;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        fragment1=new Fragment1();        fragment2=new Fragment2();        android.support.v4.app.FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction();        fragmentTransaction.add(R.id.onefragment,fragment1);        fragmentTransaction.add(R.id.twofragment,fragment2);        fragmentTransaction.commit();    }    @Override    public void onSelectItemClick(String message) {        //(( Fragment2)fragment2).setMtext(message);        fragment2.setMtext(message);    }}

 

聯繫我們

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