2010年1月22日金曜日

[Android] ListView에 Button 추가

Android에서 빈번하게 사용하는 ListViewButton을 추가하는 방법.


우선, TextViewButton을 가지고 있는 레이아웃(리스트의 한행)을 작성한다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content">
<TextView android:id="@+id/list_with_button_text"
android:layout_height="48dp" android:layout_width="fill_parent"
android:layout_marginRight="80dp"></TextView>
<Button android:id="@+id/list_with_button_button"
android:layout_alignParentRight="true" android:layout_height="48dp"
android:layout_width="80dp"></Button>
</RelativeLayout>

다음은 BaseAdapter를 상속받아서 Adapter를 작성한다.

package com.babukuma.android.test;

import static com.babukuma.android.test.Main.LOG_TAG;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

public class ListViewWithButton extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setListAdapter(new ListAdapterWithButton<String>(this, getResources()
.getStringArray(R.array.list_test_menus)));
}

class ListAdapterWithButton<T> extends BaseAdapter {
private final LayoutInflater mInflater;
private final T[] array;

public ListAdapterWithButton(final Context context, final T[] array) {
this.mInflater = LayoutInflater.from(context);
this.array = array;
}

@Override
public int getCount() {
return array.length;
}

@Override
public T getItem(int position) {
return array[position];
}

@Override
public long getItemId(int position) {
return position;
}

class ViewHolder {
TextView label;
Button button;
}

@Override
public View getView(final int position, View convertView,
ViewGroup parent) {
ViewHolder holder;

if (convertView == null) {
convertView = mInflater
.inflate(R.layout.list_with_button, null);

// Creates a ViewHolder and store references to the two children
// views
// we want to bind data to.
holder = new ViewHolder();
holder.label = (TextView) convertView
.findViewById(R.id.list_with_button_text);
holder.label.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d(LOG_TAG, "label click position=" + position);
}
});
holder.button = (Button) convertView
.findViewById(R.id.list_with_button_button);
holder.button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
Log.d(LOG_TAG, "button click position=" + position);
}
});

holder.label.setText(array[position].toString());
holder.button.setText(array[position].toString());

convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}

return convertView;
}

}
}


완성. 선택됐을 경우에 배경색을 바꾸는 건 필요하다면 수동으로 추가해야 할 듯.