2016년 6월 29일 수요일

Android Studio - 안드로이드위젯을 활용하여 나만의 위젯만들기


1. 위젯을 상속 받은 나만의 위젯구현
2. XML 파일에서 위젯태그의 attribute 속성을 추가
3. res/layout 밑에 새로 만든 위젯을 입력
4. 추가된 attribute 속성을 TitleTextView.java 에서 접근



[위젯을 상속 받은 나만의 위젯구현]

public class TitleTextView extends TextView {

    private boolean complete;
    private int completeColor;
    private float completeWidth;

    public TitleTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    public TitleTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public TitleTextView(Context context) {
        super(context);
        init(context, null);
    }

    private void init(Context context, AttributeSet attrs){
        complete = true;
        completeColor = Color.RED;
        completeWidth = 6;
    }

    @Override    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if(complete){
            Paint paint = new Paint();
            float x=0;
            float y=getHeight()/2;
            float dx = getWidth();
            float dy = y;
            paint.setColor(completeColor);
            paint.setAlpha(0x99);
            paint.setStrokeWidth(completeWidth);
            canvas.drawLine(x,y,dx,dy,paint);
        }

    }
}

[XML 파일에서 위젯태그의 attribute 속성을 추가]

res/value 밑에 attrs.xml 생성



[res/layout 밑에 새로 만든 위젯을 입력]

스키마 namespace를 추가 하고(Android studio는 자동 추가 되긴 함)

xmlns:app="http://schemas.android.com/apk/res-auto"

<myapp.TitleTextView    
android:id="@+id/titleTxt"    
android:layout_width="match_parent"    
android:layout_height="wrap_content"    
android:layout_toRightOf="@id/icon"    
style="@style/TodoStyle"    
android:lines="1"    
app:complete="true"    
app:completeColor="@android:color/holo_green_dark"    
app:completeWidth="12px"    
/>


[추가된 attribute 속성을 TitleTextView.java 에서 접근]

추가된 attribute 속성은, AttributeSet 클래스에 들어가게 된다.

public TitleTextView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(context, attrs);
}

이 AttributeSet 에서 내가 추가 한 attribute 속성을 가져 오기 위해선

private void init(Context context, AttributeSet attrs){
    TypedArray att = context.obtainStyledAttributes(attrs, R.styleable.TitleTextView);
    complete = att.getBoolean(R.styleable.TitleTextView_complete, false);
    completeColor = att.getColor(R.styleable.TitleTextView_completeColor, Color.RED);
    completeWidth = att.getDimension(R.styleable.TitleTextView_completeWidth, 6);
}


댓글 없음:

댓글 쓰기