Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 初級開發 >> Android 自定義View

Android 自定義View

編輯:初級開發

在values/attrs.xml中: <?XML version="1.0" encoding="utf-8"?>
<resources> <declare-styleable name="MyVIEw">
<attr name="textColor" format="color" />
<attr name="textSize" format="dimension" />
<attr name="imgBackground" format="integer" />
<attr name="textPaddingLeft" format="dimension"/>
<attr name="textPaddingTop" format="dimension"/>
</declare-styleable> </resources>
編寫MyView.java,繼承View package test.cuntomizedvIEw; import Java.util.Calendar; import test.cuntomizedvIEw.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.View; public class MyView extends View { private Paint mPaint; private Context mContext; private String mStr; public MyVIEw(Context context, AttributeSet attrs) {
super(context, attrs); mContext = context;
initMyVIEw(); TypedArray params = context.obtainStyledAttributes(attrs,
R.styleable.MyVIEw);
int backgroudId = params.getResourceId(
R.styleable.MyVIEw_imgBackground, 0);
if (backgroudId != 0)
setBackgroundResource(backgroudId);
int textColor = params.getColor(R.styleable.MyVIEw_textColor,
0XFFFFFFFF);
setTextColor(textColor);
float textSize = params.getDimension(R.styleable.MyVIEw_textSize, 36);
setTextSize(textSize);
float paddingLeft = params.getDimension(
R.styleable.MyVIEw_textPaddingLeft, 41);
float paddingTop = params.getDimension(
R.styleable.MyVIEw_textPaddingTop, 21);
setPaddings(paddingLeft, paddingTop);
} @Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas); if(mStr != null) {
canvas.drawText(mStr, 0, 0, mPaint); canvas.drawText("heiheihei", 30, 60, mPaint);
} private void initMyVIEw() {
mPaint = new Paint();
mPaint.setColor(Color.WHITE);
} private void setTextColor(int textColor) {
mPaint.setColor(0XFFAABBCC);
} private void setTextSize(float textSize) {
mPaint.setTextSize(textSize);
} private void setPaddings(float paddingLeft, float paddingTop) { setPadding((int)paddingLeft, (int)paddingTop, 0, 0); } // 注意怎樣在attrs中怎樣定義background並取得background。 在layout中使用MyVIEw,
main.XML
<?XML version="1.0" encoding="utf-8"?>
<LinearLayout XMLns:android="http://schemas.android.com/apk/res/android"
XMLns:app="http://schemas.android.com/apk/res/test.cuntomizedvIEw"
android:orIEntation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent"> <test.cuntomizedview.MyVIEw android:id="@+id/v"
android:layout_width="fill_parent" android:layout_height="fill_parent"
app:textColor="#FFFFFFFF" app:textSize="40dip"
app:textPaddingLeft="40dip" app:textPaddingTop="40dip"
app:imgBackground="@drawable/bg_time"
/>
</LinearLayout>
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved