【发布时间】:2017-12-26 17:00:19
【问题描述】:
我创建了一个自定义控件,它是 LinearLayout 的子类。我还创建了这个控件所基于的布局文件。最后,我定义了在构造函数中解析的属性以设置我的自定义属性。例如,其中一个属性称为“文本”。
这是我的代码的简化版本(我已经删除了很多其他属性,因此我们可以只关注一个属性“文本”):
首先,类(我们自定义的 RadioButton 版本)...
public class RadioButton extends LinearLayout
{
private TextView textView;
public RadioButton(Context context, AttributeSet attrs)
{
super(context, attrs);
initAttributes(attrs, 0);
}
private void initAttributes(AttributeSet attrs, int defStyle)
{
final TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.CheckBoxView, defStyle, 0);
text = a.getString(R.styleable.RadioButton_text);
if(text == null)
text = "Not set";
a.recycle();
}
@Override
protected void onFinishInflate()
{
super.onFinishInflate();
textView = (TextView)findViewById(R.id.textView);
textView.setText(text);
}
private String text;
public String getText() { return text; }
public void setText(String newValue)
{
text = newValue;
if(textView != null)
textView.setText(text);
}
}
这是 attrs.xml 文件...
<resources>
<attr name="text" format="string" />
<declare-styleable name="RadioButton">
<attr name="text" />
</declare-styleable>
</resources>
这里是“reusable_radiobutton.xml”布局文件(注意:内部 RadioButtonView 是自定义渲染的视图,工作正常):
<?xml version="1.0" encoding="utf-8"?>
<com.somedomain.reusable.ui.RadioButton
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical">
<com.somedomain.reusable.ui.RadioButtonView
android:id="@+id/radioButtonView"
style="@style/DefaultRadioButtonView" />
<TextView
android:id="@+id/textView"
style="@style/DefaultRadioButtonText" />
</com.somedomain.reusable.ui.RadioButton>
通过以上,我的控件的用户可以简单地将它包含在他们自己的布局文件中,就像这样......
<include android:id="@+id/someRadioButton"
layout="@layout/reusable_radiobutton" />
在他们的代码中,使用以下内容,他们可以获得该实例并按照他们的意愿使用它,就像这样......
RadioButton someRadioButton = (RadioButton)findViewById(R.id.someRadioButton);
someRadioButton.text = "Woot!";
这按预期工作。
但是,这并不...
<include android:id="@+id/someRadioButton"
layout="@layout/reusable_radiobutton"
app:text="Hello World!" />
它会给我一个警告,否则会忽略它。
然后我尝试了这个......
<com.somedomain.reusable.ui.RadioButton
app:text="Hello World!" />
虽然这确实实例化了我的控件并传递了“Hello World!”通过属性到我的属性,实际上没有加载甚至将布局文件关联到我的类,因此屏幕上什么也没有出现!
那么我怎样才能创建一个基于布局的自定义视图,其他开发人员可以在他们自己的布局文件中简单地引用它,同时还允许他们设置自定义属性?
希望一切都有意义! :)
注意:Android 文档确切地谈到了我所追求的“复合控件”as referenced here,但他们没有给出使用布局来定义复合控件的示例。不过,我觉得这已经很接近了。
【问题讨论】:
标签: android android-layout android-custom-view android-attributes