第四章–探索Fragment
什么是Fragment
Fragment是一种可以嵌入在活动当中的UI片段,能让程序更加合理和充分地利用大屏幕的空间,因而在平板上应用得非常广泛。可以将Fragment理解成一个迷你型的活动,包含了布局、生命周期。
Fragment使用方式
Fragment简单使用方法
在一个活动中添加两个Fragment,并让两个Fragment平分活动空间。
- 新建一个左侧Fragment布局
<?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"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Button"/>
</LinearLayout>
- 新建一个右侧Fragment布局
<?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_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textSize="20dp"
android:text="This is right fragment"/>
</LinearLayout>
- 新建一个LeftFragment类
public class LeftFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.left_fragment, container, false);
return view;
}
}
- 建议使用support-v4库中的Fragment(android.support.v4.app.Fragment),可以让Fragment在所有Android系统版本中保持功能一致性。
- 重写Fragment的public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)方法。
- LayoutInflater inflater参数:用于对Fragment中的任何view进行inflate的LayoutInflater对象
- ViewGroup container参数:如果非空,这是Fragment的UI应附加到的父视图。 该Fragment不应该添加view本身,但可以用于生成view的LayoutParams。
- Bundle savedInstanceState:如果非空,则此Fragment正在按照此处给出的先前保存的状态重新构建。
inflate(int resource, ViewGroup root, boolean attachToRoot)方法,加载指定XML布局
- resource参数:要加载的XML布局资源的标识(例如R.layout.main_page
- root参数:可选view是生成的层次结构的父级(如果attachToRoot为true),或者只是为返回的层次结构的根提供一组LayoutParams值的对象(如果attachToRoot为false)
attachToRoot参数:inflated层次结构是否应附加到根参数? 如果为false,则root仅用于为XML中的根视图创建LayoutParams的正确子类。
新建一个RightFragment类
public class RightFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.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.myfzhou.fragmenttest.LeftFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
<fragment>
<android:id="@+id/right_layout">
<android:name="com.example.myfzhou.fragmenttest.RightFragment"
<android:layout_width="0dp">
<android:layout_height="match_parent">
<android:layout_weight="1"/>
</LinearLayout>
动态添加Fragment
新建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="This is another right fragment"/>
</LinearLayout>
新建AnotherRightFragment作为另一个右侧碎片
public class AnotherRightFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.another_right_fragment, container, false);
return view;
}
}
修改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.myfzhou.fragmenttest.LeftFragment"
android:layout_width="match_parent"
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">
<!--</FrameLayout>-->
</LinearLayout>
- 将前面的右侧Fragment替换成了一个FrameLayout,这是Android中最简单的一种布局,所有的控件默认都会摆放在布局的左上角
向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 = findViewById(R.id.button);
button.setOnClickListener(this);
replaceFragment(new RightFragment());
}
@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.addToBackStack(null); // 在fragment中模拟返回栈
transaction.commit();
}
}
- 给左侧Fragment中的按钮注册一个点击事件
- 调用replaceFragment()方法动态添加RightFragment这个Fragment
- 点击左侧Fragment中的按钮,调用replaceFragment()方法将右侧Fragment替换成AnotherRightFragment
动态添加Fragment步骤
1. 创建待添加的碎片实例
2. 获取FragmentManager,在活动中可以直接通过调用getSupportFragmentManager()方法得到
3. 开启一个事务,通过调用beginTransaction()方法开启
4. 向容器内添加或替换Fragment,一般使用replace()方法实现,需要传入容器的id和待添加的Fragment实例
5. 提交事务,调用commit()方法来完成
在Fragment中模拟返回栈
上面实现了向活动中动态添加Fragment的功能,但是按下Back键程序会直接退出。在FragmentTransaction中提供了一个addToBackStack()方法,即可实现模仿类似于返回栈的效果。
Fragment和活动之间进行通信
虽然Fragment都是嵌入在活动中显示的,但是两者之间并没有那么明显的方式来直接进行通信。
FragmentManager提供了一个类似于findViewById()的方法,专门用于从布局文件中获取碎片的实例,即在活动中得到相应Fragment的实例。
代码:
RightFragment rightFragment = (RightFragment) getSupportFragmentManager().findFragmentById(R.id.right_fragment);
在Fragment中调用活动里的方法:在每个Fragment中都可以通过调用getActivity()方法来得到和当前Fragment相关联的活动实例。
代码:
MainActivity activity = (MainActivity) getActivity();
此外,有了活动实例后,在Fragment中调用活动里的方法就更简单了,当Fragment中需要使用Context对象,可以使用getActivity()方法。
Fragment的生命周期
Fragment的状态和回调
活动的生命周期:运行、暂停、停止、销毁4种状态
Fragment的生命周期:运行、暂停、停止、销毁4种状态
1. 运行状态:Fragment是可见的,且它所关联的活动正处于运行状态
2. 暂停状态:当一个活动进入暂停状态是(由于另一个为占满全屏的活动被添加到了栈顶),与它相关联的可见Fragment就会进入到暂停状态
3. 停止状态:当一个活动进入停止状态时,与它相关联的Fragment就会进入到停止状态,或者通过调用FragmentTransaction的remove()、replace()方法将Fragment从活动中移除。但,如果在事务提交之前调用addToBackStack()方法,这时Fragment也会进入到停止状态
4. 销毁状态:Fragment总共是依附于活动而存在的,当活动被销毁,与它相关联的Fragment就会进入到销毁状态;或者调用FragmentTransaction的remove()、replace()方法将Fragment从活动中移除,但在事务提交之前调用addToBackStack()方法,这是Fragment也会进入到销毁状态
Fragment类中提供了一系列的回调方法,以覆盖Fragment生命周期的每个环节。其中活动中有的回调方法,Fragment中几乎都有,不过Fragment还提供了一些附加的回调方法:
1. onAttach():当Fragment和活动建立关联时候调用
2. onCreateView():为Fragment创建视图(加载布局)时调用
3. onActivityCreated():确保与Fragment相关的活动一定已经创建完毕的时候调用
4. onDestroyView():当与Fragment关联的试图被移除的时候调用
5. onDetach():当Fragment和活动解除关联的时候调用
Fragment生命周期示意图:
动态加载布局的技巧
使用限定符
借助限定符来判断程序应该是使用双页模式还是单页模式。
修改FragmentTest项目中的activity_main.xml文件,删除多余代码,留下一个左侧Fragment,并充满整个父布局。
<?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.myfzhou.fragmenttest.LeftFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"/>
</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.myfzhou.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.myfzhou.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,这时就可以使用最小宽度限定符。最小宽度限定符允许我们对屏幕的宽度指定一个最小值(以dp为单位),然后以这个最小值为临界点,屏幕宽度大于这个值的设备就加载一个布局,屏幕宽度小于这个值的设备就加载另一个布局。
此时layout文件夹命名方式为:layout-sw***dp
Fragment的最佳实践-一个简易版的新闻应用
加载RecyclerView依赖库
implementation 'com.android.support:recyclerview-v7:26.1.0'
新建实体类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;
}
}
新闻内容布局
<?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: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: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_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实现)分隔开。
创建NewsContentFragment类
加载新闻内容布局的标题和内容:
public class NewsContentFragment extends Fragment {
private View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 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 = view.findViewById(R.id.news_title);
TextView newsContentText = view.findViewById(R.id.news_content);
newsTitleText.setText(newsTitle);
newsContentText.setText(newsContent);
}
}
onCreateView()
方法加载news_content_frag布局,
refresh()
方法就是用于将新闻的标题和内容显示在界面上。
创建单页模式的布局及活动
新建NewsContentActivity活动,将布局名指定成news_content。
修改news_content.xml中的代码,直接在布局中引入了NewsContentFragment,这样也就相当于把news_content_frag布局的内容自动加了进来:
<?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:name="com.example.fragmentbestpractice.NewsContentFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
修改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);
}
}
onCreate()方法中,通过Intent获取到了传入的新闻标题和新闻内容,调用FragmentManager的findFragmentById()方法得到了NewsContentFragment的实例,接着调用它的refresh()方法,并将新闻的标题和内容传入,就可以把这些数据显示出来了。
注:相关actionStart()方法,阅读2.6.3小节。
显示新闻列表的布局及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="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="@+id/news_title_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>
</LinearLayout>
新建news_item.xml作为RecyclerView子项布局,
<?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>
android:padding
表示给控件的周围加上补白,
android:ellipsize
用于设定当文本内容超出控件宽度时,文本的缩略方式。
展示新闻列表
新建NewsTitleFragment作为展示新闻列表的Fragment,
public class NewsTitleFragment extends Fragment {
private boolean isTwoPane;
@Nullable
@Override
public View onCreateView(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_layout) != null) {
isTwoPane = true;
} else {
isTwoPane = false;
}
}
}
onCreateView()
方法中加载了news_title_frag布局,
onActivityCreated()
方法通过在活动中能否找到一个id为news_content_layout的View来判断当前是双页模式还是单页模式。
使用限定符完成判定单、双页模式
修改activity_main.xml的代码,使得在单页模式下,只会加载一个新闻标题的Fragment:
<?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:name="com.example.fragmentbestpractice.NewsTitleFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</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.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放在了一个Frame-layout布局下,而这个布局id正是news_content_layout。
使用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 = view.findViewById(R.id.news_title);
}
}
public NewsAdapter(List<News> mNewsList) {
this.mNewsList = mNewsList;
}
@Override
public ViewHolder onCreateViewHolder(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(ViewHolder holder, int position) {
News news = mNewsList.get(position);
holder.newsTitleText.setText(news.getTitle());
}
@Override
public int getItemCount() {
return mNewsList.size();
}
}
}
相RecyclerView中填充数据
public class NewsTitleFragment extends Fragment {
private boolean isTwoPane;
@Nullable
@Override
public View onCreateView(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 = 0; 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();
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(getActivity().findViewById(R.id.visibility_layout) != null) {
isTwoPane = true;
} else {
isTwoPane = false;
}
}
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 = view.findViewById(R.id.news_title);
}
}
public NewsAdapter(List<News> mNewsList) {
this.mNewsList = mNewsList;
}
@Override
public ViewHolder onCreateViewHolder(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(ViewHolder holder, int position) {
News news = mNewsList.get(position);
holder.newsTitleText.setText(news.getTitle());
}
@Override
public int getItemCount() {
return mNewsList.size();
}
}
}