第一行代码笔记③

3.1 初识碎片

首先定义好两个碎片left_fragment.xml和right_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Button" />

</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#00ff00">

    <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(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.left_fragment, container, false);
        return view;
    }
}

重写Fragment的onCreateView()方法就行了,加载一下刚刚定义的碎片布局

接着在activty_main.xml中添加刚刚写的碎片,使用<fragemnt>标签添加碎片,此外还需要通过android:name属性去显式指名要添加的碎片类名,并将类的包名也加上。

    <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" />

3.2 动态添加碎片

上一节中是在布局文件中添加碎片,碎片真正厉害的地方是可以在程序运行时动态地添加到活动中。新建another_right_fragment.xml

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="This is another right fragment"
        android:textSize="20sp" />

接着新建AnotheRightFragment这个类

public class AnotheRightFragment 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,将碎片动态的添加到活动中

    <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" />

我们将刚刚的右侧碎片换成了一个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);
        button.setOnClickListener(this);
        replaceFragment(new RightFragment());
    }

    private void replaceFragment(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.right_layout, fragment);
        transaction.commit();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button:
                replaceFragment(new AnotheRightFragment());
                break;
            default:
                break;
        }
    }
}

首先给左侧碎片中的按钮注册了一个点击事件(这里ide会报红,找不到这个按钮,但运行没问题)然后调用replaceFragment方法动态添加了RightFragment这个碎片,当点击按钮时,又将右侧碎片换AnotheRightFragment。
动态添加碎片的步骤如下:
(1)创建待添加的碎片实例
(2)获取FragmentManager,在活动可以调用getSupportFragmentManager得到
(3)开启一个事务,调用fragmentManager的beginTransaction方法得到
(4)向容器内添加或者替换碎片,一般使用repalce方法,参数为需要传入容器的id和待添加的碎片实例
(5)提交事务,调用commit()方法实现
replace()方法:先将之前存在于容器的 Fragment 全部移除(销毁),然后添加要显示的 Fragment(会重新执行一遍它的生命流程)

3.3 在碎片中模拟返回栈

上一小节中,我们成功实现了向活动中动态添加碎片的功能。但是此时按下Back键,会直接退出,如果我们想实现类似于返回栈的效果,按下Back键回到上一个碎片,只需要添加一行代码。

        transaction.addToBackStack(null);

参数一般为null,此时按下Back键,返回到上一个碎片RightFragment,再按下Back键,RightFragment也会消失,再按一次Back键,才会退出。

3.4 碎片和活动之间通信

碎片和活动都是存在于一个独立的类 当中
为了方便碎片与活动之间进行通信FragmentManager提供了一个类似于findViewById的方法

从布局中获取碎片实例

RightFragment rightFragment = (RightFragment)getSupportFragmentManager()
.findFragmentById(R.id.left_fragment);

碎片调用活动里面的方法,每个碎片都可以通过调用getActivity()方法得到和当前碎片相关联的活动实例

MainActivity activity = (MainActivity)getActivity();

3.5 动态加载布局

使用限定符—>只需要新建一个layout文件夹,命名为layout-large
在这里插入图片描述
在这里插入图片描述
平板自动加载large下的布局,手机则加载默认的

使用最小宽度限定符—>更加灵活的为不同设备加载布局,large到底是多大?该方式允许一个最小值为临界点,大于这个值加载一个布局,小于则加载另一个布局。
同样新建layout-sw600dp文件夹,当程序运行在屏幕宽度大于600dp的设备时,加载该文件夹下面的布局,低于则加载默认的。

3.6 碎片的最佳实践——一个简易版的新闻应用

碎片很多时候都是在平板开发中使用的,主要是为了解决屏幕空间不能充分利用的问题。确实有不少公司开发程序,提供一个手机版和一个pad版。那么如何编写同时兼容手机和平板的应用程序呢?

①首先新建News类


//title表示 新闻标题,content表示新闻内容
package com.example.fragmentbestpractice;

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,作为新闻内容的布局

<?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: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="682dp"
            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实现,宽或高设置为1dp,颜色设置为黑色即可。
③新建一个NewsContentFragment类

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);  // 刷新新闻的内容
    }
}

首先加载刚刚创建的news_content_frag布局,接着实现了一个refresh()方法,用于将新闻的标题和内容显示在界面上。

以上都是在双页模式(平板)中使用的,如果想在单页模式使用(手机),新建一个NewsContentActivity,对应的布局为news_content.xml
④新建news_content.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <fragment
        android:id="@+id/news_content_fragment"
        android:name="com.example.fragmentbestpractice.NewsContentFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

这里是利用代码的复用性,直接在布局中引入NewsContentFragment,相当于把news_content_frag布局引入进来。
即:引入NewsContentFragment类—>类中引入R.layout.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);  // 刷新NewsContent-Fragment界面

    }
}

这里先是用Intent获取到了传入的新闻标题和新闻内容,接着调用getSupportFragmentManager()
.findFragmentById得到碎片实例,接着调用refresh()方法,将标题和内容传入并显示。这里的actionStart()方法是作用是啥来着,有点忘了。
⑥接着新建一个显示新闻列表的布局,新建news_title_frag.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/news_title_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

该布局只有一个显示新闻列表的RecyclerView,接下来定义RecyclerView的子项布局—>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="@integer/material_motion_duration_long_1"
    android:ellipsize="end"
    android:textSize="18sp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:paddingTop="15dp"
    android:paddingBottom="15dp"/>

android:padding表示填补空白,android:maxLines表示最大显示的行数?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_layout)!=null){
            isTwoPane = true;   // 可以找到news_content_layout布局,为双页模式,否则就是单页
        }else {
            isTwoPane = false;
        }
    }
}

通过判断是否找到了R.id.news_content_layout这个布局,来判断是双页还是单页。
接着修改activity_main.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/news_title_layout"
    tools:context=".MainActivity">

    <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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">


    <fragment
        android:id="@+id/news_title_fragment"
        android:name="com.example.fragmentbestpractice.NewsTitleFragment"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_width="0dp"/>

    <FrameLayout
        android:id="@+id/news_content_layout"
        android:layout_height="match_parent"
        android:layout_weight="3"
        android:layout_width="0dp">

        <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>

双页模式下,我们引入了两个碎片,并将新闻内容的碎片放置在一个FrameLayout布局下,这个布局的id为news_content_layout
⑦在NesTitleFragment中通过RecyclerView将新闻列表展示出来,新建一个内部类NesAdapter作为适配器
⑧向RecyclerView中填充数据,修改NewsTitleFragment中的代码
有点绕,后面有时间再更吧,先不写了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值