【问题标题】:MVVM : How to Concat the String in model class?MVVM:如何在模型类中连接字符串?
【发布时间】:2017-03-21 11:06:07
【问题描述】:

我使用改造回调创建了应用程序。在那我想用文字显示一些信息。在 textView 中我已经绑定了数据,我还需要连接一些文本。

我的代码如下

查看:

<?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="UserProfile"
            type="com.practical_session.sai.instaprouser.Profile.model.UserProfileInfo" />

    </data>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/linear"
    android:orientation="vertical"
    android:background="@drawable/animation_list"
    tools:context="com.practical_session.sai.instaprouser.Profile.view.ProfileActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <android.support.v7.widget.AppCompatTextView
            android:id="@+id/username"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/imageView"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="8dp"
            android:textSize="20dp"
            android:text="@{UserProfile.username}"
            android:textColor="@android:color/black" />

</RelativeLayout>
</LinearLayout>
</layout>

型号:

public class UserProfileInfo extends BaseObservable {

    @SerializedName("username")
    @Expose
    private String username;

    @Bindable
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

预期输出:

模型返回+“连接字符串”

【问题讨论】:

  • 你确实把答案写成了你问题的最后一句话......只需在你的 getxxx() 方法的末尾添加 +“你的字符串”

标签: android mvvm android-databinding


【解决方案1】:

试试这个简单的方法

您所有的处理事物和业务逻辑都应该在控制器类中(即:MVVM 中的 ViewModel)

在Controller中编写一个方法,将值传递给Controller,然后该方法通过Concat String返回值

代码示例

android:text="@{Controller.getUserProfile(UserProfile.username)}"

控制器方法

public String getUserProfile(String name)
{
     return name + "concat string";
}

【讨论】:

    【解决方案2】:

    在 xml 中合并它

    android:text="@{UserProfile.username + `Concat String`}"
    

    【讨论】:

    • 很好,但是当您从 TextView 或 EditText 获取值时,它将返回 concat 字符串
    • @Keerthivasan OP 没有澄清这些问题,OP 只是想连接字符串,所以我给出了一个最简单的方法 :)
    • 是的……我接受。这就是为什么我为你的答案投票
    猜你喜欢
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-22
    • 2015-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多