레이블이 안드로이드인 게시물을 표시합니다. 모든 게시물 표시
레이블이 안드로이드인 게시물을 표시합니다. 모든 게시물 표시

2010년 2월 23일 화요일

[android] ListView와 RatingBar 사용하기.

#. ViewWrapper 클래스
package my.app.RateListExample;

public class ViewWrapper {
View base;
RatingBar rate = null;
TextView label = null;

public ViewWrapper(View base) {
this.base = base;
}

RatingBar getRatingBar() {
if (rate == null) {
rate = (RatingBar) base.findViewById(R.id.rate);
}

return rate;
}

public TextView getLabel() {
if (label == null) {
label = (TextView) base.findViewById(R.id.label);
}

return label;
}

}




#. RateList 클래스
package my.app.RateListExample;

public class RateList extends ListActivity {

TextView selection;
String[] items={"lorem", "ipsum", "dolor", "sit", "amet", "consectetuer", "adipiscing", "elit", "morbi", "vel",
"ligula", "vitae", "arcu", "aliquet", "mollis", "etiam", "vel", "erat", "placerat", "ante",
"porttitor", "sodales", "pellentesque", "augue", "purus"};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

ArrayList<RowModel> list = new ArrayList<RowModel>();

for (String s : items) {
list.add(new RowModel(s));
}

setListAdapter(new CheckAdapter(this, list));
}

private RowModel getModel(int position) { // 레이블로 사용할 텍스트와 함께 별점 상태를 보관
return(((CheckAdapter)getListAdapter()).getItem(position));
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
selection.setText(getModel(position).toString());
}

class CheckAdapter extends ArrayAdapter<RowModel> {
Activity context;

public CheckAdapter(Activity context, ArrayList<RowModel> list) {
super(context, R.layout.raterow, list);
this.context = context;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
View raterow = convertView;
ViewWrapper wrapper = null;
RatingBar rate = null;

if (raterow == null) {
// 레이아웃 파일을 사용해 새로운 행 생성
LayoutInflater inflater = context.getLayoutInflater();
raterow = inflater.inflate(R.layout.raterow, null);

// 생성된 View 인스턴스에 ViewWrapper 인스턴스 생성
wrapper = new ViewWrapper(raterow);
raterow.setTag(wrapper);
rate = wrapper.getRatingBar(); // 행마다 들어있는 RatingBar

/*
* 선택된 값을 Intager 형태로 변환하는 메소드
* 변환된 값은 ArrayAdapter 내에서 해당하는 행이 어디에 위치하는지를 가르키는
         *  번호다.
* 행번호를 찾고나면 해당하는 행과 연동된 RowModel을 찾아온다.
* RatingBar에서 새로 선택된 값은 RowModel 인스턴스에 직접 설정한다.
*/
RatingBar.OnRatingBarChangeListener l =
new OnRatingBarChangeListener() {

@Override
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);

model.rating = rating;

LinearLayout parent = (LinearLayout) ratingBar.getParent();
TextView label = (TextView) parent.findViewById(R.id.label);
label.setText(model.toString());

}
};
} else {
wrapper = (ViewWrapper) raterow.getTag();
rate = wrapper.getRatingBar();
}

RowModel model = getModel(position);
wrapper.getLabel().setText(model.toString());
rate.setTag(new Integer(position));
rate.setRating(model.rating);

return raterow;
}
}

class RowModel {
String label;
float rating=2.0f;

RowModel(String label) {
this.label=label;
}

public String toString() {
if (rating>=3.0) {
return(label.toUpperCase());
}

return(label);
}
}
}




[android] ListView 홀더패턴..

#. ViewWrapper 클래스
package my.app.ViewWrapper;

class ViewWraper {
/*
* 모든 View 객체는 setTag()와 getTag()를 가지고 있다.
* 객체마다 원하는 데이터를 넣어 둘 수 있도록 준비된 메소드.
* 홀더패턴은 View에 홀더 객체를 태그로 설정해두고,
* 해당하는 행을 사용할때는 필요한 내부 객체에 대한 참조를 갖고 있기 때문에
* findViewById 메소드를 매번 호출할 필요가 없다.
*
*  이 클래스는 내부 위젯에 대한 참조를 보관 / 값을 채워넣는 레이지로딩 방법도 적용하고있음.
*  Wrapper 인스턴스를 생성했어도 실제로 호출하지 않으면 findViewById()는 호출되지 않으므로
*   => 결과적으로 CPU를 최대한 효율적으로 사용가능하다.
*/

View base;
TextView label = null;
ImageView icon = null;

ViewWraper(View base) {
this.base = base;
}

TextView getLabel() {
if (label == null) {
label = (TextView) base.findViewById(R.id.label);
}
return (label);
}

ImageView getIcon() {
if (icon == null) {
icon = (ImageView) base.findViewById(R.id.icon);
}
return (icon);
}
}




#. ViewWrapperExample
package my.app.ViewWrapper;

public class ViewWrapperExample extends ListActivity {

TextView selection;
String[] items={"lorem", "ipsum", "dolor", "sit", "amet", "consectetuer", "adipiscing", "elit", "morbi", "vel",
"ligula", "vitae", "arcu", "aliquet", "mollis", "etiam", "vel", "erat", "placerat", "ante",
"porttitor", "sodales", "pellentesque", "augue", "purus"};

@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
setListAdapter(new IconicAdapter(this));
selection = (TextView) findViewById(R.id.selection);
}

private String getModel(int position) {
return (((IconicAdapter)getListAdapter()).getItem(position));
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
selection.setText(getModel(position));
}

class IconicAdapter extends ArrayAdapter<String> {

Activity context;

public IconicAdapter(Activity context) {
super(context, R.layout.row, items);
this.context = context;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

View row = convertView;
ViewWraper wrapper = null;

// 필요한 경우에만 행별 위젯생성
if ( row == null ) {
LayoutInflater inflater = context.getLayoutInflater();
row = inflater.inflate(R.layout.row, null);
wrapper = new ViewWraper(row);
// 홀더패턴 설정
row.setTag(wrapper);
} else {
wrapper = (ViewWraper) row.getTag();
}

wrapper.getLabel().setText(getModel(position));

if (getModel(position).length() > 4) {
wrapper.getIcon().setImageResource(R.drawable.delete);
} else {
wrapper.getIcon().setImageResource(R.drawable.ok);
}

return (row);
}

}
}





2010년 2월 18일 목요일

[android] Intent, Multi Activity 예제 및 설명

Intent는 Message Object로 실행할때 오퍼레이션을 가지고있는 오브젝트이다.
액티비티 간의 연결고리 역할을 함.

#. 첫번째 Activity
public class ActivityTest extends Activity {
    protected static final int GET_CODE = 0;
/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
     /* AndroidManifest.xml의 application에서 액티비티를 추가한후 intent 필터 설정해준다
      *      <intent-filter>
      *          <action android:name="android.intent.action.MAIN" />
      *          <category android:name="android.intent.category.LAUNCHER" />
      *      </intent-filter>
      * 자세한 설명은 http://www.androidside.com/B46/137 참조.. */
     setContentView(R.layout.actvity1);  
     Button button =(Button)findViewById(R.id.startButton);
       button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
             EditText edit1 =(EditText)findViewById(R.id.text1);
             EditText edit2 =(EditText)findViewById(R.id.text2);
                
// intent(넘겨줄 activity, 받을 activity)
// intent 객체만 생성해주는 것일뿐 동작은 startActivity(Intent intent)로 동작..
                Intent intent = new Intent(ActivityTest.this, ActivityTest1.class);
/* 받을 Activity에서 TEXT1이라는 변수명으로 사용
* putExtra(name, value) ==>(data set 할 때)
                 *   get<Type>Extra(name)==>(data get할 때) ex)getStringExtra */
                intent.putExtra("TEXT1", edit1.getText().toString());
                intent.putExtra("TEXT2", edit2.getText().toString());
          
       // activity가 끝날때 결과물을 받음 인자는 (intent, 호출구분코드)
// 아래 onActivityResult와 쌍으로 동작한다..
                startActivityForResult(intent, GET_CODE);
            }
        });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// 설명하자면 현재 activity에서 textview를 가져온후 호출구분코드가 조건에 맞고
// 다른 activity에서 넘겨준 호출구분코드가 조건에 맞으면 현재 액티비티에 버튼이 입력된값 출력함..
TextView view =(TextView)findViewById(R.id.text);
    if (requestCode == GET_CODE) {  
        if (resultCode == RESULT_OK)
     view.setText(data.getAction());
    }
 }
}



#. 두번째 액티비티
public class ActivityTest1 extends Activity {
    @Override
protected void onCreate(Bundle savedInstanceState)
    {
         super.onCreate(savedInstanceState);
        setContentView(R.layout.activity2);
    
        Button button = (Button)findViewById(R.id.button1);
        Intent intent = getIntent();
        String t1 = intent.getStringExtra("TEXT1"); // 액티비티1의 TEXT1로 지정한 내용 가져옴
        String t2 = intent.getStringExtra("TEXT2");
        
        button.setText(t1);
        button.setOnClickListener(mCorkyListener);
        button = (Button)findViewById(R.id.button2);
        button.setText(t2);
        button.setOnClickListener(mVioletListener);
       }

    private OnClickListener mCorkyListener = new OnClickListener()
    {
        public void onClick(View v)
        {
         Button button1 = (Button)findViewById(R.id.button1);
            // To send a result, simply call setResult() before your
            // activity is finished.
           // RESULT_OK 라는 호출구분코드로 넘겨줘서 구분한다.
            setResult(RESULT_OK, (new Intent()).setAction(button1.getText().toString()));
            finish();
        }
    };

    private OnClickListener mVioletListener = new OnClickListener()
    {
        public void onClick(View v)
        {
            // To send a result, simply call setResult() before your
            // activity is finished.
       Button button2 = (Button)findViewById(R.id.button1);
            setResult(RESULT_OK, (new Intent()).setAction(button2.getText().toString()));
            finish();
        }
    };
}


#. layoutl.xml 파일

-. 첫번재 액티비티 layout xml (Activity1.xml)
<?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"
    >
    <EditText
        android:id="@+id/text1"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:layout_marginLeft="20dip"
        android:layout_marginRight="20dip"
        android:scrollHorizontally="true"
        android:autoText="false"
        android:capitalize="none"
        android:gravity="fill_horizontal"
         />
    <EditText
        android:id="@+id/text2"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:layout_marginLeft="20dip"
        android:layout_marginRight="20dip"
        android:scrollHorizontally="true"
        android:autoText="false"
        android:capitalize="none"
        android:gravity="fill_horizontal"
        />
   <TextView  
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/text"
    />
  <Button
        android:id="@+id/startButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="start Activity" />
</LinearLayout>


-. 두번재 액티비티 layout xml (Activity2.xml)
<?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" > <Button android:id="@+id/button1" android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_marginLeft="20dip" android:layout_marginRight="20dip" android:scrollHorizontally="true" android:autoText="false" android:capitalize="none" android:gravity="fill_horizontal" /> <Button android:id="@+id/button2" android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_marginLeft="20dip" android:layout_marginRight="20dip" android:scrollHorizontally="true" android:autoText="false" android:capitalize="none" android:gravity="fill_horizontal" /> </LinearLayout> 



참조 : http://www.androidside.com/B46/66
문제시 포스팅 삭제할께요~

2010년 2월 16일 화요일

[android] Spinner 예제

#. 스핀컨트롤
  GUI 툴킷으로 제공하는 드롭다운 선택기능.
  ListView와 비슷하지만 화면 전체를 차지하지않고 원하는 선택 기능 충분히 사용
  but 화면을 한번더 터치해야함...


# main.xml
<?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:id ="@+id/selection"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />

<Spinner
android:id ="@+id/spinner"
android:layout_width="fill_parent"
    android:layout_height="wrap_content"
/>
</LinearLayout>



#. 소스코드
package android.SpinnerExample;

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

public class SpinnerExample extends Activity implements OnItemSelectedListener{

TextView selection;
String[] items = {"lorem", "ipsum", "wallet", "pen", "cellPhone", "key", "gum", "mp3", "face", "clock"};

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        selection = (TextView)findViewById(R.id.selection);

        Spinner spin = (Spinner)findViewById(R.id.spinner);
        spin.setOnItemSelectedListener(this); // 액티비티 스스로를 선택 변경 이벤트에 대한 리스너로 등록

        ArrayAdapter<String> aa =
         new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);

        // 드롭다운 화면에 표시
        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spin.setAdapter(aa);
    }


    @Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
selection.setText(items[arg2]);
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
selection.setText("");
}
}

[android] ListView(ArrayAdapter) 예제

화면에 리스트뷰 표현하는 예제임.
Layout에서 ListView의 아이디를 아래처럼 지정해주면 ListActivity에서 해당하는 리스트 박스를 찾아
기본리스트로 사용한다.

ArrayAdapter를 사용했따(젤 사용하기 간단..)
인자로는 아래 3개를 넘겨준다.
 -. context인스턴스(Activity)
 -. 사용할 뷰의 리소스ID
 -. 화면에 표시할 실제 내용이 들어있는 배열


# main.xml

<?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:id = "@+id/selection"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   />
<ListView
android:id = "@android:id/list"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:drawSelectorOnTop = "false"
/>
</LinearLayout>




#. 소스코드
package android.ListViewExample;

import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class ListViewExample extends ListActivity {

TextView selection;
String[] items = {"lorem", "ipsum", "wallet", "pen", "cellPhone", "key", "gum", "mp3", "face", "clock"};

/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items));
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
     // TODO Auto-generated method stub
     //super.onListItemClick(l, v, position, id);
     selection.setText(items[position]);
    }
}