我有我实现了作为组成的复合控件的自定义按钮:在根改变一个Android复合控件的启用状态,同时保持其样式设置
- 一个FrameLayout里,这是我使用@android:style/Widget.Holo.Button进行了样式设计,以便像按钮一样进行查看和操作;
- 两个TextView作为上述FrameLayout的子项,配置了duplicateParentState = true,这样如果我将FrameLayout设置为false,它们将显示为禁用。
修整后的XML看起来如下:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
style="@android:style/Widget.Holo.Button"
android:id="@+id/layout_button">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PLACEHOLDER"
android:layout_gravity="center_horizontal|top"
android:duplicateParentState="true"
android:id="@+id/text_button1"
android:textSize="24sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PLACEHOLDER"
android:layout_gravity="center_horizontal|bottom"
android:duplicateParentState="true"
android:id="@+id/text_button2"
android:textSize="12sp"/>
</FrameLayout>
随着对复合控件的XML布局,我创建了一个Java实现的Android文档,它看起来是这样的描述:
public class CustomButton extends FrameLayout {
public CustomButton (Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutInflater.inflate(R.layout.control_custombutton, this, true);
}
}
如果我正确理解,当这种控制被用来构建的层次结构将(指示括号其中该视图中定义):
FrameLayout (Java) -> FrameLayout (XML) -> 2x TextViews (XML)
我希望能够切换我的自定义按钮是否处于启用或不获取到按钮的引用,并设置enabled属性,像这样:
CustomButton button = (CustomButton)findViewById(R.id.button);
button.setEnabled(false);
然而,这并不工作,因为在XML中定义的FrameLayout不会继承其父级的属性,因此该按钮将继续显示为已启用。
我已经尝试在XML中定义的FrameLayout中添加duplicateParentState = true,但在这种情况下,我的样式属性被覆盖/继承,并且控件看起来不再像按钮一样。
我也尝试过使用合并标签并以编程方式设置样式,但据我所知,不能通过编程方式设置视图样式。
我的解决方法到目前为止已经覆盖上的CustomButton的的setEnabled()方法,像这样:
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
findViewById(R.id.button_rootLayout).setEnabled(enabled);
}
这工作,但现在我必须为我想以编程方式修改每个属性做到这一点,我有与注册OnClickListeners类似的问题。
有没有更好的方法?
是否有任何理由你从FrameLayout而不是按钮派生自定义按钮? –
Button不是ViewGroup,所以我不能将夸张的Layout附加到它上面,而且我需要Layout,因为定位太复杂,无法用Button的标准setText()处理。 – Zecrates
当你说你的FrameLayout是用XML定义的时候,我很困惑。你应该可以在XML中使用''标签。你能显示布局文件的相关部分吗? –