gpt4 book ai didi

android - 使用自定义 XML 属性创建复合控件

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:35:20 25 4
gpt4 key购买 nike

我一直在尝试将 TextView 和 EditText 组合成一个复合控件,该控件使用自定义 xml 元素为每个单独的元素传递默认值。我一直在看这里的教程/文档:
Building Compound Controls
Passing Custom Attributes

到目前为止我有什么。

属性.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="FreeText">
<attr name="label" format="string" />
<attr name="default" format="string" />
</declare-styleable>
</resources>

我的主要布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<com.example.misc.FreeText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
myapp:label="label"
myapp:default="default"
/>
</LinearLayout>

我的复合控件,FreeText:

public class FreeText extends LinearLayout {

TextView label;
EditText value;

public FreeText(Context context, AttributeSet attrs) {
super(context, attrs);

this.setOrientation(HORIZONTAL);

LayoutParams lp = new LayoutParams(0, LayoutParams.WRAP_CONTENT);
lp.weight = 1;

label = new TextView(context);
addView(label, lp);

value = new EditText(context);
addView(value, lp);

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FreeText);
CharSequence s = a.getString(R.styleable.FreeText_label);
if (s != null) {
label.setText(s);
}

a.recycle();
}
}

当我运行该程序时,我看到 View 正常,但我的 CharSequence s 的值始终为空。谁能告诉我哪里出错了?

最佳答案

我讨厌你在寻求帮助后立即发现问题。

问题是我的自定义 XML 元素的命名空间应该是这样的:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<com.example.misc.FreeText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
myapp:label="label"
myapp:default="default"
/>
</LinearLayout>

关于android - 使用自定义 XML 属性创建复合控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5014679/

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