Android GridView Gallery |图像以标题分隔

Android GridView Gallery |图像以标题分隔,android,gridview,header,dialog,gallery,Android,Gridview,Header,Dialog,Gallery,我使用gridView gallery内置对话框构建应用程序。所有的画廊作品不错,但现在我想从另一个分开一些照片(需要创建一些类型的标题)。例如,我的SD卡文件夹中有一些名为1v1.jpg/1v2.jpg/1v3.jpg/2v1.jpg/2v2.jpg的照片,现在我想在gridView图库中显示它(假设它有两列) 它应该是什么样子: 一, 1v1.jpg 1v2.jpg 1v3.jpg 二, 2v1.jpg 2v2.jpg 等 现在我只有照片的画廊 一些代码: 网格适配器: public cla

我使用gridView gallery内置对话框构建应用程序。所有的画廊作品不错,但现在我想从另一个分开一些照片(需要创建一些类型的标题)。例如,我的SD卡文件夹中有一些名为1v1.jpg/1v2.jpg/1v3.jpg/2v1.jpg/2v2.jpg的照片,现在我想在gridView图库中显示它(假设它有两列)

它应该是什么样子:

一,

1v1.jpg 1v2.jpg

1v3.jpg

二,

2v1.jpg 2v2.jpg

现在我只有照片的画廊

一些代码:

网格适配器:

public class GridAdapter extends BaseAdapter {

    Context mContext;
    ArrayList<File> listFiles;

    public GridAdapter(Context context, ArrayList<File> files) {

        this.mContext = context;
        this.listFiles = files;

    }

    @Override
    public int getCount() {
        return listFiles.size();
    }

    @Override
    public Object getItem(int position) {
        return listFiles.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if(convertView == null)
        {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.my_grid, parent, false);
        }

        final ImageView iv = (ImageView) convertView.findViewById(R.id.imageView);

       Glide.with(mContext)
                .load(listFiles.get(position).getAbsolutePath()) //path to picture
                .into(iv);


        return convertView;
    }

} //end of gridadapter
公共类GridAdapter扩展BaseAdapter{
语境;
ArrayList列表文件;
公共GridAdapter(上下文、ArrayList文件){
this.mContext=上下文;
this.listFiles=文件;
}
@凌驾
public int getCount(){
返回listFiles.size();
}
@凌驾
公共对象getItem(int位置){
返回listFiles.get(位置);
}
@凌驾
公共长getItemId(int位置){
返回位置;
}
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图){
if(convertView==null)
{
convertView=LayoutInflater.from(mContext).充气(R.layout.my_grid,parent,false);
}
最终ImageView iv=(ImageView)convertView.findViewById(R.id.ImageView);
使用(mContext)滑动
.load(listFiles.get(position.getAbsolutePath())//图片路径
。加入第(iv)款;
返回视图;
}
}//gridadapter的结尾
//rest代码

public ArrayList<File> photoList;
public ArrayList<String> albumList;

photoList = imageReader(photoDir);
albumList = albumReader(photoDir);

//function to get all file paths (works)
    private ArrayList<File> imageReader(File root)
    {
        ArrayList<File> a = new ArrayList<>();
        File[] files = root.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {                 
                a.addAll(imageReader(file));
            } else {
                if (file.getName().length() == 14)
                {
                    a.add(file);
                }
            }
        }
        return a;
    }
        //function to get all headers name (works)
        private ArrayList<String> albumReader(File root)
        {
            ArrayList<String> pages = new ArrayList<>();
            File[] files = root.listFiles();
            for (File file : files)
            {
                String photoName;
                String temp = "";
                photoName =  file.getName();
                if(photoName.length()==14)
                {
                    photoName = photoName.substring(0, 4);        
                    if (!temp.equals(photoName))
                    {
                        if(pages.isEmpty() || !pages.contains(photoName))
                        {
                            pages.add(photoName);
                            temp = photoName;
                        }
                        else
                        {
                            break;
                        }
                    }
                }

            }

            return pages;
        }

public void firstChoiceDialogGallery() {

        inflater = this.getLayoutInflater();

        // Dialog layout
        v = inflater.inflate(R.layout.dialog_choice, null);

        // Get gridView from dialog_choice
        gV = (GridView) v.findViewById(R.id.gridView);

        // GridAdapter (Pass context and files list)
        GridAdapter adapter = new GridAdapter(this, photoList);



        // Set adapter
        gV.setAdapter(adapter);

        final AlertDialog.Builder builder2 = new AlertDialog.Builder(this);
        builder2.setTitle("MY GALLERY");

        builder2.setView(v);
        builder2.setPositiveButton("NEXT", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        }).setNegativeButton("BACK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });

        builder2.setCancelable(false);
        final AlertDialog dialog = builder2.create();
        dialog.show();
    }
公共阵列列表照片列表;
公共阵列列表;
照片列表=图像阅读器(photoDir);
albumList=albumReader(photoDir);
//函数获取所有文件路径(工作)
专用ArrayList imageReader(文件根)
{
ArrayList a=新的ArrayList();
File[]files=root.listFiles();
用于(文件:文件){
如果(file.isDirectory()){
a、 addAll(图像阅读器(文件));
}否则{
if(file.getName().length()==14)
{
a、 添加(文件);
}
}
}
返回a;
}
//函数获取所有标题名称(works)
专用ArrayList albumReader(文件根目录)
{
ArrayList pages=新建ArrayList();
File[]files=root.listFiles();
用于(文件:文件)
{
字符串名称;
字符串temp=“”;
photoName=file.getName();
if(photoName.length()==14)
{
photoName=photoName.substring(0,4);
如果(!temp.equals(photoName))
{
if(pages.isEmpty()| |!pages.contains(photoName))
{
页码。添加(照片名称);
温度=照片名称;
}
其他的
{
打破
}
}
}
}
返回页面;
}
public void firstChoiceDialogGallery(){
充气器=this.getLayoutFlater();
//对话框布局
v=充气机。充气(R.layout.dialog_选项,空);
//从对话框获取gridView\u选项
gV=(GridView)v.findViewById(R.id.GridView);
//GridAdapter(传递上下文和文件列表)
GridAdapter=新的GridAdapter(此为照片列表);
//设置适配器
gV.设置适配器(适配器);
final AlertDialog.Builder builder2=新建AlertDialog.Builder(此);
建筑商2.设置标题(“我的画廊”);
builder2.setView(v);
builder2.setPositiveButton(“下一步”,新的DialogInterface.OnClickListener(){
@凌驾
public void onClick(DialogInterface dialog,int which){
}
}).setNegativeButton(“返回”,新的DialogInterface.OnClickListener(){
@凌驾
public void onClick(DialogInterface dialog,int which){
}
});
builder2.可设置可取消(false);
final AlertDialog dialog=builder2.create();
dialog.show();
}
XML: grid_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <ImageView
        android:layout_width="@integer/width"
        android:layout_height="@integer/height"
        android:adjustViewBounds="true"
        android:id="@+id/imageView"
        android:layout_margin="5dp"
        android:layout_centerVertical="true"
        android:layout_alignParentEnd="true" />

</RelativeLayout>

grid.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/dialog_choice"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <GridView
        android:id="@+id/gridView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:numColumns="@integer/column_count"
        android:clickable="true"/>


</RelativeLayout>

正如你们所看到的,我编写了一个函数来获取标题名,gallery可以工作,但现在我不知道如何在特定的位置放置这些名称,以及如何做到这一点。 我想把它放到我现有的适配器上,但它不起作用


另外,我读到了StickyGridHeaders,所以在这里给出lib源代码的链接并不是答案,因为我已经知道了。问题是我不确定这是否是我想要的+我不知道如何实现这一现有代码我想您需要使用不同的项目视图类型。基于此,您可以为标题和基本项配置不同的布局。这应该适用于回收商,基于布局管理器-

有一个很好的方法来实现这种行为/布局。试着这样做:

sectionableAdapter:

public abstract class SectionableAdapter extends BaseAdapter {

public static final int MODE_VARY_WIDTHS = 0;
public static final int MODE_VARY_COUNT = 1;

private LayoutInflater inflater;
private int rowResID;
private int headerID;
private int itemHolderID;
private int colCount;
private int sectionsCount;
private int resizeMode;
private ViewGroup measuredRow;

public SectionableAdapter(LayoutInflater inflater, int rowLayoutID, int headerID, int itemHolderID)
{
    this(inflater, rowLayoutID, headerID, itemHolderID, MODE_VARY_WIDTHS);
}

/**
 * Constructor.
 * @param inflater inflater to create rows within the grid.
 * @param rowLayoutID layout resource ID for each row within the grid.
 * @param headerID resource ID for the header element contained within the grid row.
 * @param itemHolderID resource ID for the cell wrapper contained within the grid row. This View must only contain cells.
 */
public SectionableAdapter(LayoutInflater inflater, int rowLayoutID, int headerID, int itemHolderID, int resizeMode)
{
    super();
    this.inflater = inflater;
    this.rowResID = rowLayoutID;
    this.headerID = headerID;
    this.itemHolderID = itemHolderID;
    this.resizeMode = resizeMode;
    // Determine how many columns our row holds.
    View row = inflater.inflate(rowLayoutID, null);
    if (row == null)
        throw new IllegalArgumentException("Invalid row layout ID provided.");
    ViewGroup holder = (ViewGroup)row.findViewById(itemHolderID);
    if (holder == null)
        throw new IllegalArgumentException("Item holder ID was not found in the row.");
    if (holder.getChildCount() == 0)
        throw new IllegalArgumentException("Item holder does not contain any items.");
    colCount = holder.getChildCount();
    sectionsCount = getSectionsCount();
}

/**
 * Returns the total number of items to display.
 */
protected abstract int getDataCount();

/**
 * Returns the number of sections to display.
 */
protected abstract int getSectionsCount();

/**
 * @param index the 0-based index of the section to count.
 * @return the number of items in the requested section.
 */
protected abstract int getCountInSection(int index);

/**
 * @param position the 0-based index of the data element in the grid.
 * @return which section this item belongs to.
 */
protected abstract int getTypeFor(int position);

/**
 * @param section the 0-based index of the section.
 * @return the text to display for this section.
 */
protected abstract String getHeaderForSection(int section);

/**
 * Populate the View and attach any listeners.
 * @param cell the inflated cell View to populate.
 * @param position the 0-based index of the data element in the grid.
 */
protected abstract void bindView(View cell, int position);

/**
 * Perform any row-specific customization your grid requires. For example, you could add a header to the
 * first row or a footer to the last row.
 * @param row the 0-based index of the row to customize.
 * @param convertView the inflated row View.
 */
protected void customizeRow(int row, View rowView)
{
    // By default, does nothing. Override to perform custom actions.
}

@Override
public int getCount()
{
    int totalCount = 0;
    for (int i = 0; i < sectionsCount; ++i)
    {
        int count = getCountInSection(i);
        if (count > 0)
            totalCount += (getCountInSection(i)-1) / colCount + 1;
    }
    if (totalCount == 0)
        totalCount = 1;
    return totalCount;
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    int realPosition = 0;
    int viewsToDraw = 0;
    int rows = 0;
    int totalCount = 0;
    for (int i = 0; i < sectionsCount; ++i)
    {
        int sectionCount = getCountInSection(i);
        totalCount += sectionCount;
        if (sectionCount > 0 && position <= rows + (sectionCount - 1) / colCount)
        {
            realPosition += (position - rows) * colCount;
            viewsToDraw = (int)(totalCount - realPosition);
            break;
        }
        else
        {
            if (sectionCount > 0)
            {
                rows += (int)((sectionCount - 1) / colCount + 1);
            }
            realPosition += sectionCount;
        }
    }
    if (convertView == null)
    {
        convertView = inflater.inflate(rowResID, parent, false);
        if (measuredRow == null && resizeMode == MODE_VARY_COUNT)
        {
            measuredRow = (ViewGroup)convertView;
            // In this mode, we need to learn how wide our row will be, so we can calculate
            // the number of columns to show.
            // This listener will notify us once the layout pass is done and we have our
            // measurements.
            measuredRow.getViewTreeObserver().addOnGlobalLayoutListener(layoutObserver);
        }
    }
    int lastType = -1;
    if (realPosition > 0)
        lastType = getTypeFor(realPosition-1);
    if (getDataCount() > 0)
    {
        TextView header = (TextView)convertView.findViewById(headerID);
        int newType = getTypeFor(realPosition);
        if (newType != lastType)
        {
            header.setVisibility(View.VISIBLE);
            header.setText(getHeaderForSection(newType));

        }
        else
        {
            header.setVisibility(View.GONE);
        }
    }
    customizeRow(position, convertView);

    ViewGroup itemHolder = (ViewGroup)convertView.findViewById(itemHolderID);
    for (int i = 0; i < itemHolder.getChildCount(); ++i)
    {
        View child = itemHolder.getChildAt(i);
        if (i < colCount && i < viewsToDraw && child != null)
        {
            bindView(child, realPosition + i);
            child.setVisibility(View.VISIBLE);
        }
        else if (child != null)
        {
            child.setVisibility(View.INVISIBLE);
        }
    }
    return convertView;
}

private ViewTreeObserver.OnGlobalLayoutListener layoutObserver = new ViewTreeObserver.OnGlobalLayoutListener() {

    // The better-named method removeOnGlobalLayoutListener isn't available until a later API version.
    @SuppressWarnings("deprecation")
    @Override
    public void onGlobalLayout() {
        if (measuredRow != null)
        {
            int rowWidth = measuredRow.getWidth();
            ViewGroup childHolder = (ViewGroup)measuredRow.findViewById(itemHolderID);
            View child = childHolder.getChildAt(0);
            int itemWidth = child.getWidth();
            if (rowWidth > 0 && itemWidth > 0)
            {
                colCount = rowWidth / itemWidth;
                // Make sure this listener isn't called again after we layout for the next time.
                measuredRow.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                // The grid will now update with the correct column count.
                notifyDataSetChanged();
            }
        }
    }
};

}
所有这些布局都可以使用它:

活动\u分段\u grid.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
 >

<ListView
    android:id="@+id/sectionedGrid_list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:listSelector="@android:color/transparent"
    />

</RelativeLayout>

book_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:layout_height="200dp"
android:layout_weight="1"
android:orientation="vertical" 
android:background="@drawable/gradients"
android:layout_margin="8dp"
>
<TextView
    android:id="@+id/bookItem_title"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textColor="#ffffff"
    android:padding="8dp"
    />
</LinearLayout>

book\u item\u vary\u columns.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="190dp"
android:layout_height="190dp"
android:orientation="vertical" 
android:padding="8dp"
>
<TextView
    android:id="@+id/bookItem_title"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textColor="#ffffff"
    android:padding="8dp"
    android:background="@drawable/gradients"
    />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView 
    android:id="@+id/bookRow_header"
    style="@android:style/TextAppearance.Holo.Large"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="8dp"
    android:visibility="gone"
    />
<LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:id="@+id/bookRow_itemHolder"
    >
    <include layout="@layout/book_item_vary_columns"/>
    <include layout="@layout/book_item_vary_columns"/>
    <include layout="@layout/book_item_vary_columns"/>
    <include layout="@layout/book_item_vary_columns"/>
    <include layout="@layout/book_item_vary_columns"/>
    <include layout="@layout/book_item_vary_columns"/>
    <include layout="@layout/book_item_vary_columns"/>
    <include layout="@layout/book_item_vary_columns"/>
    <include layout="@layout/book_item_vary_columns"/>
    <include layout="@layout/book_item_vary_columns"/>
</LinearLayout>

</LinearLayout>

book_row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView 
    android:id="@+id/bookRow_header"
    style="@android:style/TextAppearance.Holo.Large"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="8dp"
    android:visibility="gone"
    />
<LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:id="@+id/bookRow_itemHolder"
    >
    <include layout="@layout/book_item"/>
    <include layout="@layout/book_item"/>
</LinearLayout>

</LinearLayout>

book\u row\u vary\u columns.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="190dp"
android:layout_height="190dp"
android:orientation="vertical" 
android:padding="8dp"
>
<TextView
    android:id="@+id/bookItem_title"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textColor="#ffffff"
    android:padding="8dp"
    android:background="@drawable/gradients"
    />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView 
    android:id="@+id/bookRow_header"
    style="@android:style/TextAppearance.Holo.Large"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="8dp"
    android:visibility="gone"
    />
<LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:id="@+id/bookRow_itemHolder"
    >
    <include layout="@layout/book_item_vary_columns"/>
    <include layout="@layout/book_item_vary_columns"/>
    <include layout="@layout/book_item_vary_columns"/>
    <include layout="@layout/book_item_vary_columns"/>
    <include layout="@layout/book_item_vary_columns"/>
    <include layout="@layout/book_item_vary_columns"/>
    <include layout="@layout/book_item_vary_columns"/>
    <include layout="@layout/book_item_vary_columns"/>
    <include layout="@layout/book_item_vary_columns"/>
    <include layout="@layout/book_item_vary_columns"/>
</LinearLayout>

</LinearLayout>


请注意,这段代码不是我的,它正好符合这个问题,我以前研究过这些信息。尝试在google中搜索分段网格-您将找到一个演示apk。

需要创建一个名为item_row.xml的自定义适配器或任何您想要的适配器

item_row.xml

在布局中定义所需的视图,在本例中,我看到的是图像视图和文本视图:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="105dp"
android:layout_height="120dp">
<ImageView
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:id="@+id/ImgItem"
    android:layout_marginTop="7dp"
    android:layout_gravity="center"/>
<TextView
    android:id="@+id/textItem"
    android:layout_width="120dp"
    android:layout_height="25dp"
    android:textSize="16sp"
    android:layout_marginBottom="3dp"
    android:layout_gravity="center"
    android:textColor="#182b4b"
    android:gravity="center" />
</LinearLayout>
T
public class rowitem extends ArrayAdapter<String> {

private final Activity context;
private String[] nameItem;
private Bitmap[] iconsItem;

public rowitem(Activity context, String[] nameItem, Bitmap[] iconsItem) {
    super(context, R.layout.adapter_sketchmenuside, nameItem);
    // TODO Auto-generated constructor stub

    this.context = context;
    this.nameItem = nameItem;
    this.iconsItem = iconsItem;
}

public View getView(int posicion, View view, ViewGroup parent){
    LayoutInflater inflater = context.getLayoutInflater();
//inflate the item_row.xml view
    View rowView = inflater.inflate(R.item_row,null, 
true);

    TextView txtTitle = (TextView) rowView.findViewById(R.id.textItem);
    ImageView imageView = (ImageView) rowView.findViewById(R.id.ImgItem);

// Do your stuff
}
GridView myGrid = (GridView) view.findViewById(R.id.GrdCategory);

//in wherever you want, set the adapter:
myGrid.setAdapter(new rowitem(getActivity(), 
               namesArray, //here you send an Array with Strings for the names of the images
               imgArray, // here you send an array with the images you want to load
));
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
    <ListView
        android:id="@+id/lv_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    </RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
    android:id="@+id/tv_header"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

<GridView
    android:id="@+id/gv_items"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:numColumns="2" />
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">


<ImageView
    android:layout_width="@integer/width"
    android:layout_height="@integer/height"
    android:adjustViewBounds="true"
    android:id="@+id/imageView"
    android:layout_margin="5dp"
    android:layout_centerVertical="true"
    android:layout_alignParentEnd="true" />

</RelativeLayout>