探究碎片
碎片(fragment)是一种可以嵌入在活动当中的UI片段,它能让程序更加合理充分地利用大屏幕空间,因此在平板上使用的十分广泛。
碎片的使用方式
碎片一般都是在平板开发中使用的,所以首先我们应该创建一个平板模拟器,并创建一个FragmentTest项目,开始我们的碎片学习。
碎片的简单用法
这里先写一个最简单的碎片示例来练练手,在一个活动中添加两个碎片,并让这两个碎片平分活动空间。
首先先新建一个左边的布局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_3"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center_horizontal"
/>
</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_gravity="center_horizontal"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textSize="20sp"
android:text="This is right fragment"
/>
</LinearLayout>
接着新建LeftFragment类,并让其继承自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;
public class LeftFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.left_fragment,container,false);
return view;
}
}
这里重写了Fragment的onCreateView()方法,然后通过LayoutInflater的inflate()方法将left_fragment布局动态加载进来,整个方法简单明了。用同样方法再建一个RightFragment类,代码如下:
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;
public class RightFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.right_layout,container,false);
return view;
}
}
最后修改activity_main.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_3"
android:text="BUTTON"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center_horizontal"
/>
</LinearLayout>
效果如预期一样:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1xo56oRS-1659931235731)(C:\Users\渣渣致\AppData\Roaming\Typora\typora-user-images\image-20220805104537461.png)]
动态添加碎片
碎片真正的强大在于在程序运行时动态的添加到活动当中,根据具体情况动态添加碎片,就可以将程序界面定制的多样化。
我们在前面的基础上继续完善,新建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="another fragment"
/>
</LinearLayout>
新建AnotherRightFragment作为右侧碎片,代码如下:
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;
public class AnotherFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull 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"
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"
/>
<FrameLayout
android:id="@+id/right_layout"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
下面我们在代码中向FrameLayout里添加内容,从而实现动态添加碎片的功能。修改MainActivity中的代码,如下所示:
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_3);
button.setOnClickListener(this);
replaceFragment(new RightFragment());
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.button_3:
replaceFragment(new AnotherFragment());
break;
default:
break;
}
}
private void replaceFragment(Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.right_layout,fragment);
transaction.commit();
}
}
可以发现,首先是在左边的按钮注册了点击事件,然后调用replaceFragment()方法将右侧碎片替换成AnotherRightFragment,结合replaceFragment代码可以看出,动态添加碎片主要分为5步
- 创建待添加的碎片实例
- 获取FragmentManager,在活动中可以直接通过调用getSupportFragmentManager()方法得到
- 开启事务,通过调用beginTransaction()方法开启
- 向容器内添加或替换碎片,一般用replace()方法实现,需要传入容器的id和待添加的碎片实例
- 提交事务,调用commit()方法完成
这样就完成了活动中动态添加碎片的功能,重新运行程序,可以看到和之前相同的界面,然后点击下按钮,左边的碎片就发生了变化。
在碎片中模拟返回栈
虽然实现了向活动中动态添加碎片的功能,不过按下back按钮后程序就会直接退出。如果这里我们想模仿类似于返回栈的效果,按下back返回到上一个碎片,该怎么实现呢?
FragmentTransaction中提供了一个addToBackStack()方法,可以用于将事务添加到返回栈中,修改MainActivity中的代码,如下:
private void replaceFragment(Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.right_layout,fragment);
transaction.addToBackStack(null);
transaction.commit();
}
FragmentTransaction中的addToBackStack()方法,可以直接接收一个名字用来描述返回栈的状态,一般传入null即可。
碎片和活动之间进行通信
为了方便碎片和活动之间进行通信,FragmentManager提供了一个类似于findViewById()的方法,专门用于从布局文件中获取碎片的实例,代码如下所示:
RightFragment rightFragment = (RightFragmen) getSupportFragmentManager().findFragmentById(R.id.right_fragment);
调用FragmentManager的findFragmentById()方法,可以在活动中获得相应的碎片实例,然后就能轻松的调用碎片里的方法了。
掌握了如何在活动中调用碎片里的方法,那碎片中又该怎么样调用活动里的方法呢?其实这就更简单了,在每个碎片中都会通过调用getActivity()方法来得到和当前碎片相关联的活动实例,代码如下:
MainActivity activity = (MainActivity)getActivity();
有了活动实例后,在碎片中调用活动里的方法就变得轻而易举了。另外当碎片中需要使用Context对象时,也可以使用getActivity()方法,因为获取到的活动本身就是一个Context对象。
这时还有一个问题:既然碎片和活动之间的通信问题已经解决了,那么碎片和碎片之间可不可以通信呢——答案时肯定的。
碎片的生命周期
和活动一样,碎片也有自己的生命周期,并且它和活动的生命周期非常的像。
碎片的状态和回调
活动在其生命周期会经历运行状态、暂停状态、停止状态和销毁状态4种。类似地,每个碎片在其生命周期也会经历这几个状态,只不过在一些细小地地方会有区别。
-
运行状态
当碎片可见时处于运行状态
-
暂停状态
另一个为占满屏幕地碎片被添加到了栈顶,与他关联地碎片会进入到暂停状态。
-
停止状态
当一个活动进入停止状态时,与它相关联的碎片就会进入到停止状态,或者通过调用FragmentTransaction的remove()、replace()方法将碎片从活动中移除,但如果在事务提交之前调用addToBackStack()方法,这时的碎片也会进入到停止状态。进入停止状态的碎片对用户来说是完全不可见的,而且又可能会被系统回收。
-
销毁状态
碎片总是依附于活动存在的,因此活动被销毁的时候,与它相关联的碎片就会进入到销毁状态。或者通过调用FragmentTransaction的remove()、replace()方法将碎片从活动中删除,但是在事务提交之前并没有调用addToBackStack()方法,这时的碎片会进入销毁状态。
Fragment也提供了一系列的回调方法,以覆盖碎片生命周期的每个环节。其中,活动中有的回调方法,碎片几乎都有。重点是以下几个回调:
- onAttach() 当碎片和活动建立关联的时候调用
- onCreateView() 为碎片创建视图(加载布局)时调用
- onActivityCreated() 确保与碎片相关联的活动一定已经创建完毕
- onDestoryView() 当碎片关联的视图被移除时调用
- onDetach() 当碎片和活动解除关联的时候调用
碎片完整生命周期示意图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aAvK3H0Y-1659931235734)(F:\Typora\Typora\md\android\picture\4-2.png)]
体验碎片的生命周期
动态加载布局的技巧
动态添加碎片功能很强大,但是只是在布局文件中进行添加和替换操作,如果程序能够根据设备的分辨率或者屏幕大小在运行时来决定哪个布局,那发挥空间将更大。
使用限定符
要怎么才能运行时判断程序是双页还是单页模式呢?这就要借助限定符来实现了。以下用例子来学习用法:
修改FragmentTest项目中的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.activitytest.LeftFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
这里将多于代码都删掉,只留下一个左侧碎片,并让他充满整个父布局。接着在res目录下新建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_weight="1"
android:layout_height="match_parent"
/>
<fragment
android:id="@+id/right_fragment"
android:name="com.example.fragmenttest.RightFragment"
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="3"
/>
</LinearLayout>
可以发现,layout/activity_main.xml只包含了一个碎片,即单页模式。而layout-large/activity_main.xml只包含了两个碎片,即双页模式。其中large 就是限定符,那些屏幕被认为是large的设备就会自动加载layout-large文件下的布局,而小屏幕就会加载layout文件下的布局。
然后将MainActivity中的replaceFragment()方法里的代码注释掉,并在平板上重新运行程序,效果如下:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-t8yluaCJ-1659931235735)(C:\Users\渣渣致\AppData\Roaming\Typora\typora-user-images\image-20220805225647321.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ylOYotiu-1659931235737)(C:\Users\渣渣致\AppData\Roaming\Typora\typora-user-images\image-20220805225723892.png)]
Android中常用的限定符
Android中常用的限定符如下表:
屏幕特征 | 限定符 | 描述 |
---|---|---|
大小 | small | |
normal | ||
large | ||
xlarge | ||
分辨率 | ldpi | 提供给低分辨率的设备资源(120dpi以下) |
mdpi | 120~160dpi | |
hdpi | 160~240dpi | |
xhdpi | 240dpi~320dpi | |
xxhdpi | 320~480dpi |
屏幕特征 | 限定符 | 描述 |
---|---|---|
方向 | land | 提供给横屏设备的资源 |
port | 提供给竖屏设备的资源 |
使用最小宽度限定符
前面虽然使用large成功解决了单页和双页的判断问题,不过很快又有一个新的问题出现了,large到底是多大呢?我们希望更加灵活的为不同设备加载布局,不管是不是被系统认定为large,这时就可以使用最小宽度限定符
最小宽度限定符允许我们对屏幕的宽度指定一个最小值(以dp为单位),然后以这个最小值为临界点,屏幕宽度大于这个值的设备就加载一个布局,屏幕宽度小于这个值的设备就加载另外一个布局
在res目录下新建layout-sw600dp文件夹,然后再这个文件夹新建activity_main.xml布局。
碎片的最佳实践——一个简易版的新闻应用
碎片是用来解决屏幕空间利用不足的问题,但是如果在实际开发中所有程序都提供一个手机版一个Pad版,这样的话花费的人力物力就会增加,维护两个版本也意味着新功能会写两遍,bug也会改两遍,这样十分的麻烦。这个实践目的是同时兼容手机和平板的应用程序。
新建一个FragmentBestPractice项目,由于编写新闻列表会用到RecycleView,因此需要在app/build.gradle当中加入依赖库,如下所示:
dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
}
接下来我们准备一个新闻实体类,新建类News,代码如下所示:
public class News {
private String title;
private String content;
public String getTitle(){
return title;
}
public String setTitle(String title){
return this.title = title;
}
public String getContent(){
return content;
}
public String setContent(){
return this.content = content;
}
}
News类title表示新闻标题,content字段表示新闻内容。接着新建布局文件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:orientation="horizontal"
android:visibility="invisible"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/news_title"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_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_height="0dp"
android:layout_width="match_parent"
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来实现的,将View的宽高设置为1dp,再通过background属性给细线设置一下颜色即可。
然后再新建一个NewsContentFragment类,继承自Fragment,代码如下所示:
public class NewsContentFragment extends Fragment {
private View view;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.new_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);
}
}
首先onCreateView()方法里加载了我们刚创建的news_content_frag布局,接下来提供了refresh方法,这个方法就是用于将新闻的标题和内容显示在界面上的。
这样我们就把新闻内容的碎片和布局就创建好了,但是它们都是在双页模式中使用的,如果想在单页模式中使用的话,我们还要再创建一个活动。新建一个NewsContentActivity,并将布局名指定成news_content,然后修改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:id="@+id/news_content_fragment"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:name="com.example.fragmenttest.NewsContentFragment"
/>
</LinearLayout>
这里充分使用了代码的复用性,直接在布局中引入了NewsContentFragment,这样也就相当于把news_content_frag布局的内容自动加了进来。
然后修改NewsContentActivity中的代码,如下所示:
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);//刷新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">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/news_title_recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
这个布局的代码就非常简单了,里面只有一个用于显示新闻列表的RecyclerView。既然要用到RecyclerView那么必定少不了子项的布局。新建news_item.xml作为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="match_parent"
android:maxLines="1"
android:ellipsize="end"
android:textSize="18sp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="15dp"
android:paddingBottom="15dp" >
</TextView>
子项布局只有TextView。android:ellipsize用于设定当文本内容超出控件宽度时,文本缩略方式,这里指定成end表示在尾部进行忽略。
接下来就需要一个用于展示新闻列表的地方。这里新建NewsTitleFragment作为展示新闻列表的碎片,代码如下所示:
public class NewsTitleFragment extends Fragment {
private boolean isTwoPane;
@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);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(getActivity().findViewById(R.id.news_content_fragment) != null){
isTwoPane = true;
} else {
isTwoPane = false;
}
}
}
可以看到,NewsTitleFragment中并没有很多代码,在onCreateView()方法中加载了news_title_frag布局,这个没什么好说。在onActivityCreated()方法中,这个方法通过在活动中能否找到一个id为news_content_layout的View来判断当前时双页模式还是单页模式,但是我们还需要;利用限定符,在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:layout_height="match_parent"
android:layout_width="match_parent"
android:name="com.example.fragmenttest.NewsTitleFragment"
/>
</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:layout_width="0dp"
android:layout_height="match_parent"
android:name="com.example.fragmenttest.NewsContentFragment"
/>
</FrameLayout>
</LinearLayout>
可以看出,双页模式我们引入了两个碎片,并将新闻内容的碎片放在了一个FrameLayout布局下,而这个布局的id正是news_content_layout,只要能找到这个id就是双页模式,找不到就是单页模式。
现在大部分的工作都已经完成了,只需要通过NewsTitleFragment中通过RecyclerView中通过RecyclerView将新闻列表表示出来。在NewsTitleFragment中新建一个内部类NewsAdapter来作为RecyclerView的适配器,如下:
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;
}
@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;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position, @NonNull List<Object> payloads) {
News news = mNewsList.get(position);
holder.newsTitleText.setText(news.getTitle());
}
@Override
public int getItemCount() {
return mNewsList.size();
}
}
}
最后一步是收尾工作,就是向RecyclerView中填充数据。修改NewsTitleFragment中的代码,如下所示:
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 = (RecyclerView) view.findViewById(R.id.news_title_recyclerView);
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<=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();
}
这样我们就实现了单双页的新闻界面,并且兼容性也非常的好。
谢谢阅读!