如何从代码中访问默认的安卓风格



我正试图通过修改android源代码来编写我自己版本的android.widget.SeekBar:我不能使用派生类,因为我想使用派生类不可见的私有成员变量来覆盖一些行为。

SeekBar和大多数小部件一样,都是样式化的。我想改变行为,但不想改变样式,所以我需要获得android.widget.SeekBar使用的默认样式。android源代码中的版本有这样的风格:-

final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.SeekBar, defStyleAttr, defStyleRes);
final drawable thumb = a.getDrawable(R.styleable.SeekBar_thumb);
...
a.recycle();

用户代码中无法访问WellR.styleable。如何通过派生类访问Android内部样式属性的答案?建议将R.styleable.SeekBar替换为new int[] { android.R.attr.seekBarStyle },但省略了a.recycle(),我怀疑这可能是错误的。它还说,一次只能通过这种方式访问一个样式属性。假设每次都需要回收TypedArray

然而,SeekBar有很多样式属性,从r.attr导出的唯一东西是android.R.attr.seekBarStyle,它是一个单一的整数。我如何获取单个样式属性?

您可以使用以下代码获取默认资源的值:-

Resources res = getResources();
int defStyleAttr = res.getIdentifier(
"android:attr/seekBarStyle", "", "android");
int resId = res.getIdentifier(
"android:attr/thumb", "", "android");
TypedArray a = obtainStyledAttributes(
null, new int[] {resId}, defStyleAttr, 0);
final Drawable thumb = a.getDrawable(0);
a.recycle();
resId = res.getIdentifier(
"android:attr/thumbTint", "", "android");
a = obtainStyledAttributes(
null, new int[] {resId}, defStyleAttr, 0);
ColorStateList ThumbTintList = null;
ThumbTintList = a.getColorStateList(0);
a.recycle();
resId = res.getIdentifier(
"android:attr/progressDrawable", "", "android");
a = obtainStyledAttributes(
null, new int[] {resId}, defStyleAttr, 0);
final Drawable track = a.getDrawable(0);
a.recycle();
resId = res.getIdentifier(
"android:attr/progressTint", "", "android");
a = obtainStyledAttributes(
null, new int[] {resId}, defStyleAttr, 0);
ColorStateList progressTintList = null;
progressTintList = a.getColorStateList(0);
a.recycle();
resId = res.getIdentifier(
"android:attr/paddingLeft", "", "android");
a = obtainStyledAttributes(
null, new int[] {resId}, defStyleAttr, 0);
int paddingLeft = a.getInt(0, 0);
a.recycle();
resId = res.getIdentifier(
"android:attr/paddingTop", "", "android");
a = obtainStyledAttributes(
null, new int[] {resId}, defStyleAttr, 0);
int paddingTop = a.getInt(0, 0);
a.recycle();
resId = res.getIdentifier(
"android:attr/paddingRight", "", "android");
a = obtainStyledAttributes(
null, new int[] {resId}, defStyleAttr, 0);
int paddingRight = a.getInt(0, 0);
a.recycle();
resId = res.getIdentifier(
"android:attr/paddingBottom", "", "android");
a = obtainStyledAttributes(
null, new int[] {resId}, defStyleAttr, 0);
int paddingBottom = a.getInt(0, 0);
a.recycle();

getIdentifier已弃用,但目前(2022年1月4日(仍然有效。当然,你需要知道资源的名称。你可以通过去掉初始类名和下划线从R.styleable中得到这些。

getResourcesobtainStyledAttributesContext的成员函数,所以如果您不是从继承Context的类调用它们(Activities可以,但widgets不可以(,那么您需要在前面有一个context.

您可以通过查找要替换的小部件的源代码来获得defStyleAttr的名称:它似乎是首字母小写的小部件类的名称;风格"附件。如果您正在创建一个全新的小部件,0应该可以,但我还没有对此进行适当的测试。

最新更新