Android 입문자를 위한 Tutorial - 6. 커스텀 위젯

Mobile Programming/Android 2010. 11. 9. 14:46

위젯을 사용자가 정의하고 이를 사용한다.

package geng.mm.jnu;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;



public class ch9 extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

class Editlength extends LinearLayout implements TextWatcher{
	
	EditText mEdit;
	TextView mText;
	
	public Editlength(Context context) {
  	  
		super(context);
		init();
	}
	public Editlength(Context context,AttributeSet attrs) {
	  	  
		super(context,attrs);
		init();
	}
			
	void init() {
  	
		setOrientation(LinearLayout.VERTICAL);
		mEdit = new EditText(getContext());
		mText = new TextView(getContext());
		mText.setText("Now Length : 0 Char");
		
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		
		addView(mEdit,params);
		addView(mText,params);
		mEdit.addTextChangedListener(this);
	}
	
	@Override
	public void afterTextChanged(Editable arg0) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub
		mText.setText("Now Length : " + s.length() + "Characters");
	}
}

class EditEcho extends LinearLayout implements TextWatcher{

	EditText mEdit;
	TextView mText;
	
	public EditEcho(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		init();
	}
	
	public EditEcho(Context context,AttributeSet attrs) {
	  	  
		super(context,attrs);
		init();
	}

	void init() {
	  	
		setOrientation(LinearLayout.VERTICAL);
		mEdit = new EditText(getContext());
		mText = new TextView(getContext());
		mText.setText("Now Length : 0 Char");
		
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		
		addView(mEdit,params);
		addView(mText,params);
		mEdit.addTextChangedListener(this);
	}

	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub
		mText.setText("Now Length : " + s + "Characters");
	}
	
}

 

외부 클래스로 만들고자 하는 위젯을 만들어야 한다.
본 예제에서의 위젯은 리니어 레이아웃을 기반으로한 텍스트뷰 위젯이므로 먼저 linearlayout을 상속하고, 위젯이 사용해야하는 두 생성자를 사용, 그리고 초기화 함수를 호출하여 위젯을 구성한다.
 두 리니어 레이아웃 모두 텍스트 에디트 + 텍스트뷰이기 때문에 init함수에서 에디트와 텍스트뷰를 add하고 있다.
Text뷰의 변화 감지를위해 addTextChangedLister를 호출하고,
역시 implements 되어있기 때문에 현재 클래스에서 찾을 수 있도록 (this)를 넘겨주었다.
 

Android 입문자를 위한 Tutorial - 5. ArrayList

Mobile Programming/Android 2010. 11. 4. 14:14

arrayList를 확장하여 이용하는 뷰가 참 많이 있다.

먼저 가장 많이 사용하는 "리스트뷰", 말 그대로 여러정보를 리스트를 뿌려주듯이 뿌려줄 수 있다.

adapter를 이용하기 위해서 먼저 ArrayList를 만들고 ,

ArrayList Items;
ArrayAdapter Adapter;
ListView list;

	Items = new ArrayList();
	Items.add("First");
	Items.add("Second");
	Items.add("Third");



Array Adapter를 만들어줘야한다.
Adapter = new ArrayAdapter(this, android.R.layout.
				simple_list_item_multiple_choice, Items);

그 뒤에 listview에 연결시켜주면 된다.
list.setAdapter(Adapter);
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
.


다음으로 스피너는
팝업창을 통해서 리스트 뷰를 띄워주는 형태라고 생각하면 될 것 같다.

다음은 스피너를 이용하는 소스이다.
package geng.mm.jnu;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.RatingBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class fruitrating extends Activity {
    /** Called when the activity is first created. */
		ArrayAdapter adspin;
		RatingBar mRating;
		TextView mRateText;
		String fruit;
		float rate;
		//채워넣을 곳//
		public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fruitrating);

		mRating = (RatingBar)findViewById(R.id.ratingbar);
		mRateText = (TextView)findViewById(R.id.ratetext);

		Spinner spin = (Spinner)findViewById(R.id.myspinner);
		spin.setPrompt("과일을 고르세요.");

		adspin = ArrayAdapter.createFromResource(this, R.array.fruits, 
		android.R.layout.simple_spinner_item);
		adspin.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spin.setAdapter(adspin);

		spin.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView parent, View view, int position, long id) {
				//채워넣을 곳//
				fruit = (String) adspin.getItem(position);
			}
			public void onNothingSelected(AdapterView parent) {
			}
		});

		mRating.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
			public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
				mRateText.setText("Now Rate : " + rating);
				rate = rating;
				//채워넣을 곳//
				String tmp ;
				if(rate<1){
					tmp = "나빠";
				}else if(rate < 2.5)
					tmp = "괜찮아";
				else if(rate<3.9)
					tmp = "좋아!";
				else 
					tmp = "완전좋아~!!";
				Toast.makeText(fruitrating.this, fruit + "는 "+  tmp , Toast.LENGTH_SHORT).show();

			}
		});
	}
}
;

<string-array name="fruits">
<item>사과</item>
<item>감</item>
</string-array>
와 같이 xml에 넣어주었다.

rating chanaged 메서드와 , itemselected 메서드로 변화를 감지해서 클릭된 스피너의 아이템을 알아내고 그에 따라 토스트를 출력한다.


Android 입문자를 위한 Tutorial - 4. 라디오 버튼

Mobile Programming/Android 2010. 10. 21. 14:51


<RadioGroup>
          <RadioButton>
           />
          <RadioButton>
          />
</RadioGroup>


class안이어도 메서드 밖에서는 findViewById등의 메서드의 사용이 불가함 !

만약 하단 소스에서 nameG와 imageG를 선언과동시에 FindViewById()를 호출한다면 프로그램이 맥없이 뻗는다..

아래 예제는 명화들을 출력하는 ImageView imageG 를 라디오버튼을 이용해 조작하는 간단한 프로그램.


라디오버튼  레이아웃 입력 형태를 숙지하고 확인하도록 하자.

자바 소스는 단순히 OnCheckedChanged를 오버라이드, 아이디 별로 해당 작업을 수행하기만 한다.

package geng.mm.jnu;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

public class radio extends Activity implements RadioGroup.OnCheckedChangeListener {
 
	 TextView nameG;
	 ImageView imageG;
	 Drawable a1,a2,a3,a4,a5;

	 public void onCreate(Bundle savedInstanceState) {
		  super.onCreate(savedInstanceState);
		  setContentView(R.layout.formss);
		 
		  nameG = (TextView)findViewById(R.id.grimname);
		  imageG = (ImageView)findViewById(R.id.grimpan);
		 
		  RadioGroup ColGroup = (RadioGroup)findViewById(R.id.grimgroup);
		  ColGroup.setOnCheckedChangeListener(this);
		 
		  nameG = (TextView)findViewById(R.id.grimname);
		  imageG = (ImageView)findViewById(R.id.grimpan);
		 
		  a1 = this.getResources().getDrawable(R.drawable.cgrim1);
		  a2 = this.getResources().getDrawable(R.drawable.cgrim2);
		  a3 = this.getResources().getDrawable(R.drawable.cgrim3);
		  a4 = this.getResources().getDrawable(R.drawable.cgrim4);
		  a5 = this.getResources().getDrawable(R.drawable.cgrim5);

	 }
	 @Override
	 public void onCheckedChanged(RadioGroup group, int checkedId) {
	  // TODO Auto-generated method stub
	  
	  switch(checkedId){
	  case R.id.grim11:
	   imageG.setImageDrawable(a1);
	   nameG.setText("모나리자");
	   break;
	  
	  case R.id.grim22:
	   imageG.setImageDrawable(a2);
	   nameG.setText("이삭줍는여인들");
	   break;
	   
	  case R.id.grim33:
	   imageG.setImageDrawable(a3);
	   nameG.setText("절규");
	   break;
	  
	  case R.id.grim44:
	   imageG.setImageDrawable(a4);
	   nameG.setText("아담의창조");
	   break;
	  case R.id.grim55:
	   imageG.setImageDrawable(a5);
	   nameG.setText("별이빛나는밤에");
	   break;
	  }
	  
	 }
 
}