Search code examples
androidjsonlistviewandroid-listview

Inflate two different Itens with different adapters in ListView on Android


I make a ListView that receive data in JSON and define each item according the data received. Its working fine, but now I need to add the first item with a different layout, that will be defined by a different JSON, with different data, how can I do this?

I'm using InfiniteScroll library, but it just make the ListView infinite, the base is the same.

Obs: I've already tried to inflate different layout for position == 0, but didn't work, the first and the last itens of ListView keep with the different layout, and if I do this, I will lost the first item for the JSON data that I'm already using.

Here is how I'm doing the firs part:

public class TabPerfil extends ListActivity {

public static ArrayList<ItensMural> array_itensMural;


private static final int SEVER_SIDE_BATCH_SIZE = 25;

private InfiniteScrollListView demoListView;

private ListAdapterMural demoListAdapter;
private Handler handler;
private AsyncTask<Void, Void, List<ItensMural>> fetchAsyncTask;

private LoadingMode loadingMode = LoadingMode.SCROLL_TO_BOTTOM;
private StopPosition stopPosition = StopPosition.REMAIN_UNCHANGED;

ImageLoader imageLoader;

public TabPerfil () {
    super();
    array_itensMural = new ArrayList<ItensMural>();
    // Set up the image mapping for data points

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.tab_perfil);


    handler = new Handler();

    demoListView = (InfiniteScrollListView) this.findViewById(android.R.id.list);

    demoListView.setLoadingMode(loadingMode);
    LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    demoListView.setLoadingView(layoutInflater.inflate(R.layout.loading_view_demo, null));
    demoListAdapter = new ListAdapterMural(getApplicationContext(), new NewPageListener() {
        @Override
        public void onScrollNext() {
            fetchAsyncTask = new AsyncTask<Void, Void, List<ItensMural>>() {
                @Override
                protected void onPreExecute() {
                    // Loading lock to allow only one instance of loading
                    demoListAdapter.lock();
                }
                @Override
                protected List<ItensMural> doInBackground(Void ... params) {
                    List<ItensMural> result = new ArrayList<ItensMural>();
                    // Mimic loading data from a remote service

                    getMuralData();


                    for(int i = 0; i<SEVER_SIDE_BATCH_SIZE;i++)
                    {   
                        if(array_itensMural.size()>0 && i<array_itensMural.size())
                            result.add(array_itensMural.get(i));
                        else
                            break;
                    }
                    array_itensMural.clear();
                    return result;
                }
                @Override
                protected void onPostExecute(List<ItensMural> result) {
                    if (isCancelled() || result == null || result.isEmpty()) {
                        demoListAdapter.notifyEndOfList();
                    } else {
                        // Add data to the placeholder
                            demoListAdapter.addEntriesToBottom(result);

                        // Add or remove the loading view depend on if there might be more to load
                        if (result.size() < SEVER_SIDE_BATCH_SIZE) {
                            demoListAdapter.notifyEndOfList();
                        } else {
                            demoListAdapter.notifyHasMore();
                        }
                        // Get the focus to the specified position when loading completes

                    }
                };
                @Override
                protected void onCancelled() {
                    // Tell the adapter it is end of the list when task is cancelled
                    demoListAdapter.notifyEndOfList();
                }
            }.execute();
        }
        @Override
        public View getInfiniteScrollListView(final int position, View convertView, ViewGroup parent) {
            // Customize the row for list view


            if(convertView == null) {

                    LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    convertView = layoutInflater.inflate(R.layout.item_perfil, null);

            }

            defineLayout(convertView, position);

            return convertView;
        }
    });
    demoListView.setAdapter(demoListAdapter);
    // Display a toast when a list item is clicked
    demoListView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
            handler.post(new Runnable() {
                @Override
                public void run() {

                }
            });
        }
    });

     // Set a listener to be invoked when the list should be refreshed.
    ((InfiniteScrollListView) getListView()).setOnRefreshListener(new ca.weixiao.widget.InfiniteScrollListView.OnRefreshListener() {
        @Override
        public void onRefresh() {
            // Do work to refresh the list here.
            new GetDataTask().execute();
        }
    });

}

@Override
protected void onResume() {
    super.onResume();
    // Load the first page to start demo
    demoListAdapter.onScrollNext();
}

public void getMuralData()
{

    //Json Request
    String resposta = Services.JsonRequest();

    try {
        JSONObject jObj = new JSONObject(resposta);
        JSONArray items = jObj.getJSONArray(TysdoConstants.JSON_ITEMS);

        TabPerfil.array_itensMural = new ArrayList<ItensMural>();

        for(int i=0; i<items.length();i++)
        {
            ItensMural newItem = new ItensMural();

            JSONObject item_obj = items.getJSONObject(i);
            newItem.items_id = item_obj.getInt("id");
              //...
            array_itensMural.add(newItem);
        }


    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public void defineLayout(View convertView, int position)
{

    final ItensMural itens = (ItensMural) demoListAdapter.getItem(position);

     if (itens != null) {

            //Set layout things, like TextView.setText("Text") etc
        }

}



private class GetDataTask extends AsyncTask<Void, Void, List<ItensMural>> {

    @Override
    protected void onPreExecute() {
        // Loading lock to allow only one instance of loading
        demoListAdapter.clearEntries();
    }

    @Override
    protected List<ItensMural> doInBackground(Void... params) {
        // Simulates a background job.

        demoListAdapter.onScrollNext();

        return array_itensMural;
    }

 @Override
    protected void onPostExecute(List<ItensMural> result) {

        ((InfiniteScrollListView) getListView()).onRefreshComplete();

        super.onPostExecute(result);
    }
}
}

The tab_perfil.xml:

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


<ca.weixiao.widget.InfiniteScrollListView
    android:id="@android:id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/infinite_listview_radiogroup_stop_position" />

</RelativeLayout>

the item_perfil.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
        android:paddingRight="5dp"
    android:paddingLeft="5dp">

<LinearLayout 
    android:paddingTop="5dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:id="@+id/layout_1">

    <TextView
        android:id="@+id/row_username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:paddingLeft="10dp"
        android:paddingRight="5dp"
        android:textSize="19sp" 
        android:textColor="@color/dark_grey"/>

         <TextView
            android:id="@+id/row_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="10dp"
            android:paddingRight="5dp"
            android:textSize="19sp" 
            android:text="18h"
            android:textColor="@color/dark_grey"/>

</LinearLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:id="@+id/layout_2"
    android:layout_below="@+id/layout_1"
    android:paddingBottom="-15dp">



            <ImageView
                android:id="@+id/img_photo"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:clickable="true"
                android:padding="2dp"
                android:scaleType="fitXY" />

             <ImageView
                android:id="@+id/img_photo_1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:clickable="true"
                android:src="@drawable/moldura_empresa_big"
                 android:scaleType="fitXY"
                 />

             <ImageView
                android:id="@+id/img_status"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:clickable="true"
                android:paddingLeft="-1dp"
                android:src="@drawable/feito_flag_big"
                android:scaleType="fitXY" />

                 <RelativeLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    android:background="@drawable/sombra_desejo"
                    android:layout_alignParentBottom="true">

                        <TextView
                            android:id="@+id/txt_desejo"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            style="@style/style_btnLogin"
                            android:gravity="center"/>

                  </RelativeLayout>

</RelativeLayout>

<RelativeLayout 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_below="@+id/layout_2"
    android:background="@drawable/barra_branca_desejo">

    <LinearLayout
                android:id="@+id/layout_curtir"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="15dp" 
                android:layout_alignParentLeft="true">

                    <Button
                        android:id="@+id/btn_like"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@drawable/icone_curtido_inactive" />

                    <TextView
                        android:id="@+id/row_likes"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingLeft="10dp"
                        android:paddingRight="5dp"
                        android:textColor="@color/dark_grey"
                        android:textSize="20sp"
                        android:textStyle="bold" />                 

        </LinearLayout>

    <LinearLayout
                android:id="@+id/layout_comment"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="15dp" 
                android:paddingRight="-15dp"
                android:layout_toRightOf="@+id/layout_curtir">

                    <Button
                        android:id="@+id/btn_comment"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@drawable/icone_comentario" />

                    <TextView
                        android:id="@+id/row_comments"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="@color/dark_grey"
                        android:paddingLeft="10dp"
                        android:paddingRight="5dp"
                        android:textSize="20sp"
                        android:textStyle="bold" />                 

        </LinearLayout>         

        <LinearLayout
                android:id="@+id/layout_incentivo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="15dp" 
                android:paddingLeft="-15dp"
                android:layout_toRightOf="@+id/layout_comment">

                    <Button
                        android:id="@+id/btn_incentivar"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@drawable/icone_incentivo" />

                    <TextView
                        android:id="@+id/row_incentivar"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="@color/dark_grey"
                        android:paddingLeft="10dp"
                        android:paddingRight="5dp"
                        android:textSize="20sp"
                        android:textStyle="bold"
                        android:text="999" />                   

        </LinearLayout>         

        <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_alignParentRight="true"
                android:padding="20dp">

                    <Button
                        android:id="@+id/btn_add"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@drawable/icone_mais" />            

        </LinearLayout>                 

</RelativeLayout>

</RelativeLayout>

Solution

  • Add Header View in your listview, try something like this-

    listMain = (ListView) findViewById(R.id.listMain);
            View header = View.inflate(this, R.layout.row_top, null);
            listMain.addHeaderView(header);
    

    EDIT:

    If above code does not work try this one-

    LayoutInflater inflater = getLayoutInflater();
            ViewGroup header = (ViewGroup)inflater.inflate(R.layout.header, listMain, false);
            listMain.addHeaderView(header, null, false);