第三章(碎片实践,简易版的新闻应用)

碎片实践,简易版的新闻应用

1.首先添加RecyclerView的依赖库:
简便方法:File->Project Structure->Dependencies->点+号找到recyclerview添加后点击ok就自动给项目添加了依赖库

  1. 首先建一个新闻的实体类News
package com.example.fragmentbestpractice;

/**
 * Created by 侯允林 on 2018/5/27.
 */

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;
    }
}

title表示新闻标题,content表示新闻内容

  1. 新建布局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"
    android:orientation="vertical">
<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_height="wrap_content"
        android:layout_width="match_parent"
        android:gravity="center"
        android:padding="10dp"
        android:textSize="20sp"/>
    <View
        android:layout_height="1dp"
        android:layout_width="match_parent"
        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实现细分隔线

  1. 新建一个NewsContentFragment继承Fragment,并提供一个refresh方法用于刷新内容
package com.example.fragmentbestpractice;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * Created by 侯允林 on 2018/5/27.
 */

public class NewsContentFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.news_content_frag,container,false);
        return view;
    }
    public void refresh(String newsTitle,String newsContent){
        LinearLayout layout=getView().findViewById(R.id.visibility_layout);//getView() return The fragment's root view, or null if it has no layout.
        layout.setVisibility(View.VISIBLE);
        TextView newsTitleText=(TextView)getView().findViewById(R.id.news_title);
        TextView newsTitleContentText=(TextView)getView().findViewById(R.id.news_content);
        newsTitleText.setText(newsTitle);
        newsTitleContentText.setText(newsContent);

    }
}

这些方法和一些用法很简单就不必赘述了,refresh方法是在其他活动或碎片中通过获得NewsContentFragment实例调用的

  • 以上的这个碎片是用于双页模式的
  1. 我们再建一个空Activity叫NewsContentActivity将上面这个NewsContentFragment引进来
  • 布局
<?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.fragmentbestpractice.NewsContentActivity">
<fragment
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:name="com.example.fragmentbestpractice.NewsContentFragment"
    android:id="@+id/news_content_fragment"/>
</LinearLayout>

  • NewsContentActivity
package com.example.fragmentbestpractice;

        import android.content.Context;
        import android.content.Intent;
        import android.support.v7.app.AppCompatActivity;
        import android.os.Bundle;

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");
        String newsContent=getIntent().getStringExtra("news_content");
        NewsContentFragment newsContentFragment=(NewsContentFragment) getSupportFragmentManager().findFragmentById(R.id.news_content_fragment);
        newsContentFragment.refresh(newsTitle,newsContent);
    }
}

这里的actionStart方法作用是方便别的活动启动这个活动时传递数据,要记住这种写法。
在onCreate方法里面FragmentManager的findFragmentById的方法获得NewsContentFragment的实例,然后调用它的refresh方法刷新显示内容,从而刷新了NewsContentActivity里面显示的内容

  1. 接下来创建一个用于显示新闻列表的布局,利用RecyclerView.
  • 新建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:layout_height="match_parent"
    android:layout_width="match_parent"
    android:id="@+id/news_title_recrcler_view"/>
</LinearLayout>
  • 新建news_item作为RecyclerView的子项布局
<?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:maxLines="1"
        android:ellipsize="end"
        android:textSize="18sp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="15dp"
        android:paddingBottom="15dp"/>

  1. 接下来新建一个用于展示新闻列表的Fragment,在这个碎片中我们顺带创建一个用于显示标题列表的RecyclerView的适配器
package com.example.fragmentbestpractice;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by 侯允林 on 2018/5/27.
 */

public class NewTitileFragment extends Fragment {
    private boolean isTwoPane;
    private RecyclerView newsTitleRecyclerView;

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

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getActivity().findViewById(R.id.news_content_layout) != null) {
            isTwoPane = true;
        } else {
            isTwoPane = false;
        }
    }

    public 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 title" + i));
            newsList.add(news);
        }
        return newsList;
    }

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


    public class InnerNewsAdapter extends RecyclerView.Adapter<InnerNewsAdapter.ViewHolder> {
        private List<News> mNewsList;

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

        class ViewHolder extends RecyclerView.ViewHolder {

            private TextView newsItem;

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

        @Override
        public InnerNewsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_item, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(final InnerNewsAdapter.ViewHolder holder, final int position) {
          final  News news = mNewsList.get(position);
            holder.newsItem.setText(news.getTitle());
            holder.newsItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (isTwoPane) {
                        NewsContentFragment newsContentFragment = (NewsContentFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.news_content_fragment);
                        //注意区分getFragmentManager
                        newsContentFragment.refresh(news.getTitle(), news.getContent());
                    }else {
                        NewsContentActivity.actionStart(getActivity(),news.getTitle(),news.getContent());
                    }
                }
            });

        }

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

暂且可抛开适配器不看,在onActivityCreated方法里面判断了当前是双页模式还是单页模式,可以理解为是大屏幕还是小屏幕,因为我们后后面会设置自适应大屏幕,当应用跑在大屏幕时新闻列表和新闻内容是同时出现了,所以能找到news_content_layout的实例。用isTwoPane变量判断

  1. 实现双页模式
  • 首先修改activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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.fragmentbestpractice.MainActivity">

    <fragment
        android:id="@+id/news_title_fragment"
        android:name="com.example.fragmentbestpractice.NewTitileFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</FrameLayout>

  • 然后在res里面新建一个layout-large文件夹,里面新建activity_main.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="horizontal">

    <fragment
        android:id="@+id/news_title_fragment"
        android:name="com.example.fragmentbestpractice.NewTitileFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />
    <FrameLayout
        android:layout_width="0dp"
        android:layout_weight="3"
        android:layout_height="match_parent"
        android:id="@+id/news_content_layout">

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

双页模式下我们同时引入两个碎片,注意到news_content_layout在这个布局里面
NewTitileFragment 中的onActivityCreated方法中找的就是这个

  1. 我们接下来看这个适配器内部类,写在内部是为了方便访问NewTitileFragment 中的变量,如isTwoPane。这儿我们只看onBindViewHolder方法里面的内容
 @Override
        public void onBindViewHolder(final InnerNewsAdapter.ViewHolder holder, final int position) {
          final  News news = mNewsList.get(position);
            holder.newsItem.setText(news.getTitle());
            holder.newsItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (isTwoPane) {
                        NewsContentFragment newsContentFragment = (NewsContentFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.news_content_fragment);
                        //注意区分getFragmentManager
                        newsContentFragment.refresh(news.getTitle(), news.getContent());
                    }else {
                        NewsContentActivity.actionStart(getActivity(),news.getTitle(),news.getContent());
                    }
                }
            });

        }

我们为每个标题添加了点击事件,并判断当前是否为双页模式。
如果为双页模式,就直接获取NewsContentFragment的实例并刷新里面的内容,这里获取该实例有两种方式,一种是直接通过getFragmentManager的findFragmentById方法,这个可以在碎片里面直接用,第二种是通过过去相关联的活动再调用getSupportFragmentManager的findFragmentById方法,我在这儿用的是第二种,但是第一种更简单。
如果是单页模式NewsContentActivity的actionStart方法启动NewsContentActivity,并将标题和内容传过去。getActivity方法是获取与当前碎片关联的Activity,在这儿就是MainActivity,因为在它的布局将NewTitileFragment引入进去了
平板:

image

手机:
image

这个就讲到这儿,基本没什么难点

原创文章 43 获赞 6 访问量 792

猜你喜欢

转载自blog.csdn.net/qq_34088913/article/details/105946731