首先,我们需要在Fragment中定义ListView和按钮。
接着,创建一个BaseAdapter类并重写其中的getView()方法。
在getView()方法中定义并设置list_item.xml文件中的视图元素,并在按钮的onClick()方法中更新ListView中的数据。
最后,将BaseAdapter设置为ListView的适配器,并在Fragment中实现按钮的点击事件。
下面是示例代码:
在Fragment中定义ListView和按钮:
public class MyFragment extends Fragment {
private ListView mListView;
private Button mButton;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my, container, false);
mListView = (ListView) view.findViewById(R.id.list_view);
mButton = (Button) view.findViewById(R.id.button);
// 给按钮添加点击事件监听器
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 更新ListView的数据
mAdapter.notifyDataSetChanged();
}
});
return view;
}
}
创建一个BaseAdapter类并重写其中的getView()方法:
public class MyAdapter extends BaseAdapter {
private List mDataList;
private LayoutInflater mInflater;
public MyAdapter(Context context, List dataList) {
mDataList = dataList;
mInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return mDataList.size();
}
@Override
public MyData getItem(int position) {
return mDataList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.textView = (TextView) convertView.findViewById(R.id.text_view);
holder.button = (Button) convertView.findViewById(R.id.button);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
MyData data = mDataList.get(position);
holder.textView.setText(data.getText());
holder.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 更新数据
mDataList.get(position).setText("new text");
// 通知ListView更新UI
notifyDataSetChanged();
}
});
return convertView;
}
static class ViewHolder {
TextView textView;
Button button