カスタムアダプターを使用して、Android でボタンをすべてのリスト値に動的に設定します
Main.Xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView android:layout_height="wrap_content"
android:layout_below="@+id/EditText01"
android:layout_width="wrap_content"
android:id="@+id/ListView01">
</ListView>
</RelativeLayout>
listview.xml //ListView にボタンとテキストを動的に追加するためのカスタム レイアウト
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:gravity="left|center"
android:layout_width="fill_parent"
android:paddingBottom="5px"
android:background="#fff200"
android:paddingTop="5px"
android:paddingLeft="5px">
<Button android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ImageView>
<TextView android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20px"
android:textStyle="bold"
android:layout_marginLeft="10px"
android:textColor="#0099CC">
</TextView>
</LinearLayout>
MainActivity.java
public class CustomListViewSearchOnButtonClick extends Activity
{
EditText edittext;
ListView listview;
Button search;
String[] text = { "One", "Two", "Three", "Four", "Five", "Six", "Seven",
"Eight", "Nine", "Ten" };
int textlength = 0;
ArrayList<String> text_sort = new ArrayList<String>();
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listview = (ListView) findViewById(R.id.ListView01);
listview.setAdapter(new MyCustomAdapter(text, image));
listview.setAdapter(new MyCustomAdapter(text_sort));
}
});
}
MyCustomAdapter.java
class MyCustomAdapter extends BaseAdapter
{
String[] data_text;
MyCustomAdapter()
{
}
MyCustomAdapter(String[] text)
{
data_text = text;
}
MyCustomAdapter(ArrayList<String>text,
ArrayList<Integer>image)
{
data_text = new String[text.size()];
for (int i = 0; i < text.size(); i++) {
data_text[i] = text.get(i);
}
}
public int getCount()
{
return data_text.length;
}
public String getItem(int position)
{
return null;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = getLayoutInflater();
View row;
row = inflater.inflate(R.layout.listview, parent, false);
TextView textview = (TextView) row.findViewById(R.id.TextView01);
Button button= (ImageView) row
.findViewById(R.id.Button01);
textview.setText(data_text[position]);
imageview.setImageResource(data_image[position]);
return (row);
}
}
}