개발모음집

[안드로이드 프로그래밍] Day15 선택위젯의 사용과 커스텀뷰 만들기 본문

Android

[안드로이드 프로그래밍] Day15 선택위젯의 사용과 커스텀뷰 만들기

void 2016. 6. 9. 13:24

위젯의 대표적인 예가 버튼, 버튼에 배경이미지를 추가할 시에 이미지가 버튼크기보다 크다면 자동으로 이미지만큼 커진다.


그래서 둥근 버튼 등 왜곡되는 영역이 생길 수 가 있다.

그래서 나인패치가 생김(깨짐을 줄여주기 위해서 생김)



1. arrow_left_normal.png과 arrow_left_clicked.png를 res.drawable폴더에 넣자


2. activity_main.xml에 버튼을 생성하고 백그라운드로 android:background="@drawable/arrow_left_selector"를 지정해주자 


MySelector의 res.drawable.arrow_left_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/arrow_left_clicked" />
<item android:drawable="@drawable/arrow_left_normal" />
</selector>
<!--버튼의 상태에 따라서 이미지를 어떤것을 보여줄건지 지정해줌
이 파일을 버튼의 백그라운드에 이미지처럼 추가해라. 그러면 실행했을 때 이미지처럼 사용이 가능하다.
android:state_pressed="true" 는 눌렸을 상태를 말한다, 이 속성이 없는 두번째 소스는 일반적인 상황을 말한다
-->



버튼클래스를 상속해서 버튼만들기


MySelector의 BitmapButton.java

package com.example.tristan91.myselecter;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;

/**
* Created by Tristan91 on 2016-06-09.
*/
public class BitmapButton extends Button {// 생성자는 두 개 이상 생성해줘야 한다.
public BitmapButton(Context context) {
super(context);
init();
}

public BitmapButton(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public void init() {
setBackgroundResource(R.drawable.arrow_left_normal);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction(); //액션정보를 정수로 반환
if(action == MotionEvent.ACTION_DOWN) {
setBackgroundResource(R.drawable.arrow_left_clicked);
} else if (action == MotionEvent.ACTION_UP) {
setBackgroundResource(R.drawable.arrow_left_normal);
}
return true;
}
}

MySelector의 activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.tristan91.myselecter.MainActivity">

<Button
android:layout_width="100dp"
android:layout_height="100dp"
android:id="@+id/button"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="97dp"
android:background="@drawable/arrow_left_selector" />

<com.example.tristan91.myselecter.BitmapButton
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/button"
android:layout_alignStart="@+id/button"
android:layout_marginBottom="90dp" />
</RelativeLayout>
<!--아래 버튼이 버튼클래스 상속으로 만든 버튼, 비트맵버튼생성시 패키지명까지 다써줘야한다.-->