03 speaking fragment

Fragment

Document official website: https://developer.android.google.cn/guide/components/fragments

What is Fragment

On the phone, Activity as an interface users and applications interact. If the interface more View more complex, Activity would be more complicated. Fragment provide a solution, the view into several Fragment, and then makes up a complete Activity from these Fragment.

If the same part of the plurality of interfaces, can be placed overlapping portion of the fragment, the fragment is then used in a plurality of activity, the unified style reached, code reuse purposes.

 

Fragment of scenarios:

 

Fragment of use

Static add Fragment

1. Prepare Fragment use layout file

2. Create Fragment class, inherited from Fragment

Note: onCreateView method needs to be rewritten; Fragment recommended based support-v4 packet.

public class LeftFragment extends Fragment {

 public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

      View view=inflater.inflate(R.layout.left_fragment,container,false);

      return view;

 }

}

This is done in two steps Fragment A, which is very similar Activity, corresponding to the same layout is written, and layout loading in the lifecycle process.

3. The Fragment as a normal control to the corresponding layout of Activity

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools">

    <fragment

        android:id="@+id/left_fragment"

        android:name="com.ncst.coursecode.LeftFragment"

        android:layout_width="wrap_content"

        android:layout_height="match_parent"/>

</LinearLayout>

Note: id must be explicitly specified and the name attribute. The name attribute is the class name debris.

In addition, the need to contain fragments of Activity inherited from FragmentActivity. And we use the default AppCompatActivity it is inherited from FragmentActivity.

Dynamically add Fragment

Step 2 The same as above (i.e. to prepare a Fragment).

3. fragment reserve container to be placed in the corresponding Activity layout file.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools">

       <FrameLayout

        android:id="@+id/fragment_container"

        android:layout_width=" match_parent "

        android:layout_height="match_parent"/>

</LinearLayout>

4. Dynamic Fragment added in the Acitivity

Fragment fragment=new RightFragment();

        FragmentManager manager=getSupportFragmentManager();

        FragmentTransaction transaction=manager.beginTransaction();

        transaction.add(R.id. fragment_container,fragment);

        transaction.commit();

The other two methods: replace (. R.id fragment_container, fragment); removing the container all existing fragment, and add this fragement. remove (R.id fragment_container, fragment.); removing the container fragment.

Note: Static add in the XML fragment above two methods can not be removed.

addToBackStack () to add the transaction to the return stack, the return stack management by the Activity, so that user can press to return to exit to a fragment and back button to undo transaction.

Fragment communicate with activity

Obtaining fragmentation instance in the event:

getFragmentManager().findFragmentById(R.id.right_fragment);

Acquisition and current activity instance associated debris in debris:

getActivity();

Acquisition and other debris associated with the currently active fragments of debris in a:

getActivity().getFragmentManager().findFragmentById(R.id.left_fragment);

Fragment life cycle

Activity in the segment must always be embedded in the life cycle of the host directly affected Activity lifecycle. For example, when the Activity paused, which all fragments will be suspended; when Activity is destroyed, all of the fragments are also destroyed.

 

Examples Fragment (flat panel display phones and different interfaces, multiplexed same Fragment)

 

Fragment of a few examples of applications

Fragment bottom navigation implemented (similar micro-channel interface)

image:

 

 

Analysis: page is divided into two portions: a bottom (RadioGroup), the upper part (placement Fragment)

 

  1. Prepare two Fragment (ChatFragment, MomentFragment)
  2. Activity write the corresponding layout (activity_wechat)
  3. Activity in the dynamically added to the Fragment ViewGroup in. (WechatActivity)
  4. RadioGroup to add event listeners to switch Fragment.

ViewPager achieve about the sliding interface

ViewPager functions: switching can be done by sliding gesture of View, is generally used for the guide page APP or implemented image carousel, in ViewPager: android.support.v4.view.ViewPager.

ViewPager page switching is a simple assembly, we can fill the plurality of fill View, then we can slide to switch different View, front and ListView science, RecyclerView, we also need a Adapter (adapter) our View padding to ViewPager, ViewPager have a specific Adapter--  PagerAdapter ! In addition, Google is the official suggested that we use the Fragment to fill ViewPager, so you can more easily generate each Page, and manage the life cycle of each Page! It provides us with two Fragment dedicated Adapter: FragmentPageAdapte r and FragmentStatePagerAdapter  .

Use PagerAdapter

  1. Four methods that must be rewritten:

instantiateItem (ViewGroup, int) : Adding to the parent Layout View

destroyItem (the ViewGroup, int, Object) : View to remove a given location.

getCount () : get viewpager in how many view

isViewFromObject (View, Object) : general implementation: return view == object;

 

A typical PagerAdapter categories:

public class MyPagerAdapter extends PagerAdapter {

    List<View> viewList;

    public MyPagerAdapter(List<View> viewList) {

        this.viewList = viewList;

    }

    public int getCount() {

        return viewList.size();

    }

    public boolean isViewFromObject(View view, Object o) {

        return view==o;

    }

    public Object instantiateItem(ViewGroup container, int position) {

        container.addView(viewList.get(position));

        return viewList.get(position);

    }

    public void destroyItem(ViewGroup container, int position, Object object) {

        container.removeView(viewList.get(position));

    }

}

  1. Activity is defined Layout file containing ViewPager

<android.support.v4.view.ViewPager

        android:id="@+id/view_pager"

        android:layout_width="match_parent"

        android:layout_height="match_parent">

    </android.support.v4.view.ViewPager>

  1. Set in an Activity Adapter ViewPager

 

Further, PagerTabStrip ViewPager as interaction of pointers. Just in the XML document as a child can ViewPager of. And PagerAdapter need to rewrite getPageTitle () method, used to obtain the specified page title.

PagerTitleStrip and PagerTabStrip similar, the difference is not interactive.

  <android.support.v4.view.ViewPager

        android:id="@+id/view_pager"

        android:layout_width="match_parent"

        android:layout_height="match_parent">

 

        <android.support.v4.view.PagerTabStrip

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:layout_gravity="top" />

    </android.support.v4.view.ViewPager>

 

The official document: https://developer.android.google.cn/reference/android/support/v4/view/PagerAdapter

Use FragmentPagerAdapter

Is to achieve PagerAdapter, each page is a Fragment.

This version of the pager is best for use when there are a handful of typically more static fragments to be paged through, such as a set of tabs. The fragment of each page the user visits will be kept in memory, though its view hierarchy may be destroyed when not visible. This can result in using a significant amount of memory since fragment instances can hold on to an arbitrary amount of state. For larger sets of pages, consider FragmentStatePagerAdapter.

FragmentPagerAdapter for a small amount of a fixed number of pages situations. Multi-page without consuming memory is fixed, then you should consider using FragmentStatePagerAdapter.

 

Just rewrite the realization FragmentPagerAdapter: getItem(int) andgetCount()

class MyAdapter extends FragmentPagerAdapter {

        public MyAdapter(FragmentManager fm) {

            super(fm);

        }

        public Fragment getItem(int i) {

            return MyFragment.newInstance(i);

        }

        public int getCount() {

            return NUM_ITEMS;

        }

}

 

Android provides android.support.design.widget.TabLayout controls, to achieve about sliding function at the top headline.

  1. Add controls to the layout file:

<android.support.design.widget.TabLayout

        android:id="@+id/tab_layout"

        android:layout_width="match_parent"

        android:layout_height="wrap_content" />

  1. Let TabLayout associated with ViewPager together by ViewPager management TabLayout:

TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);

tabLayout.setupWithViewPager(viewPager);

  1. Adapter to be rewritten in the course getPageTitle () method.

 

The official document:

https://developer.android.google.cn/reference/android/support/v4/app/FragmentPagerAdapter.html

Guess you like

Origin www.cnblogs.com/duhuamei/p/11872913.html