안드로이드에서 Button을 상속하여 커스텀 버튼을 만드는 예
버튼에 터치하면 버튼의 문자열이 적색으로 변경되고 떼면 원래의 색상으로 돌아오는 내용
layout/main.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" android:id="@+id/linearLayout1"> <com.example.androidapp.MyButton android:id="@+id/mybutton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal"/> </LinearLayout>
TestActivity.java
package com.example.androidapp; import android.app.Activity; import android.os.Bundle; public class TestActivity extends Activity { public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); } }
MyButton.java
package com.example.androidapp; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.Button; public class MyButton extends Button { Paint paint; public MyButton(Context context) { super(context); init(); } public MyButton(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { setBackgroundResource(R.drawable.btn_bg); paint = new Paint(); paint.setColor(Color.BLACK); paint.setAntiAlias(true); paint.setTextScaleX(1f); paint.setTextSize(40f); paint.setTypeface(Typeface.DEFAULT); } Rect bounds = new Rect(); // 텍스트가 차지하는 영역의 정보를 저장할 때 사용 @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int w = getWidth(); int h = getHeight(); String title = "눌러보세요"; paint.getTextBounds(title, 0, title.length(), bounds); float textX = ((float)w-bounds.width())/2.0f; // 버튼상에서 텍스트 시작위치(x) float textY = ((float)h-bounds.height())/2.0f; // 버튼상에서 텍스트 시작위치(y) canvas.drawText(title, textX, textY+bounds.height(), paint); } @Override public boolean onTouchEvent(MotionEvent event) { int action = event.getAction(); switch(action) { case MotionEvent.ACTION_DOWN: paint.setColor(Color.RED); break; case MotionEvent.ACTION_UP: paint.setColor(Color.BLACK); break; } invalidate(); return super.onTouchEvent(event); } }