Ser*_*m's 59 android attributes custom-controls
我写了一个扩展的自定义视图RelativeLayout
.我的视图有文本,所以我想使用标准,android:text
而不需要在每次使用自定义视图时指定<declare-styleable>
和不使用自定义命名空间xmlns:xxx
.
这是我使用自定义视图的xml:
<my.app.StatusBar
android:id="@+id/statusBar"
android:text="this is the title"/>
Run Code Online (Sandbox Code Playgroud)
如何获取属性值?我想我可以得到android:text属性
TypedArray a = context.obtainStyledAttributes(attrs, ???);
Run Code Online (Sandbox Code Playgroud)
但???
在这种情况下是什么(在attr.xml中没有样式)?
psk*_*ink 87
用这个:
public YourView(Context context, AttributeSet attrs) {
super(context, attrs);
int[] set = {
android.R.attr.background, // idx 0
android.R.attr.text // idx 1
};
TypedArray a = context.obtainStyledAttributes(attrs, set);
Drawable d = a.getDrawable(0);
CharSequence t = a.getText(1);
Log.d(TAG, "attrs " + d + " " + t);
a.recycle();
}
Run Code Online (Sandbox Code Playgroud)
我希望你有个主意
J. *_*eck 39
编辑
另一种方法(指定一个声明样式但不必声明自定义命名空间)如下:
attrs.xml:
<declare-styleable name="MyCustomView">
<attr name="android:text" />
</declare-styleable>
Run Code Online (Sandbox Code Playgroud)
MyCustomView.java:
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView);
CharSequence t = a.getText(R.styleable.MyCustomView_android_text);
a.recycle();
Run Code Online (Sandbox Code Playgroud)
这似乎是从自定义视图中提取标准属性的通用Android方式.
在Android API中,他们使用内部的R.styleable类来提取标准属性,并且似乎没有提供使用R.styleable提取标准属性的其他选择.
原帖
要确保从标准组件获取所有属性,应使用以下内容:
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TextView);
CharSequence t = a.getText(R.styleable.TextView_text);
int color = a.getColor(R.styleable.TextView_textColor, context.getResources().getColor(android.R.color.darker_gray)); // or other default color
a.recycle();
Run Code Online (Sandbox Code Playgroud)
如果您想要来自另一个标准组件的属性,只需创建另一个TypedArray.
有关标准组件的可用TypedArrays的详细信息,请参阅http://developer.android.com/reference/android/R.styleable.html.
归档时间: |
|
查看次数: |
16993 次 |
最近记录: |