Android基础教程:自定义带提示文本的EditText组件
[日期:2013-02-17] 来源:Linux社区 作者:zlqqhs [字体:]
效果图如下:
两个类,一个继承Activity的类,一个继承EditText的类,一个xml文件
继承Activity的类:
import Android.app.Activity;
import android.os.Bundle;
public class EditTestActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edittest);
}
}
继承EditText的类:
package com.mrzhu.edittest;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.EditText;
public class EditTextTest extends EditText {
public EditTextTest(Context context) {
super(context);
}
public EditTextTest(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public EditTextTest(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setTextSize(20);
paint.setColor(Color.GRAY);
canvas.drawText("输入提示文本:", 10, getHeight() / 2 + 5, paint);
super.onDraw(canvas);
}
}
edittext.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.mrzhu.edittest.EditTextTest
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="100dp"
android:text="从此处输入文本"
android:id="@+id/test"
/>
</LinearLayout>