how to convert listview to gridview

前端 未结 5 646
梦毁少年i
梦毁少年i 2021-01-02 20:04

below is my code which works fine for showing listview horizontally. how can I change it to gridvew. What changes should I make to change it to gridview? help me please

相关标签:
5条回答
  • 2021-01-02 20:28

    I'd suggest that you use RecyclerView intead.

    You might want to refer to the documentation and learn more about it. I'm sharing my piece of code in which I'm changing my gridview to listview using RecyclerView

    If you're using Android Studio then you might need to add dependencies in gradle build. In my case I added as follows:

    dependencies {
        .
        .
        .
        compile 'com.android.support:recyclerview-v7:24.0.0'
    }
    

    First I'm defining a grid cell which is to be used in grid layout

    recycler_cell.xml

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">
    
    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:id="@+id/imageView2"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:background="#FF000000"
        android:layout_marginLeft="0dp"
        android:layout_marginRight="0dp"/>
    
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Small Text"
        android:id="@+id/textView2"
        android:layout_below="@+id/imageView2"
        android:layout_alig=nParentStart="true"
        android:layout_alignEnd="@+id/imageView2"
        android:gravity="center"/>
    </RelativeLayout>
    

    Now I'm defining a list row which is to be used in list layout

    recycler_row.xml

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
    
    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:id="@+id/imageView"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:background="#FF000000"/>
    
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_alignBottom="@+id/imageView"
        android:layout_alignParentEnd="true"
        android:layout_toEndOf="@+id/imageView"
        android:gravity="center_vertical"
        android:background="#FF333333"
        android:textColor="#FFF"
        android:padding="10dp"/>
    </RelativeLayout>
    

    recycler_view_test.xml And of course define a layout which would contain RecyclerView

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
    
    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/recyclerView"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="0dp"
        android:layout_alignParentTop="true"
        android:layout_marginTop="0dp"
        android:layout_centerHorizontal="true"
        >
    </android.support.v7.widget.RecyclerView>
    
    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Layout"
        android:id="@+id/btnChange"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="62dp"/>
    
    </RelativeLayout>
    

    I'm sharing my piece of code but I'd strongly recommend that you go through the documentation and tutorials to understand RecyclerView to its full extent.

    public class RecyclerViewTest extends AppCompatActivity
    {
        final int GRID = 0;
        final int LIST = 1;
        int type;
    
        RecyclerView recyclerView;
        RecyclerView.LayoutManager gridLayoutManager, linearLayoutManager;
        MyAdapter adapter;
    
        Button btnChange;
    
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.recycler_view_test);
    
            // Display contents in views
            final List<Person> list = new ArrayList<>();
            list.add(new Person("Ariq Row 1"));
            list.add(new Person("Ariq Row 2"));
            list.add(new Person("Ariq Row 3"));
    
            // Finding views by id
            recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
            btnChange = (Button) findViewById(R.id.btnChange);
    
            // Defining Linear Layout Manager
            linearLayoutManager = new LinearLayoutManager(getApplicationContext());
            // Defining Linear Layout Manager (here, 3 column span count)
            gridLayoutManager = new GridLayoutManager(getApplicationContext(), 3);
    
            //Setting gird view as default view
            type = GRID;
            adapter = new MyAdapter(list, GRID);
            recyclerView.setLayoutManager(gridLayoutManager);
            recyclerView.setAdapter(adapter);
    
            //Setting click listener
            btnChange.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View view)
                {
                    if (type == LIST)
                    {
                        // Change to grid view
                        adapter = new MyAdapter(list, GRID);
                        recyclerView.setLayoutManager(gridLayoutManager);
                        recyclerView.setAdapter(adapter);
                        type = GRID;
                    }
    
                    else
                    {
                        // Change to list view
                        adapter = new MyAdapter(list, LIST);
                        recyclerView.setLayoutManager(linearLayoutManager);
                        recyclerView.setAdapter(adapter);
                        type = LIST;
                    }
                }
            });
    
        }
    }
    
    //Defining Adapter
    class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>
    {
        List<Person> list;
        int type;
        final int GRID = 0;
        final int LIST = 1;
    
        MyAdapter(List<Person> list, int type)
        {
            this.list = list;
            this.type = type;
        }
    
        // Inflating views if the existing layout items are not being recycled
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
        {
            View itemView;
    
            if (viewType == GRID)
            {
                // Inflate the grid cell as a view item
                itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_cell, parent, false);
            }
    
            else
            {
                // Inflate the list row as a view item
                itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_row, parent, false);
            }
    
            return new ViewHolder(itemView, viewType);
        }
    
        // Add data to your layout items
        @Override
        public void onBindViewHolder(ViewHolder holder, int position)
        {
            Person person = list.get(position);
            holder.textView.setText(person.name);
        }
    
        // Number of items
        @Override
        public int getItemCount()
        {
            return list.size();
        }
    
        // Using the variable "type" to check which layout is to be displayed
        @Override
        public int getItemViewType(int position)
        {
            if (type == GRID)
            {
                return GRID;
            }
    
            else
            {
                return LIST;
            }
        }
    
        // Defining ViewHolder inner class
        public class ViewHolder extends RecyclerView.ViewHolder
        {
            TextView textView;
            final int GRID = 0;
            final int LIST = 1;
    
            public ViewHolder(View itemView, int type)
            {
                super(itemView);
                if (type == GRID)
                {
                    textView = (TextView) itemView.findViewById(R.id.textView2);
                }
    
                else
                {
                    textView = (TextView) itemView.findViewById(R.id.textView);
                }
            }
        }
    }
    
    // Data Source Class
    class Person
    {
        String name;
    
        Person(String name)
        {
            this.name = name;
        }
    }
    

    If you end up with the issue to auto fit the number of columns in case of grid layout then you might want to check @s-marks's answer in which he extended the GridLayoutManager class and added his own patch of code, and also my fix if you start having weird column width.


    In my case, using his solution I made a class as follows:

    class GridAutofitLayoutManager extends GridLayoutManager
    {
        private int mColumnWidth;
        private boolean mColumnWidthChanged = true;
    
        public GridAutofitLayoutManager(Context context, int columnWidth)
        {
            /* Initially set spanCount to 1, will be changed automatically later. */
            super(context, 1);
            setColumnWidth(checkedColumnWidth(context, columnWidth));
        }
    
        public GridAutofitLayoutManager(Context context, int columnWidth, int orientation, boolean reverseLayout)
        {
            /* Initially set spanCount to 1, will be changed automatically later. */
            super(context, 1, orientation, reverseLayout);
            setColumnWidth(checkedColumnWidth(context, columnWidth));
        }
    
        private int checkedColumnWidth(Context context, int columnWidth)
        {
            if (columnWidth <= 0)
            {
                /* Set default columnWidth value (48dp here). It is better to move this constant
                to static constant on top, but we need context to convert it to dp, so can't really
                do so. */
                columnWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 48,
                        context.getResources().getDisplayMetrics());
            }
    
            else
            {
                columnWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, columnWidth,
                        context.getResources().getDisplayMetrics());
            }
            return columnWidth;
        }
    
        public void setColumnWidth(int newColumnWidth)
        {
            if (newColumnWidth > 0 && newColumnWidth != mColumnWidth)
            {
                mColumnWidth = newColumnWidth;
                mColumnWidthChanged = true;
            }
        }
    
        @Override
        public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state)
        {
            int width = getWidth();
            int height = getHeight();
            if (mColumnWidthChanged && mColumnWidth > 0 && width > 0 && height > 0)
            {
                int totalSpace;
                if (getOrientation() == VERTICAL)
                {
                    totalSpace = width - getPaddingRight() - getPaddingLeft();
                }
                else
                {
                    totalSpace = height - getPaddingTop() - getPaddingBottom();
                }
                int spanCount = Math.max(1, totalSpace / mColumnWidth);
                setSpanCount(spanCount);
                mColumnWidthChanged = false;
            }
            super.onLayoutChildren(recycler, state);
        }
    }
    

    Then you simply have to change:

    gridLayoutManager = new GridLayoutManager(getApplicationContext(), 3);
    

    and use your custom grid layout object, here 100 is the width of columns in dp

    gridLayoutManager = new GridAutofitLayoutManager(getApplicationContext(), 100);
    
    0 讨论(0)
  • 2021-01-02 20:32

    You can do something like this:

    For the layout of the grid/list use a merge:

    <?xml version="1.0" encoding="utf-8"?>
    
    <merge xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    
    
    <ViewStub android:id="@+id/list" 
        android:inflatedId="@+id/showlayout"
        android:layout="@layout/list_view" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"/>
    
    <ViewStub android:id="@+id/grid" 
        android:inflatedId="@+id/showlayout"
        android:layout="@layout/grid_view" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"/>
    
    
    </merge>
    

    then define the layout for the list and the grid (and also for their items), and manage the passage between them inflating the layouts, and then use a method like this to change the current view:

    private void changeView() {
    
        //if the current view is the listview, passes to gridview
        if(list_visibile) {
            listview.setVisibility(View.GONE);
            gridview.setVisibility(View.VISIBLE);
            list_visibile = false;
            setAdapters();
        }
    
        else {
            gridview.setVisibility(View.GONE);                      
            listview.setVisibility(View.VISIBLE);
            list_visibile = true;
            setAdapters();
        }
    }
    

    If you need the complete code, it is available in this article:

    http://pillsfromtheweb.blogspot.it/2014/12/android-passare-da-listview-gridview.html

    0 讨论(0)
  • 2021-01-02 20:33

    Just take a GridView object instead of Listview like :

    GridView gridView;
    gridView= (GridView) this.findViewById(R.id.gridView1);
    

    And in you getView method of CategoryListAdapter3 do like :

    convertView = inflater.inflate(R.layout.your_grid_item_leyout, null);
    

    And at last in onPostExecute of TheTask do like :

    gridView.setAdapter(cla);
    

    That's It.

    0 讨论(0)
  • 2021-01-02 20:37

    No change at all. Just set adapter of GridView as your are setting for ListView.

    0 讨论(0)
  • 2021-01-02 20:48

    Use GridView instead of below:

    Then replace

    listview = (HorizontalListView) this.findViewById(R.id.listview2);
    

    to

    GridView gridview;
    gridview=(GridView) findViewById(R.id.gridview);
    

    Everything else are fine, just set Adapter using GridView object. And you are done.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题