我正在尝试重用原始形状,并使用这些声明性XML元素组成我的大部分用户界面.
但我不想为每个属性值及其排列创建单独的XML文件,并且在此过程中复制了大部分工作.
例如,我希望这个形状的消费者能够定义android:radius值?
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:startColor="#449def"
android:endColor="#2f6699"
android:angle="270"/>
<stroke
android:width="1dp"
android:color="#2f6699"/>
<corners
android:radius="3dp"/>
</shape>
Run Code Online (Sandbox Code Playgroud)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/shape_box_round_blue_uniform" />
<!-- How to set the corner radius here? -->
<item android:drawable="@drawable/shape_box_round_blue" />
</selector>
Run Code Online (Sandbox Code Playgroud)
我一直在为Android的自定义控件工作,虽然我试图做这里建议的东西似乎有些事我做错了.
这是我的代码,看看是否有人可以发现问题:
MyComponent.java
public MyComponent(Context context, AttributeSet attrs)
{
super(context);
TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.MyComponent);
CharSequence myId = arr.getString(R.styleable.MyComponent_identifier);
if (myId != null)
{
this.setIdentifier(myId.toString());
}
Integer cds = arr.getInteger(R.styleable.MyComponent_cd_number, 0);
if(cds != null)
{
this.setCds(cds);
}
arr.recycle();
}
Run Code Online (Sandbox Code Playgroud)
attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyComponent">
<attr name="cd_number" format="integer" />
<attr name="identifier" format="string" />
</declare-styleable>
</resources>
Run Code Online (Sandbox Code Playgroud)
main.xml中
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:bgl="http://schemas.android.com/apk/res/my.test.package.components"
android:id="@+id/table"
android:layout_width="match_parent"
android:layout_height="match_parent">
...
<my.test.package.MyComponent
android:id="@+id/hand"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="2"
bgl:cd_number="4"
bgl:identifier="plr"/>
...
</TableLayout>
Run Code Online (Sandbox Code Playgroud)
当我把它我得到以下错误:
错误:未发现在包"my.test.package"错误属性"cd_number"资源标识符:没有在包"my.test.package"找到的属性"识别符"资源标识符
如果我将命名空间更改为:
xmlns:bgl="http://schemas.mywhatever.com/apk/res/my.test.package"
Run Code Online (Sandbox Code Playgroud)
...错误发生并且事情运行但myId为null并且cds为0(默认值!)返回MyComponent.java构造函数. …
我想创建一个自定义视图TestView
类,我可以通过它创建对象new TestView()
.但是,新的视图类需要AttributeSet对象.从哪里获取AttributeSet以及它包含哪些内容?