Android中GridView项的边框

3

我在GridView中展示了图片和文字,每个项目包含一张图片和一段文字。目前运行良好。但我想知道如何在安卓中单独设置每个GridView项目的边框。

2个回答

7

1)在res>value文件夹下创建attrs.xml。

2)添加资源:

<declare-styleable name="Gallery1">
        <attr name="android:galleryItemBackground" />
 </declare-styleable>

3) 在您的活动中添加以下代码:

TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
int mGalleryItemBackground = a.getResourceId(
                    R.styleable.Gallery1_android_galleryItemBackground, 0);
a.recycle();

4) 然后将mGalleryItemBackground设置为您视图的背景。这样您的视图外部就会有一个边框。

例如:

imageView.setBackgroundResource(mGalleryItemBackground);

1
谢谢您的回复。我使用了您的代码,但是仍然出现了“styleable无法解析”的红线错误。但是我已经在值文件夹下创建了attr.xml。 - sanjay
抱歉啊,我打错字了,文件名应该是attrs.xml。改一下文件名就可以正常工作了。 - mudit

0

您还可以通过创建自己的形状文件来创建自定义背景...

    <shape xmlns:android="http://schemas.android.com/apk/res/android"
      android:shape="rectangle" >
    <solid android:color="#ffffff" />
    <stroke android:width="1dip" android:color="#4fa5d5"/>
    </shape>

然后只需为资源添加一个背景...

    imageView.setBackgroundResource(R.drawable.shape);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接