【安卓学习】4.碎片(Fragment)实践---一个简单的新闻应用。

今天看了有关碎片(Fragment)的一些知识,最后面有一个实践应用,我就做了这个项目,并做了一点小结。

很多时候我们希望我们的app能够在手机/Pad上通用,但是Pad屏幕面积比较大,手机上可以一个屏幕都在展示一个项目,但是如果平板也这样,可能就比较浪费,为了应对这个问题,安卓有一个特别好用的东西,叫碎片Fragment。具体的可以看前面的博客。

1.修改build.gradle,添加依赖的类库。

首先,创建一个安卓项目:SimpleNewsApp,因为我们项目中使用到了RecyclerView,因此需要在app/build.gradle中添加依赖库,如下图所示:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    testCompile 'junit:junit:4.12'
}
其中,第7行就是我们需要添加的东西。

2.创建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;
    }
}
这个就是一个普通实体类,没什么好说的。

3.新建布局文件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="#000000" />

        <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="#000000"
        />

</RelativeLayout>

这里重要的是有两个<TextView>,第一个id为news_title,用来显示新闻的标题,第二个id为news_content,用来显示新闻的内容。其中<View>标签是用来分割标题与内容的,即中间的那条黑色的细线。设置width宽度为1,背景颜色为#000000黑色。

截至目前,我们已经有了一个展示新闻的布局,以及一个新闻的实体。

4.新建一个NewsContentFrage类,继承了Fragment(support.v4下面的)。

    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 = (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()方法则是将新闻的标题内容显示出来。

目前为止,我们已经创建好了新闻内容的碎片与布局。这个只是在双页模式下使用的,如果不知道什么是双页模式,可以看我前一篇博客。接下来我们需要实现单页模式下使用。单页下,其实就是一个新的活动。

5.创建布局命名为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:name="com.example.ustcg.simplenewsapp.NewsContentFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

我们在这里重用了代码,直接布局中引入了NewsContentFragement,这样就相当于把news_content_frage布局的内容添加进来。代码比较就简单,我们继续下面的。

6.创建布局对应的活动,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()方法中,我们通过getIntent,然后在intent中获取到传入的新闻标题与内容。获取之后,我们该怎么展示呢?当然实在fragment,即碎片。怎么做呢,首先我们获取到目标碎片(fragment)的实例,getSupportFragmentManager().findFragmentById(R.id.news_content_fragment)即实现这个功能,然后调用碎片中的refresh方法,将标题与内容传入,然后显示出来。

actionStart方法的用途,类似实现一个intent,但是为什么不写在源activity而是目标activity?原因比较简单,如果写在了目标的activity,源activity调用的时候,就需要传入规定的参数。使用情景就是:假如两个activity是两个不同的人开发的,当一个人需要跳转的另外一个人的activiy时,需要提供参数,但是怎么知道需要提供哪些参数呢?如果不用这种方式,那么这个人就需要去都目标activity的代码,然后才能知道需要提供什么数据。

7.创建一个显示新闻列表的布局,news_title_frag.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">

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

</LinearLayout>

代码比较少,比较简单,其实主要是用到了一个显示新闻列表的RecyclerView标签,具体的作用,可以百度。嘿嘿。用到了RecyclerView就要定义子项的布局,接下来我们定义子项布局。

8.子项布局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:singleLine="true"
    android:ellipsize="end"
    android:textSize="18sp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:paddingTop="15dp"
    android:paddingBottom="15dp"
    />

子布局只有一个TextView,几个关键的属性介绍一下,android:singleLine="true"的含义是让这个TextView只会单行显示,android:ellipsize设置文本内容超出控件宽度 之后文本的缩略方式,end表示尾部缩略。其他的都比较简单,如果看不明白可以百度。

新闻列表以及子项的布局都已经创建好了,接下来就需要找一个展示的地方了。

9.创建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;
        } else {
            isTwoPane = false;
        }
    }
}

代码简单,在onCreateView()方法中加载了news_title_frag布局,在onActiivityCreated中主要是添加了一个标志,判断当前是双页模式还是单页模式,即平板还是手机。

么才能实现判断的功能呢?这个比较简单。

10.创建两个activity_main.xml布局

这两个布局文件不能放到一个地方,不然就重名报错了。一个放在layout下面,作为普通的布局,即手机布局。另一个需要放到一个新的文件夹layout-sw600dp下面,即

机器像素大于600dp使用的布局,即平板布局。系统会自动根据你的机器尺寸选择合适的布局。

layout文件夹下的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:name="com.example.ustcg.simplenewsapp.NewsTitleFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</FrameLayout>
单页模式下,只加载NewsTitleFragment的碎片。
layout-sw600dp文件夹下的activity_main.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="horizontal">

    <fragment
        android:id="@+id/news_title_fragment"
        android:name="com.example.ustcg.simplenewsapp.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.ustcg.simplenewsapp.NewsContentFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>


    </FrameLayout>
</LinearLayout>

这里加载了两个碎片,并把新闻内容碎片放在了一个FrameLayout布局下面,布局的id为news_content_layout,如果能找到这个id,则证明为双页模式,即平板。斗则就是

手机。

至此我i们完成了大部分工作。接下来我们需要在NewsTitleFragment碎片中,通过RecyclerView将新闻咧白哦展示出来。这个比较复杂。

11.修改NewsTitleFragment

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

        @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(NewsAdapter.ViewHolder holder, int position) {
            News news = mNewsList.get(position);
            holder.newsTitleText.setText(news.getTitle());
        }

        @Override
        public int getItemCount() {
            return mNewsList.size();
        }
    }

    @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.news_content_layout) != null) {
            isTwoPane = true;
        } else {
            isTwoPane = false;
        }
    }
}

原谅我比较懒,直接把这个类粘贴出来了。

首先最开始我们新建了一个内部类NewsAdapter作为RecyclerView的适配器。很抱歉的是,我对于适配器的代码也没太搞明白,因此这里就先不说了,直接跳过,后期在我

搞明白之后,我会再来编辑的。

其他的代码就比较简单了,就不解释了。直接运行吧。

项目代码我已经放到github上了,你们可以去download。简单的新闻安卓app

有问题可以留言,大家一起探讨吧,毕竟我现在还没入门。

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,让我来为你详细介绍一下如何使用Kotlin在安卓应用中编写一个带有RecyclerView的Fragment的Adapter。 首先,我们需要在项目的Gradle文件中添加RecyclerView的依赖项: ``` implementation 'androidx.recyclerview:recyclerview:1.2.1' ``` 接下来,我们创建一个名为`MyAdapter`的Kotlin类,并继承`RecyclerView.Adapter`。在类中,我们需要定义一个内部类`ViewHolder`,该类继承自`RecyclerView.ViewHolder`。在`ViewHolder`类中,我们需要定义一个`TextView`的成员变量,用于显示列表项的文本。 ``` class MyAdapter(private val data: List<String>) : RecyclerView.Adapter<MyAdapter.ViewHolder>() { class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val textView: TextView = view.findViewById(R.id.text_view) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.list_item, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.textView.text = data[position] } override fun getItemCount(): Int { return data.size } } ``` 在`MyAdapter`类中,我们还需要实现三个方法:`onCreateViewHolder`、`onBindViewHolder`和`getItemCount`。这些方法分别用于创建新的ViewHolder、绑定数据到ViewHolder和返回列表项的数量。 `onCreateViewHolder`方法中,我们需要创建一个新的ViewHolder,并为其绑定列表项的布局文件。 `onBindViewHolder`方法中,我们需要获取当前位置的数据并将其绑定到ViewHolder的TextView中。 `getItemCount`方法中,我们需要返回列表项的数量。 最后,在Fragment中,我们可以使用以下代码来设置RecyclerView的布局和适配器: ``` recyclerView.layoutManager = LinearLayoutManager(activity) recyclerView.adapter = MyAdapter(data) ``` 其中,`data`是一个String类型的List,包含了我们想要显示的列表项数据。 这样,我们就成功地使用Kotlin编写了一个带有RecyclerView的Fragment的Adapter。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值