gpt4 book ai didi

android - 如何为扩展布局定义 AttributeSet 参数

转载 作者:行者123 更新时间:2023-11-30 02:35:10 26 4
gpt4 key购买 nike

我无法理解如何在代码中实例化自定义布局。具体来说,我不知道如何定义所需的 AttributeSet 参数。

我已经阅读了官方文档,但无法全神贯注:

http://developer.android.com/training/custom-views/create-view.html http://developer.android.com/reference/android/util/AttributeSet.html

在我的 Activity 中,我将其实例化为:

new MyCustomLayout(getActivity(), attrs)

但是我该如何定义attrs呢?

MyCustomLayout.java

public class MyCustomLayout extends LinearLayout implements
OnClickListener {

...
...

public MyCustomLayout(Context context, AttributeSet attrs) {

super(context, attrs);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.mycustomxmllayout, this, true);
...
}

...
}

mycustomxmllayout.xml

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android" >

<TextView
android:id="@+id/txt_1"
android:layout_width="60dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:lines="1"/>

<Button
android:id="@+id/btn_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="0dp"
android:minWidth="0dp"
android:background="@null"
android:text="x"
android:layout_weight="1"
/>

</merge>

最佳答案

首先,您应该在 res/values/attrs.xml 中定义自定义属性, 只需添加 <declare-styleable> ,例如:

   <declare-styleable name="MyCustomLayout">
<attr name="showText" format="boolean" />
<attr name="buttonPosition" format="enum">
<enum name="left" value="0"/>
<enum name="right" value="1"/>
</attr>
</declare-styleable>

现在您可以通过 xml 设置自定义属性,如下所示:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto">
<your.package.name.MyCustomLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
custom:showText="true"
custom:buttonPosition="left" />
</LinearLayout>

在您的构造函数中,您可以获取该属性:

public MyCustomLayout(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.MyCustomLayout,
0, 0);

try {
mShowText = a.getBoolean(R.styleable.MyCustomLayout_showText, false);
mButtonPos = a.getInteger(R.styleable.MyCustomLayout_buttonPosition, 0);
} finally {
a.recycle();
}
}

如果您想以编程方式设置属性,您应该为此创建公共(public) getter/setter:

private boolean mShowText;
private Integer mButtonPos;

public void setButtonPos(int pos) {
mButtonPos = pos;
}

public void setShowText(boolean showText) {
mShowText = showText;
}

之后,您可以通过编程方式设置属性:

MyCustomLayout layout = new MyCustomLayout(getActivity());
layout.setButtonPos(0);
layout.setShowText(true);

关于android - 如何为扩展布局定义 AttributeSet 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26686802/

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