【发布时间】:2013-01-25 21:01:22
【问题描述】:
我正在尝试在现有视图中添加自定义 XML 属性
将它们添加到自定义视图并不是什么大问题,但我不知道如何在“基本”视图中访问这些属性(例如 TextView、LinearLayout、ImageView ...)
当涉及片段和/或库项目时,这会更加困难
到目前为止,这是我的代码
海关属性定义和 XML(attrs.xml 和布局):
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="StarWars">
<attr name="jedi" format="string" />
<attr name="rank" format="string" />
</declare-styleable>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:sw="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="28dp"
android:gravity="center_horizontal"
sw:jedi="Obiwan" />
<TextView
android:id="@+id/rank"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="28dp"
android:gravity="center_horizontal"
sw:rank="Master" />
由于我在 Fragment 上对此进行了膨胀(所以没有使用 attrs arg 的 onCreate !),尝试获取 2 sw 自定义属性的唯一方法是:
-
在onCreateView中为Fragment LayoutInflater设置一个自定义的LayoutInflater.Factory
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); LayoutInflater layoutInflater = inflater.cloneInContext(inflater.getContext()); layoutInflater.setFactory(new StarWarsLayoutFactory()); View fragmentView = layoutInflater.inflate(R.layout.jedi, container, false); ((TextView) fragmentView.findViewById(android.R.id.jedi)).setText("Yep"); return fragmentView; } -
尝试获取自定义 LayoutInflater.Factory 上的自定义属性:
public class StarWarsLayoutFactory implements Factory { @Override public View onCreateView(String name, Context context, AttributeSet attrs) { *** What to do here ? *** return null; } }
有人有过这样的问题吗?
我在这里缺少什么?
提前谢谢!
【问题讨论】:
标签: android android-fragments android-view android-xml android-custom-attributes