android listview从网络获取图片及文字显示,android studio 实现listview显示简单图片文字显示...
时间: 2023-12-19 17:07:16 浏览: 215
以下是一个简单的实现步骤:
1. 在布局文件中添加ListView组件:
```
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
```
2. 创建一个自定义的适配器(Adapter),用于将数据绑定到ListView上:
```
public class CustomAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> titles;
private ArrayList<String> imageUrls;
public CustomAdapter(Context context, ArrayList<String> titles, ArrayList<String> imageUrls) {
this.context = context;
this.titles = titles;
this.imageUrls = imageUrls;
}
@Override
public int getCount() {
return titles.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = layoutInflater.inflate(R.layout.list_item, parent, false);
TextView titleTextView = row.findViewById(R.id.titleTextView);
ImageView imageView = row.findViewById(R.id.imageView);
titleTextView.setText(titles.get(position));
// 使用Glide库加载网络图片
Glide.with(context).load(imageUrls.get(position)).into(imageView);
return row;
}
}
```
3. 在布局文件中创建每个ListView项的布局(list_item.xml):
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/imageView"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="10dp"
android:background="#f0f0f0"/>
<TextView
android:id="@+id/titleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:textSize="18sp"/>
</LinearLayout>
```
4. 在Activity中获取ListView组件,并将适配器绑定到ListView上:
```
public class MainActivity extends AppCompatActivity {
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
ArrayList<String> titles = new ArrayList<>();
titles.add("Title 1");
titles.add("Title 2");
titles.add("Title 3");
ArrayList<String> imageUrls = new ArrayList<>();
imageUrls.add("https://via.placeholder.com/150");
imageUrls.add("https://via.placeholder.com/150");
imageUrls.add("https://via.placeholder.com/150");
CustomAdapter adapter = new CustomAdapter(this, titles, imageUrls);
listView.setAdapter(adapter);
}
}
```
以上就是一个简单的实现,你可以根据自己的需求进行修改和优化。
阅读全文