[Android] Custom Widget-1 Android 2012. 1. 26. 13:40

커스텀 위젯은 기존 위젯 클래스를 상속받아 기능을 확장, 수정하는 것을 말한다. 단, ViewGroup Or 파생 클래스 확장하여 내부 위젯 작용까지도 처리를 해야한다.

간단한 예를 보면 다음과 같다. 문자를 입력하면 사운드가 나온다.

물론 사전작업으로 raw에 mp3 파일을 등록한 후 작업한다.

XML Code

<?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="input text"
    />
    <imageview.test.SoundEditWidget
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="12pt"
    />
</LinearLayout>

imageview.test.SoundEditWidget 이 부분을 보면 Package 명이 섞여 있다!! 필자가 공부하는 책엔 이게 뭔지 명시가 되어 있지 않아 개인적으로 만든 Package 이용시 굉장히 헛갈렸다.

Java Code

package imageview.test;

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.util.AttributeSet;
import android.widget.EditText;

 

public class ImageViewActivity extends Activity{
 public void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
 }
}

class SoundEditWidget extends EditText{
 SoundPool m_pool = null;
 int m_click;
 public SoundEditWidget(Context context){
  super(context);
  init(context);
 }
 
 public SoundEditWidget(Context context, AttributeSet att){
  super(context, att);
  init(context);
 }
 
 public SoundEditWidget(Context context, AttributeSet att, int defStyle){
  super(context, att, defStyle); 
  init(context);
 }
 
 private void init(Context context){
  m_pool = new SoundPool(1,AudioManager.STREAM_MUSIC,0);
  m_click = m_pool.load(context, R.raw.aid, 1);
 }
 
 protected void onTextChanged(CharSequence text, int start, int before, int after){
  if(m_pool != null){
   m_pool.play(m_click, 1,1,0,0,1);
  }
 }
}
이 코드들을 작성하다가 팁 하나!! 이클립스를 사용하는 분들은 알겠지만 Ctrl + Shift + O 를 누르면 import 대상들이 자동 import 된다.