Android自绘widget有更加容易的方法。
假如你要创建一个很像android里其中一个内置widget,那么你可以直接继承这个widget,然后重载你想改变的行为。
在后面的例子中是这种自绘widget的实现,同时在实现前,先说一些需要注意的。
<!--[if !supportLists]-->1. <!--[endif]-->从例子中,可以看到我们继承类的属性不同于之前,public static class LinedEditText extends EditText,在其中我们的类访问属性为static,在java中static class只能做为内部类使用,
<!--[if !supportLists]-->2. <!--[endif]-->在例子继承了onDraw,在同时也调用了父类的onDraw。
<!--[if !supportLists]-->3. <!--[endif]-->因为我们把类直接定义到了activity中,跟试用widget的activity同个layout,
所以在xml中的定义也要所不同
下面是示例程序:
Layout的main.xml
<?xmlversion="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<view
class="com.OwnWidget.OwnWidget$LinedEditText"
android:id="@+id/widget_myLinedEditText"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:scrollbars="vertical"
android:fadingEdge="vertical" />
</LinearLayout>
然后建立自己的Widget(OwnButton)和调用的activity代码:
package com.OwnWidget;
import com.OwnWidget.OwnButton.OwnButton;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.AttributeSet;
import android.widget.EditText;
import android.widget.LinearLayout;
public class OwnWidget extends Activity {
/** Calledwhen the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*LinearLayout layout = newLinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
OwnButton btn = new OwnButton(this);
layout.addView(btn);
setContentView(layout);*/
setContentView(R.layout.main);
}
public static class LinedEditText extends EditText
{
private Rect mRect;
private Paint mPaint;
public LinedEditText(Context context)
{
super(context);
mRect = new Rect();
mPaint = new Paint();
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(0x800000FF);
}
// we need this constructor for LayoutInflater
public LinedEditText(Context context,AttributeSet attrs)
{
super(context, attrs);
mRect = new Rect();
mPaint = new Paint();
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(0x800000FF);
}
@Override
protected void onDraw(Canvas canvas)
{
Rectr = mRect;
Paintpaint = mPaint;
int count =getLineCount();
for (int i = 0; i <count; i++)
{
int baseline = getLineBounds(i, r);
canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint);
}
super.onDraw(canvas);
}
}
}