Fragment parses creation and passing parameters, and dynamically adds fragment and fragment

Source: Internet
Author: User

Fragment parses creation and passing parameters, and dynamically adds fragment and fragment

Here is my summary.

Create XML for fragment

<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>
/Then create a class that inherits the Fragment
Public class Yule extends ListFragment {@ Override public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {return inflater. inflate (R. layout. yule, container, false);} // load the fragment we just wrote. xml layout file and return


 

Open or create activity_main.xml as the layout file of the main Activity, add two Fragment references to it, and use the android: name prefix to reference the specific 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>  


 

Dynamically add fragment to delete the two fragmnet controls in activity_main.xml, leaving only the linearlayout layout. Set an id for this layout // modify the code in MainActivity as follows:
Public class MainActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // obtain the screen size Display = getWindowManager (). getdefadisplay display (); 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 ();}}}

First, we need to get the width and height of the screen, and then judge, if the screen width is greater than the height, add fragment1, if the height is greater than the width, add fragment2. Dynamic Fragment addition is mainly divided into four steps:

1. Get the FragmentManager, which can be obtained directly through getFragmentManager in the Activity.

2. Start a transaction by calling the beginTransaction method.

3. Add Fragment to the container, which is generally implemented using the replace method. You need to input the container id and Fragment instance.

4. Submit the transaction and call the commit method to submit the transaction. // Fragment lifecycle, which is called when the Fragment and activity are associated with the onAttach method of the Activity.
OnCreateView method: called when layout is loaded for Fragment.
OnActivityCreated method: This method is called after the onCreate method in the Activity is executed.
OnDestroyView method: called when the layout in Fragment is removed.
OnDetach method: called when Fragment and Activity are unbound.


 

Communication between Fragment: two methods are used to pass parameters and getActivity.Fragment1.xml layout:
<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 layout:
<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"}; // parameter passing interface 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 (); // use the interface to pass the parameter // mOnHeadlineSelectedListener. onSelectItemClick (item); // use getActivity () to obtain the TextView of fragment2 and pass the parameter TextView textView = (TextView) getActivity (). findViewById (R. id. one); Log. e ("getActivity ()", getActivity () + ""); textView. setText (item) ;}// define the parameter passing interface public interface OnHeadlineSelectedListener {public void onSelectItemClick (String message );} // establish a relationship with activity @ Override public void onAttach (Activity activity) {super. onAttach (activity); mOnHeadlineSelectedListener = (optional) activity;} // load the layout for this 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;} // after the Activity is loaded, use the adapter to store the data to @ 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 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 ("content"); return view;} // enter the public void setMtext (String message) {mtext in the text method. 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);    }}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.