Android——《第一行代码(第二码)》4.5碎片的最佳实践代码

简易版新闻的理解

请添加图片描述

MainActivity调用根据屏幕大小调用布局:

  1. 单页模式:RecyclerView显示新闻标题,有点击传递数据进入NewContentActivity,其布局中是静态Fragment
  2. 双页模式:
    1. 左侧:RecyclerView显示新闻标题
    2. 右侧:根据左侧的点击,获得NewContentFragment对象刷新

News.java

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_item.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    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"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

</TextView>

news_title_frag.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/news_title_recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</androidx.recyclerview.widget.RecyclerView>ja

NewsContentFragment.java

package com.example.fragmentbestpractice;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

/*新闻内容碎片*/
public class NewsContentFragment extends Fragment {
    private View view;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        /*新闻内容布局*/
        view = inflater.inflate(R.layout.news_content_frag, container, false);
        return view;
    }

    /**
     *
     * @param newsTitle 新闻标题
     * @param newsContent 内容控件
     */
    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);
    }
}

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

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.fragmentbestpractice.NewsContentFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

NewsContentActivity.java

package com.example.fragmentbestpractice;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

public class NewsContentActivity extends AppCompatActivity {

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

    /**
     * 写在跳转到的Activity中
     * @param context 开始跳转的Activity
     * @param newsTitle 标题
     * @param newsContent 内容
     */
    public static void actionStar(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);
    }
}

MainActivity.java

package com.example.fragmentbestpractice;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /*引用的是一个FrameLayout,其中有一个静态加载的fragment*/
        setContentView(R.layout.activity_main);
    }
}

activity_main.xml单页

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
    tools:context=".MainActivity">

    <!--main_activity加载这个碎片会去调用他的onCreateView之类的方法,静态调用-->
    <fragment
        android:id="@+id/news_title_fragment"
        android:name="com.example.fragmentbestpractice.NewsTitleFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</FrameLayout>

双页

<?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_weight="1"
        android:layout_height="match_parent"/>
    <!--帧布局,用来显示右边的内容-->
    <FrameLayout
        android:id="@+id/news_content_layout"
        android:layout_width="0dp"
        android:layout_weight="3"
        android:layout_height="match_parent">
        <!--静态加载右边的内容碎片-->
        <fragment
            android:id="@+id/news_content_fragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:name="com.example.fragmentbestpractice.NewsContentFragment"/>
    </FrameLayout>
</LinearLayout>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Broadcast 广播是 Android 系统中的一种重要的组件通信方式,它可以让应用程序之间进行消息传递,从而实现应用程序之间的数据交换和功能协同。广播可以被用来处理一些系统事件或应用程序内部的特定事件。在本篇文章中,我们将学习如何在 Android 应用程序中使用广播。 一、广播的基本概念 广播是指一种可以跨应用程序发送和接收消息的机制,它允许应用程序向全局范围内的其他应用程序通知某些事件的发生。Android 中的广播可以分为两类: 1.标准广播(Normal Broadcast):这种广播是完全异步的,所有的接收者都会在同一时刻接收到广播消息,因此它们之间没有任何优先级的区别。使用标准广播时,所有接收者都无法终止广播的传播,这也是标准广播的一个缺点。 2.有序广播(Ordered Broadcast):这种广播是同步执行的,所有的接收者都是按照优先级顺序依次接收广播消息的。在广播传递过程中,每个接收者都可以截断广播的传播,使得后面的接收者无法收到广播消息。如果某个接收者截断了广播的传播,那么其后面的接收者就无法收到广播消息。这种广播的优先级由高到低依次为:1000、500、0、-500、-1000。 二、发送和接收广播 1.发送广播 在 Android 应用程序中,我们可以通过以下代码来发送广播: ```java Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST"); sendBroadcast(intent); ``` 上述代码中,我们首先创建了一个 Intent 对象,然后将其 action 设置为 "com.example.broadcasttest.MY_BROADCAST",这个 action 可以自己定义。最后,我们调用了 sendBroadcast() 方法来发送广播。 2.接收广播 要接收广播,需要在代码中注册一个 BroadcastReceiver 对象,并在其 onReceive() 方法中处理广播消息。以下是一个简单的例子: ```java public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "Received in MyBroadcastReceiver", Toast.LENGTH_SHORT).show(); } } ``` 在上述代码中,我们创建了一个 MyBroadcastReceiver 类,并实现了其 onReceive() 方法。当收到广播消息时,系统会自动调用该方法,并将广播消息以 Intent 对象的形式传递给该方法。在 onReceive() 方法中,我们可以根据 Intent 对象中携带的信息来进行相应的处理,例如弹出一个 Toast 提示框。 3.注册广播接收器 在 Android 应用程序中,我们需要使用 IntentFilter 对象来指定要接收的广播类型。以下是一个注册广播接收器的例子: ```java MyBroadcastReceiver receiver = new MyBroadcastReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("com.example.broadcasttest.MY_BROADCAST"); registerReceiver(receiver, intentFilter); ``` 在上述代码中,我们首先创建了一个 MyBroadcastReceiver 对象,然后创建了一个 IntentFilter 对象,并将要接收的广播类型设置为 "com.example.broadcasttest.MY_BROADCAST"。最后,我们调用 registerReceiver() 方法来注册广播接收器。 4.注销广播接收器 当我们不再需要接收某个广播时,应该及时将其注册的广播接收器进行注销。以下是一个注销广播接收器的例子: ```java unregisterReceiver(receiver); ``` 在上述代码中,我们调用 unregisterReceiver() 方法来注销广播接收器。 三、有序广播的使用 有序广播可以让我们按照优先级顺序接收广播消息,并且可以截断广播的传播。以下是一个有序广播的例子: ```java Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST"); sendOrderedBroadcast(intent, null); ``` 在上述代码中,我们调用了 sendOrderedBroadcast() 方法来发送有序广播。由于没有指定接收者的权限,因此我们将其设置为 null。 接下来,我们需要在代码中注册一个 BroadcastReceiver 对象,并在其 onReceive() 方法中处理广播消息。以下是一个简单的例子: ```java public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String msg = getResultData(); Toast.makeText(context, msg + " Received in MyBroadcastReceiver", Toast.LENGTH_SHORT).show(); setResultData("Hello MainActivity"); } } ``` 在上述代码中,我们首先调用 getResultData() 方法来获取上一个接收者设置的数据,然后弹出一个 Toast 提示框,并将自己的数据设置为 "Hello MainActivity"。 接下来,我们需要指定广播接收者的优先级。在 AndroidManifest.xml 文件中,我们可以使用 priority 属性来设置广播接收者的优先级。以下是一个简单的例子: ```xml <receiver android:name=".MyBroadcastReceiver"> <intent-filter> <action android:name="com.example.broadcasttest.MY_BROADCAST"/> </intent-filter> <priority android:priority="1000" /> </receiver> ``` 在上述代码中,我们将 MyBroadcastReceiver 类注册为广播接收者,并将其优先级设置为 1000。 为了演示有序广播的效果,我们可以再注册一个 BroadcastReceiver 对象,并将其优先级设置为 500。以下是一个简单的例子: ```java public class AnotherBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String msg = getResultData(); Toast.makeText(context, msg + " Received in AnotherBroadcastReceiver", Toast.LENGTH_SHORT).show(); setResultData("Hello MainActivity"); } } ``` 在上述代码中,我们将 AnotherBroadcastReceiver 类注册为广播接收者,并将其优先级设置为 500。 最后,我们在 AndroidManifest.xml 文件中注册这两个广播接收者,代码如下: ```xml <receiver android:name=".MyBroadcastReceiver"> <intent-filter> <action android:name="com.example.broadcasttest.MY_BROADCAST"/> </intent-filter> <priority android:priority="1000" /> </receiver> <receiver android:name=".AnotherBroadcastReceiver"> <intent-filter> <action android:name="com.example.broadcasttest.MY_BROADCAST"/> </intent-filter> <priority android:priority="500" /> </receiver> ``` 在上述代码中,我们将 MyBroadcastReceiver 和 AnotherBroadcastReceiver 类都注册为广播接收者,并指定了它们的优先级。 在执行上述代码后,我们可以看到,在发送广播时,首先会将广播消息发送给优先级为 1000 的 MyBroadcastReceiver 类,然后再发送给优先级为 500 的 AnotherBroadcastReceiver 类。在 MyBroadcastReceiver 类的 onReceive() 方法中,我们可以获取到 AnotherBroadcastReceiver 类设置的数据,然后弹出一个 Toast 提示框,并将自己的数据设置为 "Hello MainActivity"。最后,我们可以看到,弹出的 Toast 提示框中显示的内容为 "Hello MainActivity Received in MyBroadcastReceiver",这表明 MyBroadcastReceiver 类成功地截断了广播的传播。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CCPigSnail

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值