参考书籍:Android第一行代码(第二版).郭霖著
兼顾手机和平板,Android自3.0版本开始引入碎片概念,可以让界面在平板上更好地展示。
碎片(Fragment):一种可嵌入到活动当中的UI片段。可理解成迷你型活动。
1、使用方式:
首先需有一个平板模拟器。
在新建碎片类时,建议继承android.support.v4.app.Fragment(还有一个系统内置的android.app.Fragment),因为它可以让碎片在所有Android系统版本中保持功能一致(内置的在Android4.2系统之前的设备运行会崩溃)。不需要在build.gradle中添加support-v4库依赖,因为已经添加了appcompat-v7库依赖(会将support-v4库一起引入)。
(1)简单用法
例:在一个活动中添加两个碎片平分活动空间。
新建左右两个碎片布局left_fragment.xml和right_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>
<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="20sp"
android:text="This is right fragment"/>
</LinearLayout>
新建对应的碎片类,LeftFragment和RightFragment:
public class LeftFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.left_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.jojo.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.jojo.fragmenttest.RightFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
/>
</LinearLayout>
通过android:name属性来显示知名要添加的碎片类名(将包名也加上)。
效果如下:
(2)动态添加
碎片的真正强大之处:在程序运行时动态地添加到活动当中。
新建布局文件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>
新建相应碎片类:
public class AnotherRightFragment extends Fragment {
@Nullable
@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.jojo.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>
使用了最简单的FrameLayout布局(放入碎片不需任何定位)。
接下来在代码中向FrameLayout里添加内容,实现动态添加碎片功能:
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 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();//通过beginTrasaction开启一个事务
transaction.replace(R.id.right_layout,fragment);//向容器内添加或替换碎片,一般使用replace方法实现,需传入容器id和待添加碎片实例
transaction.commit();//提交事务
}
}
动态添加碎片的步骤如上replaceFragment()方法所述。
效果如下:
(3)模拟返回栈
按钮点击添加一个碎片后,如这时按下Back键程序会直接退出。接下来实现按Back键返回上一个碎片。
FragmentTransaction中提供了一个addToBackStack()方法,可用于将一个事务添加到返回栈中,修改MainActivity中代码:
private void replaceFragment(Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();//通过beginTrasaction开启一个事务
transaction.replace(R.id.right_layout,fragment);//向容器内添加或替换碎片,一般使用replace方法实现,需传入容器id和待添加碎片实例
**transaction.addToBackStack(null);//就收一个名字用于描述返回栈的状态,一般传入null**
transaction.commit();//提交事务
}
在事务提交之前调用此方法即可。
(4)碎片与活动之间通信
碎片和活动都是各自存在于一个独立类当中的,没有那么明显的方式直接进行通信。
为方便二者通信,FragmentManager提供了一个类似于findViewById()的方法,专门用于从布局文件中获取碎片实例:
LeftFragment leftFragment = (LeftFragment) getFragmentManager().findFragmentById(R.id.left_fragment);
在碎片中调用活动里的方法:通过调用getActivity()方法得到和当前碎片相关联的活动实例:
MainActivity activity = (MainActivity) getActivity();
当碎片中需要使用Context对象时,也可以使用getActivity()方法(活动本身就是一个Context对象)
碎片与碎片之间的通信:碎片中得到相关联的活动,再通过活动获取另一个碎片实例。
2、碎片的生命周期
与活动相似。
(1)碎片状态和回调
运行状态:碎片可见,且所关联的活动处于运行状态
暂停状态:当活动进入暂停状态时,与之相关联的可见碎片进入此状态。
停止状态:当活动进入停止状态,与之关联的碎片进入此状态。或调用FragmentTransaction的remove()、replace()方法将碎片从活动中移除,但如在事务提交之前调用addToBackStack()方法,也会进入此状态。有可能被系统回收。
销毁状态:当活动被销毁,与之相关联的碎片就会进入此状态。或调用FragmentTransaction的remove()、replace()方法将碎片从活动中移除,但在事务提交之前没有调用addToBackStack()方法,也会进入此状态。
活动中有的回调方法,碎片中几乎都有,还提供了一些附加的回调方法:
onAttach():当碎片和活动建立关联时调用。
onCreateView():为碎片创建视图(加载布局)时调用。
onActivityCreated():确保与碎片关联的活动一定已经创建完毕的时候调用。
onDestroyView():当与碎片关联的视图被移除时调用。
onDetach():当碎片和活动解除关联时调用。
完整生命周期如下:
在碎片中也可通过onSaveInstanceState()方法保存数据,进入停止状态的碎片有可能在系统内存不足时被回收。保存的数据在onCreate()/onCreateView()/onActivityCreated()这三个方法中重新得到,都含有Bundle类型的savedInstanceState参数。
3、动态加载布局的技巧
如果程序能根据设备的分辨率或屏幕大小在运行时决定加载哪个布局,可发挥空间就更多了。
(1)使用限定符
判定使用双页模式还是单页模式,需借助限定符(Qualifiers)。修改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.jojo.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.jojo.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.jojo.fragmenttest.RightFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3"/>
</LinearLayout>
两个布局文件分别为单页模式和双页模式。large就是一个限定符(屏幕被认为是large的设备会自动加载layout-large文件夹下的布局,小屏幕还是会加载layout文件夹下的布局)。
然后将MainActivity中replaceFragment()方法里的代码注释掉,并在平板模拟器上重新运行程序:
在手机模拟器上运行:
Android中常见的限定符:
(2)最小宽度限定符
large限定符解决了单双页判断问题。但如需更灵活为不同设备加载布局(不管是否被系统认定为large),可以使用最小宽度限定符(Smallest-width Qualifier)。它允许对屏幕的宽度指定一个最小值(以dp为单位),大于和小于这个值会分别加载不同布局。
如在res目录下新建layout-sw600dp文件夹,在此文件夹下创建的布局就会在程序运行在屏幕宽度大于600dp的设备上时被加载,而宽度小于这个值时仍加载默认的layout下的布局。
4、碎片的最佳实践(简易新闻应用)
编写同时兼容手机和平板的应用。
新建一个FragmentBestPractice项目,由于要用到RecyclerVeiw,所以需在app/build.gradle中添加依赖库。
compile 'com.android.support:recyclerview-v7:24.2.1'
点击同步。
准备一个新闻实体类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实现,设置宽/高和背景颜色即可,这里为黑色)。
新建一个NewsContentFragment类,继承自Fragment:
public class NewsContentFragment extends Fragment {
private View view;
@Nullable
@Override
public View onCreateView(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);//刷新新闻的内容
}
}
新闻内容的碎片和布局都创建好了,但他们都是在双页模式中使用的,要想在单页模式使用,需再创建一个活动NewsContentActivity,并将布局名设为news_content,修改布局:
<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.jojo.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.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:
<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:id="@+id/news_title_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
子项布局,新建news_item.xml:
<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">
</TextView>
只有一个TextView, ellipsize用于设定当文本内容超出控件宽度时,文本的缩略方式,end表示在尾部进行缩略。
接下来需要一个用于展示新闻列表的地方,新建NewsTitleFragment作为展示新闻列表的碎片:
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;//可以找到news_content_layout布局时,为双页模式
}else {
isTwoPane = false;//找不到news_content_layout布局时,为单页模式
}
}
}
onActivityCreated()方法中通过能否找到id为news_content_layout的View判断当前是单页模式还是双页模式,因此需要让这个id只在双页模式中才会出现。
借助限定符,修改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.jojo.fragmentbestpractice.NewsTitleFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</FrameLayout>
上述代码表示,在单页模式下,只会加载一个新闻标题碎片。
然后新建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.jojo.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.jojo.fragmentbestpractice.NewsContentFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</LinearLayout>
可见,在双页模式下同时引入两个碎片,并将新闻内容碎片放在一个FrameLayout布局下,id正是news_content_layout。所以能找到这个id时为双页模式。
接下来还需在NewsTitleFragment中通过RecyclerView将新闻列表展示出来。在NewsTitleFragment中新建一个内部类NewsAdapter作为适配器:
public class NewsTitleFragment extends Fragment {
private boolean isTwoPane;
。。。
//这里写成内部类的好处是,可以直接访问NewsTitleFragment的变量,如isTwoPane
class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder>{
private List<News> mNewsList;
class ViewHolder extends RecyclerView.ViewHolder{
TextView newsTitleText;
public ViewHolder(View itemView) {
super(itemView);
newsTitleText = (TextView)itemView.findViewById(R.id.news_title);
}
}
public NewsAdapter(List<News> newsList){
mNewsList = newsList;
}
@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 = (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中填充数据。修改NewsTitleFragment:
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 = 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();
}**
。。。
}
效果如下:
手机上运行,
平板上运行,