Skip to content Skip to sidebar Skip to footer

Android How To Use Adapter For Listview Without Extending Listactivity

I have an application with tabs. In one tab I need to put data (strings) in rows. To do so I chose tableLayout but when I wanted to use a contextmenu on its rows it doesn't work.

Solution 1:

main Activity class:

import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;

publicclassSelectedActivityextendsActivity {

private SelectedAdapter selectedAdapter;
private ArrayList<String> list;

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.selected_example);

    // populate the model - a simple a list
    list = newArrayList<String>();
    list.add("Apple");
    list.add("Orange");
    list.add("Grape");
    list.add("Grape1");
    list.add("Grape2");
    list.add("Grape3");
    list.add("Grape4");
    list.add("Grape5");
    list.add("Grape6");

    // create our SelectedAdapter
    selectedAdapter = newSelectedAdapter(this,0,list);
    selectedAdapter.setNotifyOnChange(true);

    ListViewlistview= (ListView) findViewById(R.id.listExample);
    listview.setAdapter(selectedAdapter);

    listview.setOnItemClickListener(newOnItemClickListener() {
        //@OverridepublicvoidonItemClick(AdapterView arg0, View view,
                                       int position, long id) {
            // user clicked a list item, make it "selected"
            selectedAdapter.setSelectedPosition(position);
        }
    });
}

Adapter class:

import java.util.List;
    import android.content.Context;
    import android.graphics.Color;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.TextView;

    publicclassSelectedAdapterextendsArrayAdapter{

        // used to keep selected position in ListViewprivateintselectedPos= -1;   // init value for not-selectedpublicSelectedAdapter(Context context, int textViewResourceId,
                       List objects) {
             super(context, textViewResourceId, objects);
        }
        publicvoidsetSelectedPosition(int pos){
        selectedPos = pos;
             // inform the view of this change
             notifyDataSetChanged();
        }
        publicintgetSelectedPosition(){
             return selectedPos;
        }
        @Overridepublic View getView(int position, View convertView, ViewGroup parent) {
                 Viewv= convertView;
                 // only inflate the view if it's null// if (v == null) {LayoutInflatervi=   (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                        v = vi.inflate(R.layout.selected_row, null);
                 //  }// get text viewTextViewlabel= (TextView)v.findViewById(R.id.txtExample);
                     Button btn=(Button)v.findViewById(R.id.btn1);

                     // change the row color based on selected stateif(selectedPos == position){
                        label.setBackgroundColor(Color.CYAN);
                        btn.setBackgroundResource(R.drawable.next);
                     }
                     else{
                        label.setBackgroundColor(Color.WHITE);
                     }

                     label.setText(this.getItem(position).toString());       
                     return(v);
        }
}

Solution 2:

main.xml:

<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent"android:background="@drawable/bg8"android:id="@+id/RootView"
    ><LinearLayoutandroid:id="@+id/myLayout"android:layout_width="wrap_content"android:layout_height="fill_parent"></LinearLayout></LinearLayout>

You need to define an xml which will be used to hold data of each row:

<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation="horizontal"android:layout_width="fill_parent"android:layout_height="fill_parent"android:weightSum="1"><TableRowandroid:id="@+id/tableRow1"android:layout_width="793dp"android:layout_height="wrap_content"android:layout_weight="0.23" ><TextViewandroid:id="@+id/col1"android:layout_height="fill_parent"android:layout_width="wrap_content"android:width="50dp"android:textSize="18sp"

        /><TextViewandroid:id="@+id/col2"android:layout_height="fill_parent"android:layout_width="wrap_content"android:width="150dp"android:textSize="18sp"
        /><ImageViewandroid:id="@+id/editimage"android:background="@drawable/edit"android:clickable="true"android:onClick="ClickHandlerForEditImage"android:layout_width="35dp"android:layout_height="35dp"/></TableRow></LinearLayout>

In the above xml i have also included the ImageView, it is not really required but this is just to update you that we can include the other controls also.

& at the last you should have a function in your related class:

privatevoidLoadData()
{

    DBAdapter db = new DBAdapter(this);
    db.open();
    Cursor cur = db.GetData();
    private ListView lv = (ListView)findViewById(R.id.myLayout);
    lv.setAdapter(null);
    if(cur.moveToFirst())
    {
            String[] from = new String[] {"_id","column1"};
            int[] to = newint[] {R.id.col1, R.id.col2};
            SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.grid_item, cur, from, to);
            lv.setAdapter(adapter);  

     }
       db.close();
         }
}

Solution 3:

It appears that noone has answered you contextMenu question. To get a context menu to work with your list , after you call ListView yourList = getListView(); you must call registerForContextMenu(yourList);

And to handle the menu creation you must implement the method

@OverridepublicvoidonCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo){ 
super.onCreateContextMenu(context, v,menuInfo);
MenuInflaterinflater= getMenuInflater();
menu.setHeaderTitle("YOUR TITLE");
menu.setHeaderIcon(R.drawable.YOUR DRAWABLE);
inflater.inflate(R.menu.YOUR_MENU_RESOURCE, menu);
}

Then you can respond to clicks by implenting the method

@OverridepublicbooleanonContextItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.YOUR_MENU_ITEM: // do stuff if the item is selectedreturntrue;
case R.id.YOUR_MENU_ITEM: // do stuff if the item is selectedreturntrue;
case R.id.YOUR_MENU_ITEM: // do stuff if the item is selectedreturntrue;
 }
 returnfalse; // nothing selected
}

Post a Comment for "Android How To Use Adapter For Listview Without Extending Listactivity"