gpt4 book ai didi

android - 使用自定义属性在 标签中使用的布局内编辑 View (TextView/ImageView)

转载 作者:搜寻专家 更新时间:2023-11-01 08:23:06 27 4
gpt4 key购买 nike

我是 Android 开发新手。
是否可以使用自定义属性更改包含的布局内的 View ?

我的意思是这样的:

这是 my_layout xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/listItem"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<ImageView
android:id="@+id/userImage"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="..." />
<!-- this src attribute can be overrided using my own attribute in the iclude tage -->

<TextView
android:id="@+id/userName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="..." />
<!-- this text attribute can be overrided using my own attribute in the iclude tage -->
</LinearLayout>

这就是我想要将 my_layout 包含到 Activity 布局中的方式:

<include layout="@layout/my_layout" userName="@string/userName1" userImage="@drawable/userImage1"/>

userNameuserImage 覆盖 android:textandroid:src 属性的值。

我读过 Data Binding但我在这里的意思是不使用任何 Java 类。我只需要在 my_layout 的数据标签中定义一个变量,其 type 值引用到 @string/@drawable/获取文本或图片。

这可能吗?

最佳答案

根据您的描述,您希望将 userName1userImage1 发布到 my_layout 中的 View 。你做不到。而且您使用自定义 View 的方式是错误的。标签“include”也不是自定义标签。

您可以按照此示例使用自定义属性:

<com.amscf.view.InviteItemView
android:id="@+id/invite_item_instagram"
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="@drawable/item_color"
android:paddingBottom="10dp"
android:paddingTop="10dp"
app:appicon="@drawable/icon_app_instagram"
app:btntext=""
app:coindesc="Post a invitation"
app:cointext="Share to Instagram"
app:showweek="false"/>

InviteItemView View 中,您可以使用以下代码获取属性 appIconbtnText:

TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.invite_item_view);
int refId = typedArray.getResourceId(R.styleable.invite_item_view_appicon, R.mipmap.ic_launcher);
String btnText = typedArray.getString(R.styleable.invite_item_view_btntext);

refIdbtnText 是您将获得的内容。

将下面的代码添加到你的attrs.xml,这是invite_item_view的定义

<declare-styleable name="invite_item_view">
<attr name="appicon" format="reference"/>
<attr name="cointext" format="string"/>
<attr name="coindesc" format="string"/>
<attr name="btntext" format="string"/>
<attr name="showweek" format="boolean"/>
</declare-styleable>

关于android - 使用自定义属性在 <include> 标签中使用的布局内编辑 View (TextView/ImageView),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48275383/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com