我正在尝试使用styles.xml 中定义的自定义属性来获取按钮自定义属性以返回真/假。我的例子很简单,只有两个按钮,但我无法让它工作。我的布局看起来像:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".CustomAttr">
<Button
android:id="@+id/button_1"
style="@style/red_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 1!" />
<Button
android:id="@+id/button_2"
style="@style/blue_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 2!" />
</LinearLayout>
<resources>
样式.xml 看起来像:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<attr name="is_red" format="boolean"/>
<style name="red_button" >
<item name="android:background">#ffff0000</item>
<item name="is_red">true</item>
</style>
<style name="blue_button" >
<item name="android:background">#ff0000ff</item>
<item name="is_red">false</item>
</style>
</resources>
代码如下:
public class CustomAttr
extends AppCompatActivity
implements View.OnClickListener {
private static final String TAG =
CustomAttr.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_attr);
findViewById(R.id.button_1)
.setOnClickListener(this);
findViewById(R.id.button_2)
.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int id = v.getId();
int [] searchAttr = {R.attr.is_red};
TypedArray attrs
= v.getContext()
.obtainStyledAttributes(null, searchAttr);
boolean isRed = attrs.getBoolean(0, false);
Log.d(TAG, String.format("%s:%b"
, (id == R.id.button_1) ? "button 1" : "button 2"
, isRed )
);
}
}
一切编译正常,按钮颜色正常,我没有收到任何警告。但是 onClick 方法中的布尔值 isRed 总是返回 false。
我整天都在浏览网络和文档,这看起来应该可以工作——但事实并非如此。我究竟做错了什么?
谢谢
史蒂夫·S。
********* 编辑 2018 年 9 月 21 日星期五 10:17:01 PDT *********
如下所述,这是一个应用程序的原型,在网格视图中有大约 250 个不同的按钮。基本上有 4 种不同类型的大约 250 种,我可以使用 4 种不同样式中的一种来设置每个按钮中的几乎所有内容。我已经在使用标签和文本字段,并且确实需要一种方法来检测按钮的类型 (1 0f 4)。我终于用它自己的属性集创建了一个自定义按钮视图。工作原型自定义视图按钮的代码及其在github上的属性。谢谢!
史蒂夫·S。