在Android中,可以使用適配器來動態加載ListView的數據。以下是實現方法的示例代碼:
public class MyAdapter extends BaseAdapter {
private List<String> mData;
private LayoutInflater mInflater;
public MyAdapter(Context context, List<String> data) {
mData = data;
mInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return mData.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 = mInflater.inflate(R.layout.list_item, parent, false);
holder = new ViewHolder();
holder.textView = convertView.findViewById(R.id.text_view);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
String item = mData.get(position);
holder.textView.setText(item);
return convertView;
}
private static class ViewHolder {
TextView textView;
}
}
public class MainActivity extends AppCompatActivity {
private ListView mListView;
private MyAdapter mAdapter;
private List<String> mData = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = findViewById(R.id.list_view);
mAdapter = new MyAdapter(this, mData);
mListView.setAdapter(mAdapter);
// 添加數據到列表
mData.add("Item 1");
mData.add("Item 2");
mData.add("Item 3");
mAdapter.notifyDataSetChanged();
}
}
在上述示例中,我們通過MyAdapter類創建了一個適配器,然后將其設置給ListView。在Activity的onCreate()方法中,我們向數據列表mData中添加了一些數據,并調用適配器的notifyDataSetChanged()方法來通知ListView更新數據。需要注意的是,更新數據后要調用notifyDataSetChanged()方法才能使ListView重新加載數據。