Per*_*man 4 android custom-widgets android-drawable android-custom-attributes
我有一个自定义控件(现在很简单)就像一个按钮.它需要显示未按下和按下的图像.它在活动中出现多次,并且具有不同的图像对,具体取决于它的使用位置.想想工具栏图标 - 与此类似.
这是我的布局的摘录:
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:MyApp="http://schemas.android.com/apk/res/com.example.mockup"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TableRow>
<com.example.mockup.ImageGestureButton
android:id="@+id/parent_arrow"
android:src="@drawable/parent_arrow"
MyApp:srcPressed="@drawable/parent_arrow_pressed"
... />
...
</TableRow>
</TableLayout>
Run Code Online (Sandbox Code Playgroud)
attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ImageGestureButton">
<attr name="srcPressed" format="reference" />
</declare-styleable>
</resources>
Run Code Online (Sandbox Code Playgroud)
并且,在R.java中,人们发现:
public static final class drawable {
public static final int parent_arrow=0x7f020003;
public static final int parent_arrow_pressed=0x7f020004;
...
}
Run Code Online (Sandbox Code Playgroud)
在窗口小部件实例化期间,我想确定活动xml中声明的id.我怎么做?我试过这个(我使用工作代码更新了我原来的帖子;所以,以下工作.)
public class ImageGestureButton extends ImageView
implements View.OnTouchListener
{
private Drawable unpressedImage;
private Drawable pressedImage;
public ImageGestureButton (Context context, AttributeSet attrs)
{
super(context, attrs);
setOnTouchListener (this);
unpressedImage = getDrawable();
TypedArray a = context.obtainStyledAttributes (attrs, R.styleable.ImageGestureButton, 0, 0);
pressedImage = a.getDrawable (R.styleable.ImageGestureButton_srcPressed);
}
public boolean onTouch (View v, MotionEvent e)
{
if (e.getAction() == MotionEvent.ACTION_DOWN)
{
setImageDrawable (pressedImage);
}
else if (e.getAction() == MotionEvent.ACTION_UP)
{
setImageDrawable (unpressedImage);
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
如果你想获得drawable,请使用TypedArray.getDrawable().在您的示例中,您使用的是getString().
在你的declare-styleable使用中
<attr name="srcPressed" format="reference" />
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5719 次 |
| 最近记录: |