阅读量:2
在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; } }
- 在Activity中使用ListView和适配器:
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重新加载数据。