在Android中,在ListView中添加按鈕可以使用自定義的Adapter來實現。以下是一個簡單的示例:
public class CustomAdapter extends BaseAdapter {
private Context context;
private List<String> data;
public CustomAdapter(Context context, List<String> data) {
this.context = context;
this.data = data;
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
holder = new ViewHolder();
holder.text = convertView.findViewById(R.id.text);
holder.button = convertView.findViewById(R.id.button);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(data.get(position));
holder.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 按鈕點擊事件
}
});
return convertView;
}
private static class ViewHolder {
TextView text;
Button button;
}
}
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:padding="12dp" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按鈕" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
private ListView listView;
private CustomAdapter adapter;
private List<String> data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
data = new ArrayList<>();
data.add("項1");
data.add("項2");
data.add("項3");
adapter = new CustomAdapter(this, data);
listView.setAdapter(adapter);
}
}
這樣,每個列表項就會顯示一個文本和一個按鈕。你還可以在按鈕的點擊事件中進行相應的操作。