1. 程式人生 > >Android中利用newInstance()方法例項化fragment

Android中利用newInstance()方法例項化fragment

Android是在Android 3.0 (API level 11)開始引入Fragment的。Fragment可以使你能夠將activity分離成多個可重用的元件,每個都有它自己的生命週期和UI。那我們應該怎麼去建立fragment呢?Google已經考慮到這種情況了,所以推薦我們使用newInstance()的方式來建立,下面讓我們看一下到底怎麼使用吧!也是很簡單的!

例,我們要實現的效果圖,

這裡寫圖片描述

MainActivity中:


public class MainActivity extends AppCompatActivity {

    private ViewPager vp;
    private
TabLayout tabLayout; private MainAdapter mainAdapter; private List<Fragment> fragments = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); vp = (ViewPager) findViewById(R.id.vp); tabLayout = (TabLayout) findViewById(R.id.tab); mainAdapter = new
MainAdapter(getSupportFragmentManager()); fragments.add(MyFragment.newInstance("第一個fragment")); fragments.add(MyFragment.newInstance("第二個fragment")); fragments.add(MyFragment.newInstance("第三個fragment")); mainAdapter.setFragments(fragments); vp.setAdapter(mainAdapter); //設定tabLayout
tabLayout.setupWithViewPager(vp); //設定文字的顏色 tabLayout.setTabTextColors(Color.GRAY, Color.BLUE); //設定下劃線的顏色 tabLayout.setSelectedTabIndicatorColor(Color.BLUE); } }

MainAdapter中:


/**
 * Created by mac on 16-8-5.
 */
public class MainAdapter extends FragmentPagerAdapter {

    private List<Fragment> fragments;
    private String[] titles = {"一頁", "二頁", "三頁"};


    public MainAdapter(FragmentManager fm) {
        super(fm);
    }

    public void setFragments(List<Fragment> fragments) {
        this.fragments = fragments;
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        return fragments != null ? fragments.size() : 0;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titles[position];
    }

}

MyFragment中:


/**
 * Created by mac on 16-8-6.
 */
public class MyFragment extends Fragment {

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            String name = bundle.get("name").toString();
            Log.d("MyFragment", name);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my, null);
        return view;
    }

    public static MyFragment newInstance(String name) {
        Bundle args = new Bundle();
        args.putString("name", name);
        MyFragment fragment = new MyFragment();
        fragment.setArguments(args);
        return fragment;
    }
}

MainActivity的佈局檔案:


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.mac.fragmentdemo.MainActivity">

    <android.support.design.widget.TabLayout
        android:id="@+id/tab"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <android.support.v4.view.ViewPager
        android:id="@+id/vp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/tab" />
</RelativeLayout>

MyFragment的佈局檔案:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher" />
</LinearLayout>

執行程式後,我們會發現控制檯出現資訊如下,

這裡寫圖片描述

在這種情況下,newInstance()方法是一種“靜態工廠方法”,讓我們在初始化和設定一個新的fragment的時候省去呼叫它的構造方法和額外的setter方法。為你的Fragment提供靜態工廠方法是一種好的做法,因為它封裝和抽象了在客戶端構造物件所需的步驟,因此Google推薦使用,所我們就使用吧!

本人菜鳥一個,有什麼不對的地方希望大家指出評論,大神勿噴,希望大家一起學習進步!