【发布时间】:2023-03-07 07:26:02
【问题描述】:
我是一个新的安卓开发者。我创建了一个测验应用程序,我需要在列表视图中连续显示问题。我所有的问题和选项都是图像。如何在列表视图中设置图像。我只想在列表视图中设置图像而不是任何文本。请帮帮我。
【问题讨论】:
我是一个新的安卓开发者。我创建了一个测验应用程序,我需要在列表视图中连续显示问题。我所有的问题和选项都是图像。如何在列表视图中设置图像。我只想在列表视图中设置图像而不是任何文本。请帮帮我。
【问题讨论】:
在你的主 xml 文件中创建一个列表视图,如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/masterLayout"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ListView
android:id="@+id/list"
android:cacheColorHint="#00000000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
然后创建另一个名为 child_layout 的 xml 文件:
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
然后在您的活动类中初始化您的列表视图:
ListView listView1 = (ListView)findViewById(R.id.list);
创建一个扩展 baseadapter 的类,并以您需要的方式修改所有必要的方法(创建将可绘制对象列表作为参数的构造函数,并创建一个设置为提供的列表的全局变量)。然后在您的活动课程中执行以下操作:
ArrayList<Drawable> images = new ArrayList<Drawable>();
// add to the list here
CustomListAdapter adapter = new CustomListAdapter(images);
listView1.setAdapter(adapter);
在 customlistadapter 类的 getView() 函数中执行此操作:
public View getView(int position, View convertView, ViewGroup parent)
{
Drawable image = images.get(position);
if (convertView == null)
{
LayoutInflater infalInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.child_layout, null);
}
ImageView imageView = (ImageView)convertView.findViewById(R.id.image);
imageView.setBackgroundDrawable(image);
return convertView;
}
ListView 项目点击监听:
listView1.setOnItemClickListener(new ListView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> listView, View itemView, int position, long itemId)
{
String message = "example text: " + position;
Toast.makeText(MyActivity.this, message, Toast.LENGTH_SHORT).show();
}
});
【讨论】:
您需要创建一个自定义 ListAdapter。 API samples 中给出了一个示例。只需添加一个 ImageView 作为自定义适配器的布局,您就可以开始了。搜索更多示例。
【讨论】:
获取一个主布局 xml 文件,您必须在其中提供 . 像这样的
<List
android:width="wrap_content"
android:height="wrap_content"
android:id="@+id/list"
/>
并使用
获取另一个布局 xml 文件<ImageView
android:width="wrap_content"
android:height="wrap_content"/>
在适配器中膨胀这个包含 ImageView 的 xml 文件。这样您就可以在列表中获取图像
【讨论】:
look at this tutorial... 并用图像视图替换 textview 并为其设置图像。
also have a look at this question...
希望这会有所帮助。
谢谢。
【讨论】: