android - 为自定义视图重新使用 android 的内置 xml 属性
问题描述
假设我有一个这样的自定义视图(这只是一个例子):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<EditText
android:id="@+id/custom_view_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
我在 attrs.xml 中创建了一个自定义属性:
<declare-styleable name="CustomView">
<attr name="myCustomAttribute" />
</declare-styleable>
这是这个虚构的自定义视图的代码:
public class CustomView extends LinearLayout {
private String mCustomAttr;
public CustomView(Context context) {
super(context);
configure(context);
}
public CustomView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
setupAttributes(context, attrs);
configure(context);
}
public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setupAttributes(context, attrs);
configure(context);
}
private void setupAttributes(Context context, AttributeSet attrs) {
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
mCustomAttr = array.getString(R.styleable.CustomView_myCustomAttribute);
array.recycle();
}
private void configure(Context context) {
LayoutInflater.from(context).inflate(R.layout.custom_view_layout, this);
EditText editText = findViewById(R.id.custom_view_edittext);
// and so on
}
}
我想要做的是使用 EditText 特定的 xml 属性作为我的 CustomView 的属性,即使它的根是 LinearLayout。例如:
<path.to.package.CustomView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:myCustomAttribute="whatever"
android:imeOptions="actionDone" />
有没有办法做到这一点,而不必在我的可声明样式中创建每个 EditText 属性?本质上,我只想在我的setupAttributes
函数中为内置的 xml 属性提供类似的东西。
TypedArray array = context.obtainStyledAttributes(attrs, android.R.styleable.EditText);
解决方案
推荐阅读
- spring - spring-cloud-stream-binder-kafka - 无法使用 ssl 配置创建多个 kafka 活页夹
- php - 无法在 localhost:3000 上设置 cookie
- javascript - 如何动态编辑或更新 Objects CRUD 应用程序的数组?
- java - Java hibernate Query 位类型 postgres
- linux - 在 Linux 上构建 Mono 6.10 后无法找到 msbuild
- ios - 在水平堆栈视图中禁用按钮宽度和高度
- google-chrome - 谷歌浏览器显示的页面颜色、文本和其他所有内容都混乱了
- php - PHP中的快速排序
- php - 使用原始 MySQL 查询创建具有自定义分类和自定义字段的帖子
- terminal - 将进入我的每个目录并根据目录名称更改文件名的脚本