Androidでよく使ってるListViewにButtonを追加する方法。
まず、TextViewとButtonを持つ行レイアウトを作る。
<?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>
次は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;
}
}
}
これで完了。