300
V2EX  ›  问与答

请教一个安卓 data binding 双向绑定的问题

  •  
  •   300 · May 16, 2018 · 1101 views
    This topic created in 3014 days ago, the information mentioned may be changed or developed.

    这里有个自定义组件:

    <LinearLayout...>
        <TextView android:id="@+id/textView" .../>
        <EditText android:id="@+id/editText" .../>
    </LinearLayout>
    

    对应的 Java 文件:

    public class CustomView extends LinearLayout {
        TextView title;
        EditText value;
        public CustomView(Context context, @Nullable AttributeSet attrs) { ... }
        getter return String...
        setter (String)...
    }
    

    对应的 ViewModel:

        public String title = "";
        public String value = "";
        @Bindable
        getter...
        setter...notifyPropertyChanged(...)
    

    主界面 activity_main.xml

    <layout...>
        <data><variable name="vm" type="com.test.test.CustomViewModel"/></data>
        <android.support.constraint.ConstraintLayout>
            <com.test.test.CustomView
                android:onClick="@{()->vm.onClick()}"
                app:title="@={vm.title}"
                app:value="@={vm.value}"/>
        </android.support.constraint.ConstraintLayout>
    </layout>
    

    现在的问题是,在 activity_main 界面修改了值,viewmodel 接收不到。但在 viewmodel 里修改,界面能显示。 想请教一下应该怎么做,网上搜了半天也没解决>.< 有个设置 adapter 的方法,但我试了,貌似没被解析

    3 replies    2018-05-17 08:50:54 +08:00
    WordTian
        1
    WordTian  
       May 16, 2018 via Android   ❤️ 1
    java 文件里有好几个构造方法,各有各的作用,都得改,不是说只改其中一个就好
    300
        2
    300  
    OP
       May 16, 2018
    @WordTian #1 改了,用 AS 提供的组件( EditText 之类)可以获取。
    就是不知道还有没有其它要改的地方。。
    300
        3
    300  
    OP
       May 17, 2018
    ##
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3343 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 11:47 · PVG 19:47 · LAX 04:47 · JFK 07:47
    ♥ Do have faith in what you're doing.