Android开发使用Databinding实现关注功能mvvp

目录
  • 正文
  • 目标
  • Modle
  • Presenter

正文

说到关注功能,可能很多小伙伴要说了。谁不会写

但是没有合理的架构,大家写出来的代码很可能是一大堆的复制粘贴。比如十几个页面,都有这个关注按钮。然后,你是不是也要写十几个地方呢 然后修改的时候是不是也要修改十几个地方 我们是否考虑过一下几个问题?

  • 可复用性 (是否重复代码和逻辑过多?)
  • 可扩展性 (比如我这里是关注的人,传userId,下个地方又是文章 articleId)
  • 可读性 冗余代码过多,势必要影响到可读性。

然后再看下自己写的代码,是否会面临上面的几个问题呢?是否有一种优雅的方式。帮我们一劳永逸。我这里给出一个解决方案是 使用Databinding ,如果对databinding使用不熟悉的,建议先去熟悉一下databinding用法

目标

我们要实现的目标是,希望能让关注这快的业务逻辑实现最大程度复用,在所有有关注按钮布局的页面,只需要引入一个同一个vm。实现关注和非关注状态逻辑的切换

Modle

下面以关注人来做为示例

要有两种状态,实体bean要继承自BaseObservable。配合databing实现mvvm效果,属性需要定义为@Bindable,当属性发生变化的时候,调用notifyPropertyChanged(属性ID)

public class User extends BaseObservable implements Serializable {
    public boolean hasFollow;//是否关注,是和否
    @Bindable
    public boolean isHasFollow() {
        return hasFollow;
    }
    public void setHasFollow(boolean hasFollow) {
        this.hasFollow = hasFollow;
        notifyPropertyChanged(com.mooc.ppjoke.BR._all);
    }
}

页面布局如下

<?xml version="1.0" encoding="utf-8"?>
<layout 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">
    <data>
        <variable
            name="feed"
            type="com.mooc.ppjoke.model.Feed" />
        <variable
            name="leftMargin"
            type="java.lang.Integer" />
        <variable
            name="fullscreen"
            type="java.lang.Boolean" />
        <import type="com.mooc.ppjoke.utils.TimeUtils" />
        <import type="com.mooc.ppjoke.ui.InteractionPresenter"></import>
        <variable
            name="owner"
            type="androidx.lifecycle.LifecycleOwner" />
    </data>
    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/author_info"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/transparent"
        android:orientation="vertical"
        android:paddingLeft="@{leftMargin}"
        android:paddingTop="@dimen/dp_3"
        android:paddingBottom="@dimen/dp_3">
        <com.mooc.ppjoke.view.PPImageView
            android:id="@+id/author_avatar"
            android:layout_width="@dimen/dp_40"
            android:layout_height="@dimen/dp_40"
            android:layout_marginTop="@dimen/dp_1"
            app:image_url="@{feed.author.avatar}"
            app:isCircle="@{true}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:src="@drawable/icon_splash_text"></com.mooc.ppjoke.view.PPImageView>
        <TextView
            android:id="@+id/author_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="@dimen/dp_3"
            android:text="@{feed.author.name}"
            android:textColor="@{fullscreen?@color/color_white:@color/color_000}"
            android:textSize="@dimen/sp_14"
            android:textStyle="bold"
            app:layout_constraintLeft_toRightOf="@+id/author_avatar"
            app:layout_constraintTop_toTopOf="parent"
            tools:text="Title"></TextView>
        <TextView
            android:id="@+id/create_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="@dimen/dp_2"
            android:text="@{TimeUtils.calculate(feed.createTime)}"
            android:textColor="@{fullscreen?@color/color_white:@color/color_000}"
            android:textSize="@dimen/sp_12"
            android:textStyle="normal"
            app:layout_constraintLeft_toRightOf="@+id/author_avatar"
            app:layout_constraintTop_toBottomOf="@+id/author_name"
            tools:text="3天前"></TextView>
        <com.google.android.material.button.MaterialButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="@dimen/dp_16"
            android:backgroundTint="@{fullscreen?@color/transparent:@color/color_theme}"
            android:gravity="center"
            android:onClick="@{()->InteractionPresenter.toggleFollowUser(owner,feed)}"
            android:paddingLeft="@dimen/dp_16"
            android:paddingTop="@dimen/dp_5"
            android:paddingRight="@dimen/dp_16"
            android:paddingBottom="@dimen/dp_5"
            android:text="@{feed.author.hasFollow?@string/has_follow:@string/unfollow}"
            android:textColor="@color/color_white"
            android:textSize="@dimen/sp_14"
            app:backgroundTint="@color/color_theme"
            app:cornerRadius="@dimen/dp_13"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:strokeColor="@{fullscreen?@color/color_white:@color/transparent}"
            app:strokeWidth="1dp"
            tools:text="已关注" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

显示效果

Presenter

package com.mooc.ppjoke.ui;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.arch.core.executor.ArchTaskExecutor;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mooc.libcommon.extention.LiveDataBus;
import com.mooc.libcommon.global.AppGlobals;
import com.mooc.libnetwork.ApiResponse;
import com.mooc.libnetwork.ApiService;
import com.mooc.libnetwork.JsonCallback;
import com.mooc.ppjoke.model.Comment;
import com.mooc.ppjoke.model.Feed;
import com.mooc.ppjoke.model.TagList;
import com.mooc.ppjoke.model.User;
import com.mooc.ppjoke.ui.login.UserManager;
import com.mooc.ppjoke.ui.share.ShareDialog;
import org.jetbrains.annotations.NotNull;
import java.util.Date;
public class InteractionPresenter {
    //关注/取消关注一个用户
    private static void toggleFollowUser(LifecycleOwner owner,User user) {
        ApiService.get("/ugc/toggleUserFollow")
                .addParam("followUserId", UserManager.get().getUserId())
                .addParam("userId", feed.author.userId)
                .execute(new JsonCallback<JSONObject>() {
                    @Override
                    public void onSuccess(ApiResponse<JSONObject> response) {
                        if (response.body != null) {
                            boolean hasFollow = response.body.getBooleanValue("hasLiked");
                            user.setHasFollow(hasFollow);
                            LiveDataBus.get().with(DATA_FROM_INTERACTION)
                                    .postValue(feed);
                        }
                    }
                    @Override
                    public void onError(ApiResponse<JSONObject> response) {
                        showToast(response.message);
                    }
                });
    }
}

综上已经实现了简单的用户关注功能。activity不需要做任何事情。

以上就是Android开发使用Databinding实现关注功能mvvp的详细内容,更多关于Android Databinding关注功能的资料请关注我们其它相关文章!

(0)

相关推荐

  • Android Jetpack组件支持库DataBinding与ViewModel与LiveData及Room详解

    目录 一.官方推荐的Jetpack架构 二.添加依赖 三.创建Repository 四.创建ViewModel 五.activity中使用 Android Jetpack之ViewModel.LiveData Android Jetpack之LifeCycle 一.官方推荐的Jetpack架构 ViewModel是介于View(视图)和Model(数据模型)之间的中间层,能够使视图和数据分离,又能提供视图和数据之间的通信. LiveData是一个能够在ViewModel中数据发生变化时通知页面刷

  • Android浅析viewBinding和DataBinding

    目录 viewBinding 优点 配置 使用 源码解析 DataBinding 配置 创建实体类 创建布局 创建viewModel dataBinding绑定 viewBinding 优点 当一个页面布局出现多个控件时,使用findViewById去进行控件绑定,过于冗长,且存在NULL指针异常风险.viewBinding直接创建对视图的引用,不存在因控件ID不存在而引发的NULL指针异常.并且在绑定类中对控件添加@NonNull注解 findViewById viewBinding 冗长 简

  • Android Jetpack组件DataBinding详解

    目录 Android之DataBinding DataBinding DataBinding的优势 亮点 使用DataBinding 单向绑定数据 双向绑定 Android之DataBinding DataBinding 数据绑定 DataBinding的优势 代码更加简洁,可读性会更高.部分和UI控件有关的代码可以在布局文件当中完成. 不需要使用findViewById()方法. 布局文件可以完成简单的业务逻辑处理. 亮点 开发中不需要持有控件的引用 拥有双向绑定的特性 数据与UI同步 使用D

  • Android DataBinding单向数据绑定深入探究

    目录 一.数据绑定流程 二.建立观察者模式绑定关系 在前面DataBinding原理----布局的加载这篇文章中,我们说明了DataBinding中布局的加载过程,这里继续下一步,数据是如何进行绑定的,这里只介绍单向数据绑定,即数据的变化会反映到控件上:后面再介绍双向数据绑定. 在分析源码之前,在心里要有一个概念就是这里的数据绑定是基于观察者模式来实现的,所以在阅读这部分源码的时候要着重分清楚,谁是观察者谁是被观察者,把这个思想放在心理,这样就能抓住代码的本质. 这一篇分为两个小部分,首先是数据

  • Android JetPack组件的支持库Databinding详解

    目录 简介 启用databinding 布局xml variable (变量标签) data (数据标签) @{}表达式 绑定普通数据 绑定可观察数据 对单个变量的绑定-fields 对集合的绑定-collections 绑定对象-objects 绑定LiveData 双向绑定 简介 DataBinding 是 Google 在 Jetpack 中推出的一款数据绑定的支持库,利用该库可以实现在页面组件中直接绑定应用程序的数据源.使其维护起来更加方便,架构更明确简介. DataBinding 唯一

  • Android基础入门之dataBinding的简单使用教程

    目录 前言 1.前期准备 1.1打开dataBinding 1.2修改布局文件 1.3修改Activity方法 2.DataBinding的使用 2.1属性更新 2.2<data>标签 2.2.1简单数据的定义与绑定 2.2.2复杂数据的定义与绑定 2.3事件绑定 2.3.1点击事件绑定 2.3.2点击事件回传数据 2.3.3动态改变对象数据在控件上显示 2.3.4动态改变基本数据在控件上显示 2.4与输入控件结合 2.5与图片控件结合 总结 前言 dataBinding是实现 view 和

  • Android DataBinding类关系深入探究

    目录 一.在相应的板块中开启DataBinding 二.DataBing的简单使用 三.生成的xml布局 四.生存的代码 一.在相应的板块中开启DataBinding dataBinding {        enabled true    } 二.DataBing的简单使用 这里写一个简单的布局,如下: <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget

  • Android开发使用Databinding实现关注功能mvvp

    目录 正文 目标 Modle Presenter 正文 说到关注功能,可能很多小伙伴要说了.谁不会写 但是没有合理的架构,大家写出来的代码很可能是一大堆的复制粘贴.比如十几个页面,都有这个关注按钮.然后,你是不是也要写十几个地方呢 然后修改的时候是不是也要修改十几个地方 我们是否考虑过一下几个问题? 可复用性 (是否重复代码和逻辑过多?) 可扩展性 (比如我这里是关注的人,传userId,下个地方又是文章 articleId) 可读性 冗余代码过多,势必要影响到可读性. 然后再看下自己写的代码,

  • Android开发中应用程序分享功能实例

    本文实例讲述了Android开发中应用程序分享功能.分享给大家供大家参考,具体如下: Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); //设置类型 shareIntent.setType("text/plain"); //设置分享的主题 shareIntent.putExtra("android.intent.extra.SUBJECT", "分享&

  • Android开发实现各种图形绘制功能示例

    本文实例讲述了Android开发实现各种图形绘制功能.分享给大家供大家参考,具体如下: 这里结合本人的开发事例,简单介绍一下如何在Android平台下实现各种图形的绘制. 首先自定义一个View类,这个view类里面需要一个Paint对象来控制图形的属性,需要一个Path对象来记录图形绘制的路径,需要一个Canvas类来执行绘图操作,还需要一个Bitmap类来盛放绘画的结果. Paint mPaint = new Paint(); mPaint.setAntiAlias(true); mPain

  • Android开发实现广告无限循环功能示例

    本文实例讲述了Android开发实现广告无限循环功能.分享给大家供大家参考,具体如下: 一.效果图: 二.代码实现: /** * 新闻首页 * * @Project App_Card * @Package com.android.koomama.fragment.home * @author chenlin * @version 1.0 * @Date 2014年6月22日 * @Note TODO */ public class NewsHomeFragment extends BaseFra

  • Android开发实现的简单计算器功能【附完整demo源码下载】

    本文实例讲述了Android开发实现的简单计算器功能.分享给大家供大家参考,具体如下: 这个Android计算器虽然还有点小bug,不过简单的计算功能还是没问题的哦: 先上图看效果 比较简单,所以我就没怎么写注释,应该一看就能明白的 有不明白的可以发信问我 先贴MainActivity.java代码 package com.example.calculator; import android.app.Activity; import android.os.Bundle; import andro

  • Android开发实现调节屏幕亮度功能

    本文实例讲述了Android开发实现调节屏幕亮度功能.分享给大家供大家参考,具体如下: 在很多app中进入二维码显示界面时会自动调整屏幕亮度,那么如何实现调节app的屏幕亮度呢?下面我来为大家介绍: 注:调节屏幕亮度的核心思想就是对安卓系统提供的ContentProvider进行操作 1.声明权限 需要允许用户修改系统配置 <uses-permission android:name="android.permission.CHANGE_CONFIGURATION"/> &l

  • Android开发实现的图片浏览功能示例【放大图片】

    本文实例讲述了Android开发实现的图片浏览功能.分享给大家供大家参考,具体如下: 效果图: 布局文件: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res

  • Android开发教程之调用摄像头功能的方法详解

    本文实例讲述了Android调用摄像头功能的方法.分享给大家供大家参考,具体如下: 我们要调用摄像头的拍照功能,显然 第一步必须加入调用摄像头硬件的权限,拍完照后我们要将图片保存在SD卡中,必须加入SD卡读写权限,所以第一步,我们应该在Android清单文件中加入以下代码 摄像头权限: <uses-permission android:name="android.permission.CAMERA"/> SD卡读写权限: <uses-permission androi

  • Android开发实现录屏小功能

    最近开发中,要实现录屏功能,查阅相关资料,发现调用 MediaProjectionManager的api 实现录屏功能即可: import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.media.project

  • Android开发中编写蓝牙相关功能的核心代码讲解

    一. 什么是蓝牙(Bluetooth)? 1.1  BuleTooth是目前使用最广泛的无线通信协议 1.2  主要针对短距离设备通讯(10m) 1.3  常用于连接耳机,鼠标和移动通讯设备等. 二. 与蓝牙相关的API 2.1 BluetoothAdapter: 代表了本地的蓝牙适配器 2.2 BluetoothDevice 代表了一个远程的Bluetooth设备 三. 扫描已经配对的蓝牙设备(1) 注:必须部署在真实手机上,模拟器无法实现 首先需要在AndroidManifest.xml 声

随机推荐