碎片實踐惋耙,簡易版的新聞應用
1.首先添加RecyclerView的依賴庫:
簡便方法:File->Project Structure->Dependencies->點+號找到recyclerview添加后點擊ok就自動給項目添加了依賴庫
- 首先建一個新聞的實體類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表示新聞內(nèi)容
- 新建布局news_content_frag.xml作為新聞內(nèi)容的布局
<?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實現(xiàn)細分隔線
- 新建一個NewsContentFragment繼承Fragment而钞,并提供一個refresh方法用于刷新內(nèi)容
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實例調(diào)用的
- 以上的這個碎片是用于雙頁模式的
- 我們再建一個空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方法作用是方便別的活動啟動這個活動時傳遞數(shù)據(jù)翎猛,要記住這種寫法胖翰。
在onCreate方法里面FragmentManager的findFragmentById的方法獲得NewsContentFragment的實例,然后調(diào)用它的refresh方法刷新顯示內(nèi)容切厘,從而刷新了NewsContentActivity里面顯示的內(nèi)容
- 接下來創(chuàng)建一個用于顯示新聞列表的布局萨咳,利用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"/>
- 接下來新建一個用于展示新聞列表的Fragment,在這個碎片中我們順帶創(chuàng)建一個用于顯示標題列表的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);
//注意區(qū)分getFragmentManager
newsContentFragment.refresh(news.getTitle(), news.getContent());
}else {
NewsContentActivity.actionStart(getActivity(),news.getTitle(),news.getContent());
}
}
});
}
@Override
public int getItemCount() {
return mNewsList.size();
}
}
}
暫且可拋開適配器不看,在onActivityCreated方法里面判斷了當前是雙頁模式還是單頁模式疫稿,可以理解為是大屏幕還是小屏幕培他,因為我們后后面會設置自適應大屏幕鹃两,當應用跑在大屏幕時新聞列表和新聞內(nèi)容是同時出現(xiàn)了,所以能找到news_content_layout的實例靶壮。用isTwoPane變量判斷
- 實現(xiàn)雙頁模式
- 首先修改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方法中找的就是這個
腾降。
- 我們接下來看這個適配器內(nèi)部類,寫在內(nèi)部是為了方便訪問NewTitileFragment 中的變量碎绎,如isTwoPane螃壤。這兒我們只看onBindViewHolder方法里面的內(nèi)容
@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);
//注意區(qū)分getFragmentManager
newsContentFragment.refresh(news.getTitle(), news.getContent());
}else {
NewsContentActivity.actionStart(getActivity(),news.getTitle(),news.getContent());
}
}
});
}
我們?yōu)槊總€標題添加了點擊事件,并判斷當前是否為雙頁模式筋帖。
如果為雙頁模式奸晴,就直接獲取NewsContentFragment的實例并刷新里面的內(nèi)容,這里獲取該實例有兩種方式日麸,一種是直接通過getFragmentManager的findFragmentById方法寄啼,這個可以在碎片里面直接用,第二種是通過過去相關(guān)聯(lián)的活動再調(diào)用getSupportFragmentManager的findFragmentById方法代箭,我在這兒用的是第二種墩划,但是第一種更簡單。
如果是單頁模式NewsContentActivity的actionStart方法啟動NewsContentActivity嗡综,并將標題和內(nèi)容傳過去乙帮。getActivity方法是獲取與當前碎片關(guān)聯(lián)的Activity,在這兒就是MainActivity极景,因為在它的布局將NewTitileFragment引入進去了
平板:
手機:
這個就講到這兒察净,基本沒什么難點