[Android] Custom Widget-2 Android 2012. 1. 26. 15:01

다음은 에디트 + 텍스트 뷰 포함하는 라이너 위젯이다.

예제 코드를 실행 해 보면 입력 문자의 수를 파악 할 수 있다.

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">
   
    <imageview.test.Edit_Widget
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
    />
</LinearLayout>

Java Code

package imageview.test;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.*;
import android.util.*;
import android.widget.*;

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

class Edit_Widget extends LinearLayout implements TextWatcher{
 EditText m_edit;
 TextView m_text;
 
 public Edit_Widget(Context context){
  super(context);
  init();
 }
 
 public Edit_Widget(Context context, AttributeSet att){
  super(context, att);
  init();
 }
  
 private void init(){
  setOrientation(LinearLayout.VERTICAL);
  m_edit = new EditText(getContext());
  m_text = new TextView(getContext());
  m_text.setText("Now Length : 0");
  LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
  addView(m_edit, param);
  addView(m_text, param);
  m_edit.addTextChangedListener(this);
 }

 public void afterTextChanged(Editable arg0) {
 }

 public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) {
 }

 public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
  m_text.setText("Now Length : " + arg0.length());
 }
}
여기에선 잘 살펴보면 TextWatcher를 이용하여 확장 개념으로 적용 한 것이다.

또한 텍스트 위젯들을 XML에 적용해서 하지 않고 바로 코드에 쓴 케이스로 XML에 적용할 경우 findViewById를 이용하여 각기 할당하여 사용하면 된다.