看了《第二行代码》一段时间了,这次按照书上的内容,用碎片写个新闻应用。
先新建一个空项目day07_FragmentBestPractice
一、一个新闻就是一个碎片
1、单个新闻的布局
news_content_frag.xml
头部显示新闻标题,正文显示新闻内容,中间使用一条细线View
将其分隔开
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/visibility_layout"
android:orientation="vertical"
android:visibility="invisible">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/news_title"
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>
2、将布局变成碎片
NewsContentFragment.java
,其中用refresh()
将标题和内容加载单个新闻的布局
public class NewsContentFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.news_content_frag, container, false);
}
public void refresh(String newsTitle, String newsContent){
View visibilityLayout = getView().findViewById(R.id.visibility_layout);
visibilityLayout.setVisibility(View.VISIBLE);
TextView newsTitleText = getView().findViewById(R.id.news_title);
TextView newsContentText = getView().findViewById(R.id.news_content);
newsTitleText.setText(newsTitle);
newsContentText.setText(newsContent);
}
}
二、一页新闻就是一个活动
新建一个活动NewsContentActivity
和其对应的布局news_content.xml
1、一页新闻的布局
news_content.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">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/news_content_fragment"
android:name="NewsContentFragment"/>
</LinearLayout>
2、 将标题和内容传入碎片
NewsContentActivity.java
用FragmentManager
的findFragmentById()
得到NewsContentFragment
实例,调用其refresh()
方法就可以让其显示数据
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);
}
}
三、一堆新闻放到一个碎片
1、添加依赖库
app/build.gradle
添加滚动控件Recyclerview
implementation 'androidx.recyclerview:recyclerview:1.0.0'
2、新闻列表的布局
news_titile_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">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/news_title_recycler_view"/>
</LinearLayout>
子项布局news_item.xml
padding
是内边距,android:ellipsize
是文本超出控件宽度时的缩略方式,end
指在尾部缩略
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/news_title"
android:maxLines="1"
android:ellipsize="end"
android:textSize="18sp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="15dp"
android:paddingBottom="15dp">
</TextView>
3、将布局变成碎片
NewsTitileFragment.java
public class NewsTitleFragment extends Fragment {
private boolean isTwoPane;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.news_title_frag, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
isTwoPane = getActivity().findViewById(R.id.news_content_layout) != null;
}
}
在onActivityCreated()
中,通过其能否在活动中找到id
为news_content_layout
的View
来判断当前是单双页模式,这就要借助限定符了,下面我们将实现它
四、一张新闻列表是一个活动
1、默认单页模式
修改主布局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:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/news_title_fragment"
android:name="com.example.day07_fragmentbestpractice.NewsTitleFragment"/>
</FrameLayout>
2、双页模式
新建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:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="@+id/news_title_fragment"
android:name="com.example.day07_fragmentbestpractice.NewsTitleFragment"/>
<FrameLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3"
android:id="@+id/news_content_layout">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/news_content_fragment"
android:name="com.example.day07_fragmentbestpractice.NewsContentFragment"/>
</FrameLayout>
</LinearLayout>
双页模式中有id
为news_content_layout
的View
,这样刚才的第三步就不会报错了
3、类和适配器
我们在新闻列表页使用RecyclerView
展示数据,所以要在这里建立对应的类和适配器
a、新闻类
News.java
,新闻实体类
public class News {
private String title;
private String content;
public String getTitle(){
return title;
}
public void setTitile(String title){
this.title = title;
}
public String getContent(){
return content;
}
public void setContent(String content){
this.content = content;
}
}
b、适配器
修改NewsTitleFragment.java
,将适配器作为内部类添加进去,可以直接访问内部变量
public class NewsTitleFragment extends Fragment {
private boolean isTwoPane;
......
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);
}
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull 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;
}
public NewsAdapter(List<News> newsList) {
mNewsList = newsList;
}
@Override
public int getItemCount() {
return mNewsList.size();
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
News news = mNewsList.get(position);
holder.newsTitleText.setText(news.getTitle());
}
}
}
五、一个新闻应用一下子完成
1、填充数据
修改NewsTitleFragment.java
,完成初始化
public class NewsTitleFragment extends Fragment {
......
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.news_title_frag, container, false);
RecyclerView newsTitleRecyclerView = 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;
}
private List<News> getNews(){
List<News> newsList = new ArrayList<>();
for (int i = 1;i <= 100; i++){
News news = new News();
news.setTitle("这是新闻标题 "+ 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();
}
}
2、运行
未点击标题
点击标题后
效果很不错!