LoginSignup
6
5

More than 5 years have passed since last update.

Android:XMLレイアウトから呼び出せる自作View

Posted at

サンプルとして簡易TextViewを作ってみました。

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns: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="Hello World, MyActivity"
            />
    <com.example.MyTextView xmlns:app="http://hoge/app"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            app:text="Hello MyTextView."
                            app:textSize="48"
                            app:textColor="#FFFF0000"
                            app:background="#FFFFFFFF"/>

</LinearLayout>
MyTextView.java
package com.example;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

public class MyTextView extends View {
    private static final int BACKGROUND_COLOR = 0;
    private static final int TEXT_COLOR=Color.WHITE;
    private static final int TEXT_SIZE = 12;
    private String text="no data";
    private Paint paint;

    public MyTextView(Context context) {
        super(context);
        paint=makePaint(TEXT_COLOR, TEXT_SIZE);
        setBackgroundColor(BACKGROUND_COLOR);
    }

    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        final String NAME_SPACE = "http://hoge/app";
        text=attrs.getAttributeValue(NAME_SPACE,"text");
        int fontColor = attrs.getAttributeIntValue(NAME_SPACE, "textColor", TEXT_COLOR);
        setBackgroundColor(attrs.getAttributeIntValue(NAME_SPACE,"background",BACKGROUND_COLOR));
        paint=makePaint(fontColor,(attrs.getAttributeIntValue(NAME_SPACE,"textSize",TEXT_SIZE)));
    }
    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawText(text,0,-paint.getFontMetrics().top,paint);
    }

    private Paint makePaint(int fontColor,int size) {
        Paint paint=new Paint();
        paint.setAntiAlias(true);
        paint.setTextSize(size);
        paint.setColor(fontColor);
        return paint;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int y=(int)(paint.getFontMetrics().bottom-paint.getFontMetrics().top);
        setMeasuredDimension((int) paint.measureText(text),y);
    }
}
6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5