SegFault SegFault - 15 days ago 6
Android Question

Passing from a listview to a gridview

I have an activity with a list, whose items are made of an image+text. I need to allow the user to change the view and have a gridview instead of it (whose elements are still made of the same image+text).

The user can do it through an icon menu:

public boolean onOptionsItemSelected(MenuItem item)
{
if(item.getItemId()== R.id.change_view)
{
// ?
}
}


I tried to just set the new adapter(see below) but it doesn't work..do I have to create a new activity to do that?

if(item.getItemId()== R.id.change_view)
{
setContentView(R.layout.grid_view);
gridViewAdapter = new GridViewAdapter(this,R.layout.bookmark_list_item,MyApp.getItems().findAll());
list.setAdapter(gridViewAdapter);
list.setVisibility(View.VISIBLE);
}

Answer

I finally resolved with something like this:

For the layout of my activity i have:

<?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 i've defined the layout for the list and the grid (and also for their items), and managed the passage between them inflating the layouts and then by this method:

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();
    }
}

the complete code is available in this article: http://pillsfromtheweb.blogspot.it/2014/12/android-passare-da-listview-gridview.html

Comments