【问题标题】:Is it possible to set value of variable from java file?是否可以从 java 文件中设置变量的值?
【发布时间】:2018-05-15 10:13:06
【问题描述】:

这是我的 xml 布局:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <variable
            name="clickHandler"          
            type="com.myproject.android.customer.ui.adapter.MyHandler" />
        <variable
            name="item"
            type="com.myproject.android.customer.api.model.Merchant" />
    </data>

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/imageViewPhoto"
            android:layout_width="@dimen/preview_image_height"
            android:layout_height="@dimen/preview_image_height"
            android:onClick="clickHandler.onClickImageViewFavorite()"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>
    </android.support.constraint.ConstraintLayout>
</layout>

好的。它工作正常。 问题:

  1. 是否可以通过 java 文件在 xml 中设置变量 test_variable 的值?
  2. 将此变量的值设置为 android:layout_width ?

类似这样的:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
        <variable name="test_variable"  type="Integer"/>
    </data>

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/imageViewPhoto"
            android:layout_width="@{test_variable}"
            android:layout_height="@dimen/preview_image_height"/>

    </android.support.constraint.ConstraintLayout>

</layout>

【问题讨论】:

    标签: android xml variables android-databinding


    【解决方案1】:

    你不用担心你也可以设置heightwidth的元素来自Activity如下

    textView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
    

    【讨论】:

    • 我只想在 xml 文件中设置 height。我不想'为此使用 java 代码。
    猜你喜欢
    • 2010-10-09
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 2019-09-27
    • 2012-06-10
    相关资源
    最近更新 更多