在Android的DataGrid中显示图片,您可以使用如RecyclerView或GridView等列表控件
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="8dp">
<ImageView
android:id="@+id/imageView"
android:layout_width="48dp"
android:layout_height="48dp"
android:src="@drawable/ic_launcher_background" />
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingLeft="8dp"
android:text="Item Text" />
</LinearLayout>
public class DataModel {
private int imageResourceId;
private String text;
public DataModel(int imageResourceId, String text) {
this.imageResourceId = imageResourceId;
this.text = text;
}
public int getImageResourceId() {
return imageResourceId;
}
public String getText() {
return text;
}
}
public class CustomAdapter extends ArrayAdapter<DataModel> {
private Context context;
private List<DataModel> dataList;
public CustomAdapter(@NonNull Context context, @NonNull List<DataModel> objects) {
super(context, R.layout.list_item, objects);
this.context = context;
this.dataList = objects;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_item, parent, false);
ImageView imageView = rowView.findViewById(R.id.imageView);
TextView textView = rowView.findViewById(R.id.textView);
DataModel dataModel = dataList.get(position);
imageView.setImageResource(dataModel.getImageResourceId());
textView.setText(dataModel.getText());
return rowView;
}
}
public class MainActivity extends AppCompatActivity {
private ListView listView;
private CustomAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
List<DataModel> dataList = new ArrayList<>();
dataList.add(new DataModel(R.drawable.ic_launcher_background, "Item 1"));
dataList.add(new DataModel(R.drawable.ic_launcher_background, "Item 2"));
dataList.add(new DataModel(R.drawable.ic_launcher_background, "Item 3"));
adapter = new CustomAdapter(this, dataList);
listView.setAdapter(adapter);
}
}
这样,您就可以在Android DataGrid(例如ListView或GridView)中显示带有图片的数据了。请根据实际需求调整代码。