第4章 探究Fragment
4.1 Fragment
Fragment是一种可以嵌入在Activity当中的UI片段,它能让程序更加合理和充分地利用大屏幕的控件,因而在平板上应用广泛。它和Activity很像,同样能包含布局,有自己的生命周期。
如果将手机上的一些页面设计直接应用到平板上,会导致界面上有大量的空白区域。在这种情况下,可以考虑通过在同一个活动里引入多个碎片,将屏幕空间充分利用起来。如下图:
4.2 Fragment的使用方式
4.2.1 Fragment的简单用法
首先要创建一个平板模拟器或者准备一台平板,然后新建一个FragmentTest项目。先写一个最简单的碎片示例,在一个活动当中添加两个碎片,并让这两个碎片平分活动空间。
新建一个左侧碎片布局left_fragment.xml,代码如下:
<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"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Button"/>
</LinearLayout>
同理,新建右侧碎片布局right_fragment.xml,代码略。将布局背景设置成了绿色,并放置了一个TextView用于显示一段文本。
接着新建一个LeftFragment类,并让它继承自Fragment。注意:这里会有两个不同包下的Fragment:一个是系统内置的android.app.Fragment,一个是AndroidX库中的androidx.fragm-ent.app.Fragment。这里请一定要使用AndroidX库中的Fragment,因为它可以让Fragment的特性在所有Android系统版本中保持一致,而系统内置的Fragment在Android 9.0版本中已被废弃。编写LeftFragment中的代码如下:
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布局动态加载进来。用同样的方法再新建一个RightFrag-ment,代码略。
接下来修改activity_main.xml中的代码:
<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"/>
<fragment
android:id="@+id/right_fragment"
android:name="com.example.fragmenttest.RightFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
</LinearLayout>
使用<fragment>标签在布局中添加Fragment,其中指定的大多数属性都是熟悉的,只不过这里还需要通过android:name属性来显式指明要添加的Fragment类名,注意一定要将类的包名也加上。
4.2.2 动态添加Fragment
Fragment的强大之处在于,它可以在程序运行时动态地添加到Activity中。
新建another_right_fragment.xml,代码如下:
<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="This is another right fragment"/>
</LinearLayout>
这个布局文件和right_fragment.xml中的代码基本相同,只是改了背景色和显示文字。然后新建AnotherRightFragment作为另一个右侧Fragment,在onCreateView()方法中加载刚刚创建的anothe-r_right_fragment布局,代码略。修改activity_main.xml,代码如下:
<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_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
</LinearLayout>
现在将右侧Fragment替换成一个FrameLayout中,所有控件会默认摆放在布局的左上角。由于这里仅需要在布局里放入一个Fragment,不需任何定位,因此适合使用FrameLayout。
下面在代码中向FrameLayout里添加内容,从而实现动态添加Fragment的功能。修改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);
button.setOnClickListener(this);
replaceFragment(new Right_Fragment());
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.button:
replaceFragment(new AnotherRightFragment());
break;
default:
break;
}
}
private void replaceFragment(Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.right_layout,fragment);
transaction.commit();
}
}
首先给左侧Fragment中的按钮注册了一个点击事件,然后调用replaceFragment()方法动态添加了RightFragment。当点击左侧Fragment中的按钮时,又会调用replaceFragment()方法将右侧Fragment替换成AnotherRightFragment。结合replaceFragment()方法中的代码可以看出,动态加载Fragment主要分为5步。
- 创建待添加的Fragment实例
- 获取FragmentManager,在活动中可直接通过调用getSupportFragmentManager()方法得到
- 开启一个事务,通过调用beginTransaction()方法开启
- 向容器内添加或替换Fragment,一般用replace()方法实现,需传入容器的id和待添加的Fra-gment实例
- 提交事务,调用commit()方法来完成。
4.2.3 在碎片中模拟返回栈
上面的应用通过点击按钮添加了一个碎片之后,按下Back键会直接退出。如果想模仿类似于返回栈的效果,按下Back键可以回到上一个碎片,如何实现?
FragmentTransaction中提供了一个addToBackStack()方法,可以用于将一个事务添加到返回栈中,修改MainActivity中的代码,如下:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
...
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即可。
4.2.4 Fragment和Activity之间进行通信
问题背景:Fragment和Activity都是各自存在于一个独立的类中,如何实现在Activity中调用Frag-ment里的方法,或者在Fragment中调用Activity里的方法?
FragmentManager提供了一个类似于findViewById()的方法,专门用于从布局文件中获取Fra-gment的实例,代码如下:
RightFragment rightFragment = (RightFragment) getFragmentManager() .findFragmentById(R.id.right_fragment);
调用FragmentManager的findFragmentById()方法,可以在Activity中得到相应Fragment的实例,然后就能轻松调用Fragment里的方法了。
相反,在每个Fragment中都可以通过调用getActivity()方法来得到和当前Fragment相关联的Activity实例,代码如下:
MainActivity activity = (MainActivity) getActivity();
有了Activity实例后,在Fragment中调用Activity里的方法就变得轻而易举了。当Fragment中需要使用Context对象时,也可以使用getActivity()方法,因为获取到的Activity本身就是一个Context对象。
4.3 Fragment的生命周期
4.3.1 Fragment的状态和回调
- 运行状态 当一个Fragment是可见,并且它所关联的Activity处于运行状态时,该碎片也处于运行状态。
- 暂停状态 当一个Activity进入暂停状态时(由于另一个未占满屏幕的活动被添加到了栈顶),与它相关联的可见Fragment就会进入到暂停状态。
- 停止状态 当一个Activity进入停止状态时,与它相关联的碎片就会进入到停止状态,或者通过调用FragmentTransaction的remove()、replace()方法将碎片从活动中移除,但如果在事务提交之前调用addToBackStack()方法,这时的碎片也会进入到停止状态。进入停止状态的Fragment对用户来说是完全不可见的,有可能会被系统回收。
- 销毁状态 Fragment总是依附于Activity而存在的,因此当Activity被销毁时,与它相关联的碎片就会进入到销毁状态。或者通过调用FragmentTransaction的remove()、replace()方法将Fragment从Activity中移除,但在事务提交之前并没有调用addToBackStack()方法,这时的Fragment也会进入到销毁状态。
同样地,Fragment类中也提供了一系列的回调方法,以覆盖Fragment生命周期的每个环节。其中,Activity中有的回调方法,Fragment中几乎都有,除此之外,Fragment还提供了一些附加的回调方法:
- onAttach() ---- 当Fragment和Activity建立关联的时候调用。
- onCreateView() ---- 为Fragment创建视图(加载布局)时调用。
- onActivityCreated() ---- 确保与Fragment相关联的Activity一定已经创建完毕的时候调用
- onDestroyView() ---- 当与Fragment关联的视图被移除的时候调用
- onDetach() ---- 当Fragment和Activity解除关联的时候调用
Fragment完整的生命周期示意图可参考下图:
4.3.2 体验Fragment的生命周期
下面通过一个例子实践下,在FragmentTest项目的基础上,修改RightFragment中的代码:
public class Right_Fragment extends Fragment {
public static final String TAG = "RightFragment";
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
Log.d(TAG,"onAttach");
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG,"onCreate");
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.right_fragment,container,false);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d(TAG,"onActivityCreated");
}
@Override
public void onStart() {
super.onStart();
Log.d(TAG,"onStart");
}
@Override
public void onResume() {
super.onResume();
Log.d(TAG,"onResume");
}
@Override
public void onPause() {
super.onPause();
Log.d(TAG,"onPause");
}
@Override
public void onStop() {
super.onStop();
Log.d(TAG,"onStop");
}
@Override
public void onDestroyView() {
super.onDestroyView();
Log.d(TAG,"onDestroyView");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG,"onDestroy");
}
@Override
public void onDetach() {
super.onDetach();
Log.d(TAG,"onDetach");
}
}
运行程序,观察logcat中的打印信息,可以看到,当RightFragment第一次被加载到屏幕上时,会依次执行onAttach()、onCreate()、onCreateView()、onActivityCreated()、onStart()和onResume()方法。
然后点击LeftFragment中的按钮。由于AnotherRightFragment替换了RightFragment,此时的RightFragment进入了停止状态,因此onPause()、onStop()和onDestroyView()方法会得到执行。当然如果在替换的时候没有调用addToBackStack()方法,此时的RightFragment就会进入销毁状态,onDestroy()和onDetach()方法就会得到执行。
接着按下Back键,RightFragment会重新回到屏幕。由于RightFragment重新回到了运行状态,因此onActivityCreated()、onStart()和onResume()方法会得到执行。注意此时onCreate()和onCreateView()方法并不会执行,因为借助了addToBackStack()方法使得RightFragment和它的视图并没有销毁。
再次按Back键退出程序。依次执行onPause()、onStop()、onDestroView()、onDestroy()和onDetach()方法,最终将Activity和Fragment一起销毁。
在Fragment中也是可以通过onSaveInstanceState()方法来保存数据的,因为进入停止状态的Fragment有可能在系统内存不足的时候被回收。保存下来的数据在onCreate()、onCreateView()和onActivityCreated()这3个方法中都可以重新得到,它们都含有一个Bundle类型的savedInstance-State参数。
4.4 动态加载布局的技巧
问题背景:程序能够根据设备的分辨率或屏幕大小在运行时来决定加载哪个布局
4.4.1 使用限定符
借助限定符(Qualifiers)可以在运行时判断程序应该是使用双页模式还是单页模式。修改FragmentTest项目中的activity_main.xml文件,代码如下:
<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="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
接着在res目录下新建layout-large文件夹,在这个文件夹下新建一个布局activity_main.xml:
<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"/>
<fragment
android:id="@+id/right_fragment"
android:name="com.example.fragmenttest.RightFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3"/>
</LinearLayout>
可以看到,layout/activity_main布局只包含了一个Fragment,即单页模式,而layout-large/activity_main布局包含了两个Fragment,即双页模式。其中large是一个限定符,那些屏幕被认为是large的设备就会自动加载layout-large文件夹下面的布局,而小屏幕的设备则还是会加载layout文件夹下的布局。
然后将MainActivity 中的replaceFragment()方法里的代码注释掉,并在不同设备上运行程序,会看到平板上显示双页,手机上显示单页。
Android中一些常见的限定符可以参考下表:
屏幕特征 | 限定符 | 描述 |
大小 | small | 提供给小屏幕设备的资源 |
normal | 提供给中等屏幕设备的资源 | |
large | 提供给大屏幕设备的资源 | |
xlarge | 提供给超大屏幕设备的资源 | |
分辨率 | ldpi | 提供给低分辨率设备的资源(120dpi以下) |
mdpi | 提供给中等分辨率设备的资源(120dpi~160dpi) | |
hdpi | 提供给高分辨率设备的资源(160dpi~240dpi) | |
xhdpi | 提供给超高分辨率设备的资源(240dpi~320dpi) | |
xxhdpi | 提供给超超高分辨率设备的资源(320dpi~480dpi) | |
方向 | land | 提供给横屏设备的资源 |
port | 提供给竖屏设备的资源 |
4.4.2 使用最小宽度限定符
最小宽度限定符(Smallest-widthQualifier),允许对屏幕的宽度指定一个最小值(以dp为单位),然后以这个最小值为临界点,屏幕宽度大于这个值的设备就加载一个布局,屏幕宽度小于这个值的设备就加载另一个布局。
在res目录下新建layout-sw600dp文件夹,然后在这个文件夹下新建activity_main.xml布局,代码同上,略。当程序运行在屏幕宽度大于600dp的设备上时,会加载layout-sw600dp/ acti-vity_ main布局,当程序运行在屏幕宽度小于600dp的设备上时,则仍然加载默认的layout/activity _main布局。
4.5 Fragment的最佳实践 ---- 一个简易版的新闻应用
目标:编写一个同时兼容手机和平板的简易版新闻应用
新建一个FragmentBestPractice项目。要准备一个新闻的实体类,新建类News如下:
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;
}
}
接着新建布局文件news_content_frag.xml,用于作为新闻内容的布局:
<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实现的,将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 = 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); //刷新新闻的内容
}
}
首先在onCreateView()方法里加载刚刚创建的news_content_frag布局。接下来提供了一个refresh()方法,用于将新闻的标题和内容显示在界面上。这里通过findViewById()方法分别获取到新闻标题和内容的控件,然后将方法传递进来的参数设置进去。注意,当调用了refresh()方法时,需要将刚才隐藏的新闻布局设置成可见。
这样新闻内容的Fragment和布局都创建好了,但是它们都是在双页模式中使用的,如果想在单页模式中使用,还需再创建一个Activity。右击com.example.fragmentbestpractice包----New----Activity----Empty Activity,新建一个NewsContentActivity。修改activity_news_content.xml:
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/newsContentFrag"
android:name="com.example.fragmentbestpractice.NewsContentFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</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.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); //刷新NewsContentFragment界面
}
}
在onCreate()方法中通过Intent获取到传入的新闻标题和新闻内容,然后调用FragmentMan-age的findFragmentById()方法得到了NewsContentFragment的实例。接着调用它的refresh()方法,将新闻标题和内容传入,就可以把数据显示出来。actionStart()方法见前面章节,启动Activity的最佳写法。
接下来还需创建一个用于显示新闻列表的布局,新建news_title_frag.xml,代码如下:
<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_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
既然要用RecyclerView,那么必定少不了子项的布局。新建news_item.xml作为Recycler-View子项的布局,代码如下:
<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:singleLine="true"
android:ellipsize="end"
android:textSize="18sp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="15dp"
android:paddingBottom="15dp"/>
子项的布局只有一个TextView,其中:
- android:padding ---- 表示给控件的周围加上补白
android:singleLine---- 设置为true表示让这个TextView只能单行显示(已弃用)- android:ellipsize ---- 用于设定当前文本内容超过控件宽度时,文本的缩略方式,这里指定成end表示在尾部进行缩略。
接下来需要一个用于展示新闻列表的地方。新建NewsTitleFragment作为展示新闻列表的Fragment,代码如下:
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.onViewCreated(savedInstanceState);
if (getActivity().findViewById(R.id.news_content_layout) != null){
isTwoPane = true; //可以找到news_content_layout布局时,为双页模式
}else{
isTwoPane = false; //找不到news_content_layout布局时,为单页模式
}
}
}
在onCreateView()方法中加载了news_title_frag布局。这里需要注意onActivityCreated()方法已经被弃用,与 Fragment 视图有关的代码应在 onViewCreated()(在 onActivityCreated() 之前调用)中执行,而其他初始化代码应在 onCreate() 中执行。如需专门在 Activity 的 onCreate() 完成时接收回调,应在 onAttach() 中的 Activity 的 Lifecycle 上注册 LifeCycleObserver,并在收到 onCreate() 回调后将其移除。其中通过在Activity中能否找到一个id为news_content_layout的View来判断当前是双页模式还是单页模式,因此需要让这个id为news_content_layout的View只在双页模式中才会出现。
借助限定符可以实现上述效果。首先修改activity_main.xml中的代码:
<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:name="com.example.fragmentbestpractice.NewsTitleFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
上述代码表示,在单页模式下,只会加载一个新闻标题的Fragment。
然后新建layout-sw600dp文件夹,在这个文件夹下再新建一个activity_main.xml文件:
<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.fragmentbestpractice.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:name="com.example.fragmentbestpractice.NewsContentFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
</LinearLayout>
在双页模式下同时引入两个Fragment,并将新闻内容的Fragment放在了一个FrameLayout布局下,而这个布局的id正是news_content_layout。因此,能够找到这个id的时候就是双页模式,否则就是单页模式。
在NewsTitleFragment中新建一个内部类NewsAdapter来作为RecyclerView的适配器,如下:
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);
}
}
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 view) {
News news = mNewsList.get(holder.getAdapterPosition());
if (isTwoPane){
//如果是双页模式,则刷新NewsContentFragment中的内容
NewsContentFragment newsContentFragment = (NewsContentFragment)
getParentFragmentManager().findFragmentById(R.id.news_content_fragment);
newsContentFragment.refresh(news.getTitle(), news.getContent());
}else {
//如果是单页模式,则直接启动NewsContentActivity
NewsContentActivity.actionStart(getActivity(), news.getTitle(), news.getContent());
}
}
});
return holder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
News news = mNewsList.get(position);
holder.newsTitleText.setText(news.getTitle());
}
@Override
public int getItemCount() {
return mNewsList.size();
}
}
}
需要注意的是,之前都是将适配器写成了一个独立的类,其实也是可以写成内部类的,这里写成内部类的好处就是可以直接访问NewsTitleFragment的变量,比如isTwoPane。
onCreateViewHolder()方法中注册的点击事件,首先获取到了点击项的News实例,然后通过isTwoPane变量判断当前是单页还是双页,如果是单页模式,就启动一个新的活动去显示新闻内容,如果是双页模式,就更新新闻内容碎片里的数据。
最后一步,向RecyclerView中填充数据。修改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);
RecyclerView newsTitleRecyclerView = (RecyclerView) 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 <= 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();
}
...
}
可以看到,onCreateView()方法中添加了RecyclerView标准的使用方法。在Fragment中使用RecyclerView和在Activity中使用几乎一模一样。另外,调用了getNews()方法来初始化50条模拟的新闻数据,同样使用了一个getRandomLengthContent()方法来随机生成新闻内容的长度。