是否可以通过编程方式将项目参数设置为可绘制的xml文件?

时间:2019-05-28 15:58:48

标签: java android xml

我有一个可绘制的文件,其中包含图层列表和项目。我正在尝试通过Java类中的变量(或方法)设置一项的位置。

我试图通过id查找它并使用setLeft(int),但是它不起作用。

findViewById(R.id.arr).setLeft(tone.position());
  • tone.positions()给我整数值
<View
            android:id="@+id/vid"
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:layout_marginStart="90dp"
            android:layout_marginEnd="90dp"
            android:background="@drawable/line"/>

这在MainActivity xml文件的LinearLayout中

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#00ffffff"/>
        </shape>
    </item>
    <item android:gravity="center">
        <shape android:shape="rectangle">
            <size android:height="1dp"/>
            <solid android:color="#000000"/>
        </shape>
    </item>
    <item
        android:id="@+id/arr"
        android:left="10dp"
        android:gravity="center_horizontal"
        android:bottom="5dp"
        android:top="-5dp"
        android:drawable="@drawable/arrow" />
</layer-list>

有我的可绘制文件。我想使用“ arr” ID更改项目中的“ left”属性。 有可能吗?

1 个答案:

答案 0 :(得分:0)

findViewById()可用于检索布局xml文件中的View。更具体地说,是您使用setContentView()设置的布局。您的示例可能会返回null,因为您的布局中没有 @+id/arr。因此,您只能使用findViewById()来检索android:id="@+id/vid"

通过首先获得View,您也许可以实现所需的目标。然后从该视图获取背景。

类似的东西(未经测试):

val view = findViewById(R.id.vid)
val background = view.background as? LayerDrawable
background?.setLayerInsetLeft(R.id.arr, tone.positions())

或使用Java(不确定语法,但您会明白的):

View view = findViewById(R.id.vid);
LayerDrawable background = (LayerDrawable)(view.getBackground());
background.setLayerInsetLeft(R.id.arr, tone.positions());

有关更多详细信息,您可以使用LayerDrawable look at the official documentation