2011. 9. 4. 17:29

안드로이드, 이벤트 처리를 onCreate() 바깥으로 빼서 처리하기


package net.br;

import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;

import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class ButtonEventOuterOnCreate extends Activity {
 private ArrayList<CharSequence> arrayList ;
 private ArrayAdapter<CharSequence> arrayAdapter ;
 private ListView listView ; 
 private EditText editText ;
 private Button btnAdd, btnDelete ; 

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
        arrayList = new ArrayList<CharSequence>() ;       
        arrayList.add("First");
        arrayList.add("Second");
        arrayList.add("Third");             
        arrayAdapter = new ArrayAdapter<CharSequence>(this,                                                                     
                                                                       android.R.layout.simple_list_item_1, arrayList); 
listView = (ListView)findViewById(R.id.listView) ;
        listView.setAdapter(arrayAdapter);
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);         
        this.findViewById(R.id.btnAdd).setOnClickListener(btnSelect) ;
        this.findViewById(R.id.btnDelete).setOnClickListener(btnSelect) ;                
        listView.setOnItemClickListener(itemClickListener);
    } //onCreate    
    private AdapterView.OnItemClickListener itemClickListener = 
                                                                                new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int index, long id) {
            String msg;
            msg = "Select Item = " + arrayList.get(index);
            Toast.makeText(ButtonEventOuterOnCreate.this, msg, Toast.LENGTH_SHORT).show();
        }
    };    
  // 버튼 이벤트 처리를 onCreate 바깥쪽으로 빼서 처리하는 방식
  private View.OnClickListener btnSelect = new View.OnClickListener() {
  @Override
  public void onClick(View v) {
   // TODO Auto-generated method stub
  switch(v.getId() ) {
   case R.id.btnAdd :
    EditText editText = (EditText)findViewById(R.id.editText);
    String text = editText.getText().toString();    
   
if(text.length() != 0) {
     arrayList.add(text);
     editText.setText("");
     arrayAdapter.notifyDataSetChanged();
    }  
    break ;    
   case R.id.btnDelete :
    int id;
    id = listView.getCheckedItemPosition();    
    if(id != ListView.INVALID_POSITION) {
     arrayList.remove(id);
     listView.clearChoices();
     arrayAdapter.notifyDataSetChanged();
    }    
    break;
   }
  }
 } ;
}