《第一行代码》阅读笔记(十三)——碎片的最佳案例

第一步:创建实体类

package com.firstcode.fragmentbestpractice;

public class News {
    private String title;
    private String content;

    public News(String title, String content) {
        this.title = title;
        this.content = 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;
    }
}

直接把get/set和构造函数全部导入,这里和书上有点不一样,后面有用

第二步:新建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>

没啥可说的,就是一个界面,但是最左边为啥还有个view,我也不是很明白,难道是为了美观?
——是为了双页展示的时候,中间有个隔断。

第三步:编写NewsContentFragment类

package com.firstcode.fragmentbestpractice;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class NewsContentFragment extends Fragment {

    private View view;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable 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);//刷新新闻标题
        newsContentText.setText(newsContent);//刷新新闻内容
    }


}

这个类的主要内容就是加载布局,然后设置新闻标题和内容。

第四步:新建NewsContentActivity类
因为我是自动生成的,所以xml文件名和书上不一样。建好之后修改activity_news_content.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:orientation="vertical">

    <fragment
        android:id="@+id/news_content_fragment"
        android:name="com.firstcode.fragmentbestpractice.NewsContentFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></fragment>
</LinearLayout>

本页只引入一个碎片

第五步:修改NewsContentActivity类

package com.firstcode.fragmentbestpractice;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

public class NewsContentActivity extends AppCompatActivity {

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_content);
        String newsTitle = getIntent().getStringExtra("news_title");
        String newsContent = getIntent().getStringExtra("news_content");
        NewsContentFragment newsContentFragment = (NewsContentFragment) getSupportFragmentManager().findFragmentById(R.id.news_content_fragment);
        newsContentFragment.refresh(newsTitle,newsContent);
    }
}

第六步:创建一个新闻列表的布局

<?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">


    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/news_title_recycle_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

第七步:给新闻列表添加子项

<?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:ellipsize="end"
    android:paddingLeft="10dp"
    android:paddingTop="15dp"
    android:paddingRight="10dp"
    android:paddingBottom="15dp"
    android:singleLine="true"
    android:textSize="18sp">

</TextView>

第八步:创建NewsTitleFragment类

package com.example.comprehensivepractice.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.comprehensivepractice.R;

public class NewsTitleFragment extends Fragment {

    private boolean isTwoPage;

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

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);
        if (getActivity().findViewById(R.id.news_content_layout) != null) {
            isTwoPage = true;
        } else {
            isTwoPage = false;
        }

    }
}

这个部分只有两个函数,第一个就是创建视图的时候加载布局,这个不多说。
第二个就是在创建活动的时候,进行一个判断。这里先写着,因为R.id.news_content_layout这个布局我们还没有写。

第九步:修改主活动的布局

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

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


</FrameLayout>

第十步:添加大屏界面

<?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="horizontal">

    <fragment
        android:id="@+id/news_title_fragment"
        android:name="com.example.comprehensivepractice.fragment.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="1">

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


    </FrameLayout>
</LinearLayout>

这两个不同尺寸的主界面都很简单,一看就明白。

第十步:添加适配器

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

        private List<News> mNewsList = new ArrayList<News>();

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

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

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

        }

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

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView title;

            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                title = (TextView) itemView.findViewById(R.id.news_title);
            }
        }


    }

第十一步:新闻信息的初始化

 @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_news_title, container, false);
        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.news_title_recycle_view);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(manager);
        NewsAdapter adapter = new NewsAdapter(getNews());
        recyclerView.setAdapter(adapter);
        return view;
    }

    private List<News> getNews() {
        List<News> newsList = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            News news = new News("This is a news title" + i, getRandomLengthContent("This is a 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();
    }

展示

平板

手机


总结

一下是笔者分析的碎片的流程

  1. 首先主活动类里面什么都没有,只是加载了一个布局。而想要追踪布局,会发现有两个同名的布局,就是咱们之前设计的单页展示和多页展示。

  2. 如果是小屏幕手机就定位到单页布局,可以看出只有一个fragment。这个fragment绑定了一个标题类。这个类非常复杂,有很多功能

    1. 首先就是加载了一个新闻标题的布局,这个布局里面只有一个RecyclerVIew
    2. 有RecyclerVIew就需要初始化
    3. onActivityCreated中添加了一个判断,根据碎片的生命周期,可以知道onActivityCreated发生在onCreateView和onStart之间,也就是碎片的空间建立好后,连接活动,在展示在我们眼前的之间的那段时间。对是不是有两页布局进行判断,如果有设为ture,没有设为false。这里应该是false
    4. 书上将适配器也在这这个类中了,主要是为了直接使用isTwoPage,根据isTwoPage的值,这里应该跳转。适配器除了这个判断以外,没有特殊的地方。
  3. 如果是大屏幕平板就定位到另一个双页布局,在布局中有两个fragment,除了刚才讲解过的标题碎片,还有一个内容碎片。内容碎片绑定一个内容类,里面加载了内容的布局,和一个刷新内容的方法。

    1. 之前的步骤都和小屏幕手机一样
    2. 判断isTwoPage的值为true的时候,加载大屏幕平板布局
    3. 通过getFragmentManager获得碎片,再通过碎片中的refresh()函数,刷新右边内容布局

注意事项:

  1. onCreateViewHolder在适配器中的作用就和活动中的onCreate一样。首先就是通过from()来获取来获取LayoutInflater,一般这里传递的参数都是parent.getContext(),就是获取父布局。因为一般我们都是把recyclerview加载到一个layout中,然后通过inflate()函数来放入子项,参数就是子项布局和父环境,这里一般就是parent,还有false。false的意思就是不为这个子项新建父布局。初期的话只要记忆就行了,慢慢使用过程中,就会加深理解。

  2. onBindViewHolder就是每项显示的时候调用的函数,通过position来定位,然后对每个子项实例化。还可以进行一些其他的造作,比如聊天demo的时候,判断属性,然后隐藏一个textView。主要就是通过viewholder操作。

  3. 加载recyclerview的时候,先通过id寻找到控件,然后通过活动来找到布局管理器(这里有个问题不知道为什么都是LinearLayoutManager),然后再活动适配器。把布局管理器和适配器全部加载给控件即可。

  4. 碎片先制作一个布局,然后绑定一个类,在类里面加载布局。然后再在需要的地方引入碎片即可。如果是动态的就用FrameLayout

原文地址:https://www.cnblogs.com/zllk/p/13363771.html