Sne*_*eha 7 android android-gridview
我编写了一个代码,我在GridView中显示图像,但现在我想在每个图像的底部显示文本.
我想像这样展示我的网格:

但是这样[也想显示Text for Image]:

main.xml中:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<GridView
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:verticalSpacing="0dp"
android:horizontalSpacing="0dp"
android:stretchMode="columnWidth"
android:numColumns="2"
/>
</FrameLayout>
Run Code Online (Sandbox Code Playgroud)
您需要定义一个自定义网格项布局,其中包含用于分配文本的文本视图.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/thumbnail"
android:padding="8dp"
android:scaleType="cropCenter"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_gravity="bottom"
android:textColor="@android:color/white"
android:background="#55000000" />
</FrameLayout>
Run Code Online (Sandbox Code Playgroud)
在这里,我们创建了一个FrameLayout,它将imageview设置为与父级的尺寸相匹配,这将是显示照片的imageview.接下来,有一个TextView,它将用于显示项目标题,并与FrameLayout的底部对齐.
接下来,我们需要编辑适配器以使用此网格项布局并呈现正确的信息.
public View getView(int position, View convertView, ViewGroup parent) {
// Inflate the single grid item layout
if (convertView == null) {
convertView = mLayoutInflater.inflate(R.layout.grid_item, parent, false);
}
// Set Image
ImageView thumbnail = convertView.findViewById(R.id.thumbnail);
if (thumbnail != null) {
thumbnail.setImageResource(mThumbIds[position]);
}
// Set Text
TextView title = convertView.findViewById(R.id.title);
if (title != null) {
title.setText("Image Number: " + position);
}
return convertView;
}
Run Code Online (Sandbox Code Playgroud)
应使用构造函数全局定义mLayoutInflater
mLayoutInflater = LayoutInflater.from(context);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3256 次 |
| 最近记录: |