第4章 探究碎片fragment

本系列學(xué)習(xí)筆記第4章

前言

打算把a(bǔ)ndroid基本知識(shí)點(diǎn)寫一個(gè)系列,旨在把a(bǔ)ndroid基礎(chǔ)書,例如《Android 第一行代碼 第2版》名斟、《愛上android》蒸眠、《瘋狂android講義》等書的一些知識(shí)點(diǎn)記錄一下楞卡,會(huì)持續(xù)更新內(nèi)容蒋腮,為了方便自己復(fù)習(xí),也希望可以幫助到大家作彤!

目錄

1竭讳、碎片是什么

2绢慢、碎片的使用方式
    2.1 靜態(tài)添加碎片(布局文件中添加碎片)
    2.2 動(dòng)態(tài)態(tài)添加碎片
        2.2.1 案例一
        2.2.2 案例二
    2.3 在碎片中模擬返回棧
    2.4 碎片和活動(dòng)之間進(jìn)行通信
    2.5 片段管理的一些說明
    
3骚露、碎片的生命周期
    3.1 碎片的狀態(tài)和回調(diào)
    3.2 體驗(yàn)碎片的生命周期


4棘幸、動(dòng)態(tài)加載布局的技巧
    4.1 使用限定符
    4.2 使用最小寬度限定符

5、碎片的最佳實(shí)現(xiàn)---------一個(gè)簡(jiǎn)易版的新聞應(yīng)用

6、FragmentTabHost實(shí)現(xiàn)底部標(biāo)簽

1诞帐、碎片是什么

碎片(Fragment)是一種可以嵌入在活動(dòng)當(dāng)中的UI片段停蕉,它能讓程序更加合理和充分地利用大屏幕的空間,因而在平板上應(yīng)用得非常廣泛蚓挤。

2灿意、碎片的使用方式

2.1 靜態(tài)添加碎片(布局文件中添加碎片)

left_fragment.xml文件

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

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Button"
        />

</LinearLayout>

right_fragment.xml文件

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textSize="20sp"
        android:text="This is right fragment"
        />

</LinearLayout>

LeftFragment.java文件

public class LeftFragment extends Fragment {

    public static final String TAG = LeftFragment.class.getSimpleName();

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

}

RightFragment.java文件

public class RightFragment extends Fragment {

    public static final String TAG = RightFragment.class.getSimpleName();


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



}

activity_main.xml文件

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


    <fragment
        android:id="@+id/left_fragment"
        android:name="com.example.fragmenttest.LeftFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        />

    <fragment
        android:id="@+id/right_fragment"
        android:name="com.example.fragmenttest.RightFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        />

</LinearLayout>

效果圖如下:


image.png
2.2 動(dòng)態(tài)態(tài)添加碎片
2.2.1 案例一

在上一節(jié)的代碼基礎(chǔ)上修改荒辕,新建another_right_fragment.xml文件

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textSize="20sp"
        android:text="This is another right fragment"
        />

</LinearLayout>

AnotherRightFragment.java文件

public class AnotherRightFragment extends Fragment {

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

activity_main.xml.文件

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


    <fragment
        android:id="@+id/left_fragment"
        android:name="com.example.fragmenttest.LeftFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        />

    <FrameLayout
        android:id="@+id/right_layout"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        />

</LinearLayout>

MainActivity.java文件

public class MainActivity extends AppCompatActivity  implements View.OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(this);
        replaceFragment(new RightFragment());
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.button:
                replaceFragment(new AnotherRightFragment());
                break;
            default:
                break;
        }
    }

    private void replaceFragment(Fragment fragment){
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.right_layout,fragment);
        transaction.commit();
    }
}

效果圖如下:


image.png
image.png
2.2.2 案例二

layout_left_fragment.xml文件

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorAccent"
    >



</android.support.constraint.ConstraintLayout>

layout_right_fragment.xml文件

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimaryDark"
    >

</android.support.constraint.ConstraintLayout>

activity_main.xml文件

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

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

</LinearLayout>

LeftFragment.java文件

public class LeftFragment extends Fragment {

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

RightFragment.java 文件

public class RightFragment extends Fragment {

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

        View view = inflater.inflate(R.layout.layout_right_fragment, null);
        return view;
    }
}

MainActivity.java文件

public class MainActivity extends AppCompatActivity {

    private LeftFragment leftFragment;
    private RightFragment rightFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WindowManager windowManager = getWindowManager();
        DisplayMetrics displayMetrics = new DisplayMetrics();
        //測(cè)量屏幕的尺寸
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
        //測(cè)量屏幕寬高
        int widthPixels = displayMetrics.widthPixels;
        int heightPixels = displayMetrics.heightPixels;

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();

        if (widthPixels > heightPixels){
            transaction.replace(R.id.container_content,getLeftFragment());
        }else if (widthPixels < heightPixels){
            transaction.replace(R.id.container_content, getRightFragment());
        }
        transaction.addToBackStack(null);
        transaction.commit();
    }

//    獲取左邊的Fragment
    private LeftFragment getLeftFragment(){
        if (leftFragment == null){
            leftFragment = new LeftFragment();
        }
        return leftFragment;
    }

    //    獲取左邊的Fragment
    private RightFragment getRightFragment(){
        if (rightFragment == null){
            rightFragment = new RightFragment();
        }
        return rightFragment;
    }
}

image.png
image.png
2.3 在碎片中模擬返回棧

修改MainActivity.java文件

public class MainActivity extends AppCompatActivity  implements View.OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(this);
        replaceFragment(new RightFragment());
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.button:
                replaceFragment(new AnotherRightFragment());
                break;
            default:
                break;
        }
    }

    private void replaceFragment(Fragment fragment){
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.right_layout,fragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }
}

效果圖如下:


image.png

image.png
image.png

image.png

image.png

image.png

image.png
2.4 碎片和活動(dòng)之間進(jìn)行通信

1)活動(dòng)中使用碎片的方法(獲得碎片的實(shí)例,就可以獲取碎片的方法)

  LeftFragment leftFragment = (LeftFragment) getSupportFragmentManager().findFragmentById(R.id.left_fragment);

2)碎片中使用活動(dòng)的方法

 MainActivity activity = (MainActivity) getActivity();

3)碎片與碎片之間的通信
基本思路如下:
在一個(gè)碎片中可以獲取得到與它相關(guān)聯(lián)的活動(dòng)厌衔,然后再通過這個(gè)活動(dòng)去獲取另外一個(gè)碎片的實(shí)例富寿,這樣也就實(shí)現(xiàn)了不同碎片之間的通信功能。

2.5 片段管理的一些說明

1)從Activity通過getSupportFragmentManager()方法(建議用這個(gè)兼容版本)或者getFragmentManager()方法獲取FragmentManager

2)通過fragmentManager.findFragmentById()方法(對(duì)于在Activity布局中提供UI片段)獲取Activity中存在的Fragment

3)通過fragmentManager.findFragmentByTag()方法(對(duì)于提供或不提供UI片段)獲取Activity中存在的Fragment
4) 通過fragmentManager.popBackStack()(模擬用戶按Back返回鍵)將片段從返回棧中彈出

5)通過fragmentManager.beginTransaction()開啟一個(gè)事務(wù)

6) 通過fragmentManager.addOnBackStackChangedListener()注冊(cè)一個(gè)監(jiān)聽返回棧的監(jiān)聽器

7)transaction.addToBackStack(null)添加返回棧

3变勇、碎片的生命周期

3.1 碎片的狀態(tài)和回調(diào)

1)運(yùn)行狀態(tài)
當(dāng)一個(gè)碎片是可見的搀绣,并且它所關(guān)聯(lián)的活動(dòng)正處于運(yùn)行狀態(tài)時(shí),該碎片也處于運(yùn)行狀態(tài)麻捻。

2)暫停狀態(tài)
當(dāng)一個(gè)活動(dòng)進(jìn)入暫停狀態(tài)時(shí)(由于另外一個(gè)未占滿屏幕的活動(dòng)被添加到了棧頂)芯肤,與它相關(guān)聯(lián)的可見碎片就會(huì)進(jìn)入暫停狀態(tài)

3)停止?fàn)顟B(tài)
當(dāng)一個(gè)活動(dòng)進(jìn)入停止?fàn)顟B(tài)時(shí)崖咨,與它相關(guān)聯(lián)的碎片就會(huì)進(jìn)入到停止?fàn)顟B(tài)击蹲,或者通過FragmentTransaction的remove()歌豺、replace()方法將碎片從活動(dòng)中移除馒铃,但是如果在事務(wù)提交之前調(diào)用addToBackStack()方法区宇,這時(shí)的碎片也會(huì)進(jìn)入到停止?fàn)顟B(tài)议谷∥韵總的來說逼裆,進(jìn)入停止?fàn)顟B(tài)的碎片對(duì)用戶來說是完全不可見的,也可能會(huì)被系統(tǒng)回收。

4)銷毀狀態(tài)
碎片總是依附于活動(dòng)而存在的然评,因此當(dāng)活動(dòng)被銷毀時(shí)碗淌,與它相關(guān)聯(lián)的碎片就會(huì)進(jìn)入到銷毀狀態(tài)亿眠。或者通過調(diào)用FragmentTransaction的remove()竟趾、replace()方法將碎片從活動(dòng)中移除岔帽,但是在事務(wù)提交之前并沒有調(diào)用addToBackStack()方法犀勒,這時(shí)的碎片也會(huì)進(jìn)入到銷毀狀態(tài)贾费。

image.png
3.2 體驗(yàn)碎片的生命周期

修改RightFragment,java文件

public class RightFragment extends Fragment {

    public static final String TAG = RightFragment.class.getSimpleName();

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Log.d(TAG, "onAttach");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView");
        View view = inflater.inflate(R.layout.right_fragment, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.d(TAG, "onActivityCreated");
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "onDestroyView");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d(TAG, "onDetach");
    }

}

運(yùn)行上面的項(xiàng)目,觀察發(fā)現(xiàn)RightFragment 的生命周期如下:


image.png

點(diǎn)擊按鈕切換Fragment


image.png
image.png

如果在替換的時(shí)候沒有調(diào)用addToBackStack()方法,生命周期如下:


image.png

點(diǎn)擊返回按鈕,RightFragment 的生命周期如下:


image.png
image.png

4、動(dòng)態(tài)加載布局的技巧

4.1 使用限定符

layout/activity_main.xml文件

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


    <fragment
        android:id="@+id/left_fragment"
        android:name="com.example.fragmenttest.LeftFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

</LinearLayout>

layout-large目錄下的activity_main.xml文件

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

    <fragment
        android:id="@+id/left_fragment"
        android:name="com.example.fragmenttest.LeftFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <fragment
        android:id="@+id/right_fragment"
        android:name="com.example.fragmenttest.RightFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3" />

</LinearLayout>
image.png
image.png
4.2 使用最小寬度限定符

最小寬度限定符允許我們對(duì)屏幕的寬度指定一個(gè)最小值(以dp為單位)九孩,然后以這個(gè)最小值為臨界點(diǎn)躺彬,屏幕寬度大于這個(gè)值的設(shè)備就加載一個(gè)布局宪拥,屏幕寬度小于這個(gè)值的設(shè)備就加載另一個(gè)布局

例如她君,res目錄下新建layout-sw6600dp的文件夾鳖枕,就是以屏幕寬度600dp為臨界點(diǎn)

5宾符、碎片的最佳實(shí)現(xiàn)---------一個(gè)簡(jiǎn)易版的新聞應(yīng)用

創(chuàng)建實(shí)體類News,java
···
public class News {

private String title;

private String content;

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getContent() {
    return content;
}

public void setContent(String content) {
    this.content = content;
}

}

···

列表item布局news_item.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/news_title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:singleLine="true"
    android:ellipsize="end"
    android:textSize="18sp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:paddingTop="15dp"
    android:paddingBottom="15dp"
    />

news_content_frag.xml布局

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

    <LinearLayout
        android:id="@+id/visibility_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:visibility="invisible" >

        <TextView
            android:id="@+id/news_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="10dp"
            android:textSize="20sp" />

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#000" />

        <TextView
            android:id="@+id/news_content"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:padding="15dp"
            android:textSize="18sp" />

    </LinearLayout>

    <View
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:background="#000" />

</RelativeLayout>

NewsContentFragment文件

public class NewsContentFragment extends Fragment {

    private View view;

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

    public void refresh(String newsTitle, String newsContent) {
        View visibilityLayout = view.findViewById(R.id.visibility_layout);
        visibilityLayout.setVisibility(View.VISIBLE);
        TextView newsTitleText = (TextView) view.findViewById (R.id.news_title);
        TextView newsContentText = (TextView) view.findViewById(R.id.news_content);
        newsTitleText.setText(newsTitle); // 刷新新聞的標(biāo)題
        newsContentText.setText(newsContent); // 刷新新聞的內(nèi)容
    }

}

NewsContentActivity.java文件

public class NewsContentActivity extends AppCompatActivity {

    public static void actionStart(Context context, String newsTitle, String newsContent) {
        Intent intent = new Intent(context, NewsContentActivity.class);
        intent.putExtra("news_title", newsTitle);
        intent.putExtra("news_content", newsContent);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_content);
        String newsTitle = getIntent().getStringExtra("news_title"); // 獲取傳入的新聞標(biāo)題
        String newsContent = getIntent().getStringExtra("news_content"); // 獲取傳入的新聞內(nèi)容
        NewsContentFragment newsContentFragment = (NewsContentFragment) getSupportFragmentManager().findFragmentById(R.id.news_content_fragment);
        newsContentFragment.refresh(newsTitle, newsContent); // 刷新NewsContentFragment界面
    }

}

news_title_frag.xml文件

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

    <android.support.v7.widget.RecyclerView
        android:id="@+id/news_title_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

</LinearLayout>

NewsTitleFragment.java文件

public class NewsTitleFragment extends Fragment {

    private boolean isTwoPane;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.news_title_frag, container, false);
        RecyclerView newsTitleRecyclerView = (RecyclerView) view.findViewById(R.id.news_title_recycler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        newsTitleRecyclerView.setLayoutManager(layoutManager);
        NewsAdapter adapter = new NewsAdapter(getNews());
        newsTitleRecyclerView.setAdapter(adapter);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getActivity().findViewById(R.id.news_content_layout) != null) {
            isTwoPane = true; // 可以找到news_content_layout布局時(shí)稀蟋,為雙頁(yè)模式
 News news = newsList.get(0);
            NewsContentFragment newsContentFragment = (NewsContentFragment)
                    getFragmentManager().findFragmentById(R.id.news_content_fragment);
            newsContentFragment.refresh(news.getTitle(), news.getContent());
        } else {
            isTwoPane = false; // 找不到news_content_layout布局時(shí)退客,為單頁(yè)模式
        }
    }

    private List<News> getNews() {
        List<News> newsList = new ArrayList<>();
        for (int i = 1; i <= 50; i++) {
            News news = new News();
            news.setTitle("This is news title " + i);
            news.setContent(getRandomLengthContent("This is news content " + i + ". "));
            newsList.add(news);
        }
        return newsList;
    }

    private String getRandomLengthContent(String content) {
        Random random = new Random();
        int length = random.nextInt(20) + 1;
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < length; i++) {
            builder.append(content);
        }
        return builder.toString();
    }

    class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {

        private List<News> mNewsList;

        class ViewHolder extends RecyclerView.ViewHolder {

            TextView newsTitleText;

            public ViewHolder(View view) {
                super(view);
                newsTitleText = (TextView) view.findViewById(R.id.news_title);
            }

        }

        public NewsAdapter(List<News> newsList) {
            mNewsList = newsList;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_item, parent, false);
            final ViewHolder holder = new ViewHolder(view);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    News news = mNewsList.get(holder.getAdapterPosition());
                    if (isTwoPane) {
                        NewsContentFragment newsContentFragment = (NewsContentFragment)
                                getFragmentManager().findFragmentById(R.id.news_content_fragment);
                        newsContentFragment.refresh(news.getTitle(), news.getContent());
                    } else {
                        NewsContentActivity.actionStart(getActivity(), news.getTitle(), news.getContent());
                    }
                }
            });
            return holder;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            News news = mNewsList.get(position);
            holder.newsTitleText.setText(news.getTitle());
        }

        @Override
        public int getItemCount() {
            return mNewsList.size();
        }

    }

}

layout目錄下的activity_main.xml文件

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/news_title_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <fragment
        android:id="@+id/news_title_fragment"
        android:name="com.example.fragmenttest.NewsTitleFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

</FrameLayout>

layout-sw600dp目錄下的activity_main.xml文件

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

    <fragment
        android:id="@+id/news_title_fragment"
        android:name="com.example.fragmenttest.NewsTitleFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <FrameLayout
        android:id="@+id/news_content_layout"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3" >

        <fragment
            android:id="@+id/news_content_fragment"
            android:name="com.example.fragmenttest.NewsContentFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </FrameLayout>

</LinearLayout>
image.png
image.png
image.png

6、FragmentTabHost實(shí)現(xiàn)底部標(biāo)簽

準(zhǔn)備好圖片資源务傲,制作selector樣式


image.png

tab1.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/tab1_normal" android:state_selected="false"/>
    <item android:drawable="@drawable/tab1_selected" android:state_selected="true"/>
</selector>

tab2.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/tab2_normal" android:state_selected="false"/>
    <item android:drawable="@drawable/tab2_selected" android:state_selected="true"/>
</selector>
image.png

layout_left_fragment.xml文件

<?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:background="@color/colorAccent"
    >



</LinearLayout>

layout_right_fragment.xml文件

<?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:background="@color/colorPrimaryDark"
    >

</LinearLayout>

LeftFragment.java文件

public class LeftFragment extends Fragment {

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

RightFragment.java文件

public class RightFragment extends Fragment {

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

        View view = inflater.inflate(R.layout.layout_right_fragment, null);
        return view;
    }
}

layout_indicator_view.xml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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"
    android:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:layout_gravity="center"
        android:id="@+id/iv_tab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="@null"
        tools:src="@mipmap/ic_launcher"/>
    <TextView
        android:id="@+id/tv_tab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="標(biāo)簽"/>
</LinearLayout>

activity_fragment_tab_host.xml文件

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.app.FragmentTabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <!--用來加載Fragment -->
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />
        <!--分割線 用來分割Fragment和底部標(biāo)簽-->
        <View
            android:layout_width="match_parent"
            android:layout_height="1px"
            android:background="#d9d9d9"
            android:orientation="vertical"/>
        <!--標(biāo)簽組件-->
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:layout_gravity="bottom" />
    </LinearLayout>

</android.support.v4.app.FragmentTabHost>

FragmentTabHostActivity.java文件

public class FragmentTabHostActivity extends AppCompatActivity {

    private FragmentTabHost fragmentTabHost;

    //標(biāo)簽的圖片
    private int imageIds[] = {R.drawable.tab1, R.drawable.tab2,
    };
    //加載的Fragment
    private Class<?> mFragmentClasses[] = {LeftFragment.class, RightFragment.class};
    //標(biāo)簽文字
    private String[] text=new String[]{"首頁(yè)","娛樂"};

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment_tab_host);

        fragmentTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);

        //初始化
        fragmentTabHost.setup(this,getSupportFragmentManager(),android.R.id.tabcontent);
        //去掉分割線
        fragmentTabHost.getTabWidget().setDividerDrawable(null);
        
        //添加標(biāo)簽
        for (int i = 0; i < imageIds.length; i++) {
            //Tab按鈕添加文字和圖片
            TabHost.TabSpec tabSpec = fragmentTabHost.newTabSpec(i + "").setIndicator(getIndicatorView(this, i));
            //添加到fragment
            fragmentTabHost.addTab(tabSpec,mFragmentClasses[i],null);

        }

        //切換標(biāo)簽時(shí)調(diào)用
        fragmentTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
            @Override
            public void onTabChanged(String s) {

            }
        });

    }

    //獲取標(biāo)簽的View
    private View getIndicatorView(Context context,int i){
        View view = View.inflate(context,R.layout.layout_indicator_view, null);
        ImageView imageView = (ImageView) view.findViewById(R.id.iv_tab);
        TextView textView = (TextView) view.findViewById(R.id.tv_tab);
        imageView.setImageResource(imageIds[i]);
        textView.setText(text[i]);
        return view;
    }
}

image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末像寒,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子祭芦,更是在濱河造成了極大的恐慌龟劲,老刑警劉巖昌跌,帶你破解...
    沈念sama閱讀 218,451評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蚕愤,死亡現(xiàn)場(chǎng)離奇詭異萍诱,居然都是意外死亡裕坊,警方通過查閱死者的電腦和手機(jī)籍凝,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,172評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門堰氓,熙熙樓的掌柜王于貴愁眉苦臉地迎上來双絮,“玉大人囤攀,你說我怎么就攤上這事焚挠±焐В” “怎么了蝌蹂?”我有些...
    開封第一講書人閱讀 164,782評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵剃允,是天一觀的道長(zhǎng)斥废。 經(jīng)常有香客問我牡肉,道長(zhǎng)统锤,這世上最難降的妖魔是什么跪另? 我笑而不...
    開封第一講書人閱讀 58,709評(píng)論 1 294
  • 正文 為了忘掉前任免绿,我火速辦了婚禮嘲驾,結(jié)果婚禮上辽故,老公的妹妹穿的比我還像新娘誊垢。我一直安慰自己喂走,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,733評(píng)論 6 392
  • 文/花漫 我一把揭開白布芋肠。 她就那樣靜靜地躺著乎芳,像睡著了一般。 火紅的嫁衣襯著肌膚如雪帖池。 梳的紋絲不亂的頭發(fā)上奈惑,一...
    開封第一講書人閱讀 51,578評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音睡汹,去河邊找鬼。 笑死帮孔,一個(gè)胖子當(dāng)著我的面吹牛雷滋,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播文兢,決...
    沈念sama閱讀 40,320評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼晤斩,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了姆坚?” 一聲冷哼從身側(cè)響起澳泵,我...
    開封第一講書人閱讀 39,241評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎兼呵,沒想到半個(gè)月后兔辅,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,686評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡击喂,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,878評(píng)論 3 336
  • 正文 我和宋清朗相戀三年维苔,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片懂昂。...
    茶點(diǎn)故事閱讀 39,992評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡介时,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出凌彬,到底是詐尸還是另有隱情沸柔,我是刑警寧澤,帶...
    沈念sama閱讀 35,715評(píng)論 5 346
  • 正文 年R本政府宣布铲敛,位于F島的核電站褐澎,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏伐蒋。R本人自食惡果不足惜工三,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,336評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望先鱼。 院中可真熱鬧徒蟆,春花似錦、人聲如沸型型。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,912評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)闹蒜。三九已至寺枉,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間绷落,已是汗流浹背姥闪。 一陣腳步聲響...
    開封第一講書人閱讀 33,040評(píng)論 1 270
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留砌烁,地道東北人筐喳。 一個(gè)月前我還...
    沈念sama閱讀 48,173評(píng)論 3 370
  • 正文 我出身青樓催式,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親避归。 傳聞我的和親對(duì)象是個(gè)殘疾皇子荣月,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,947評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容