我已经搜索了整个互联网或几个小时,没有运气
我试图弄清楚如何将MutableLiveData传递给自定义视图
这是ViewModel中用于我的活动数据绑定的实时数据
var perStops: MutableLiveData<Int> = MutableLiveData(10)
这是我在活动中使用自定义视图的方式
<com.abc.ui.widgets.NumberStepper
app:amount="@={data.perStops}"
app:min="0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"/>
这是数字步进器的自定义视图
class NumberStepper(context: Context, attrs: AttributeSet) : RelativeLayout(context, attrs) {
private val rootView = LayoutInflater.from(context)
val binding = NumberPickerCustomLayoutBinding.inflate(rootView,this,true)
init {
val customAttributes = context.obtainStyledAttributes(attrs, R.styleable.NumberStepper)
val minAmount = customAttributes.getInteger(R.styleable.NumberStepper_min,0)
val amount = customAttributes.getInteger(R.styleable.NumberStepper_amount,0)
binding.suffix = customAttributes.getString(R.styleable.NumberStepper_suffix)?:""
binding.data = amount
}}
这是NumberPickerCustomLayoutBinding的XML布局
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="data"
type="Integer" />
<variable
name="suffix"
type="String" />
</data>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/white"
android:orientation="horizontal">
<ImageButton
android:id="@+id/decrement"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginEnd="-10dp"
android:background="@null"
android:padding="@dimen/odc_padding16"
android:src="@drawable/ic_minus" />
<TextView
android:id="@+id/display"
style="@style/TextAppearance.Secondary"
android:layout_width="45dp"
android:layout_height="match_parent"
android:background="@android:color/white"
android:gravity="center"
tools:text="1"
android:text='@{data.toString() + suffix}' />
<ImageButton
android:id="@+id/increment"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginStart="-10dp"
android:background="@null"
android:padding="@dimen/odc_padding16"
android:src="@drawable/ic_plus" />
</LinearLayout>