I've been trying to solve this one but couldn't find any answer here.
what i'm trying to do is create an EditText search for custom arrayList, using ArrayAdapter.
All is going well until I actually search for an Object (named Product in this project).
when I search for one, meaning i input chars into the EditText the list goes blank and I cannot see any Items.
This is my code:
SearchActivity , receiving the ArrayList from the mainactivity :
public class SearchActivity extends Activity {
EditText editSearch;
ProductArrayAdapter productsAdapter;
ListView products;
static ArrayList<Product> viewList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
viewList = new ArrayList<Product>(MainActivity.listToBeSent);
Toast.makeText(getBaseContext(), viewList.get(1).getName(), Toast.LENGTH_LONG).show();
productsAdapter = new ProductArrayAdapter(this,
R.layout.layout_product, viewList);
products = (ListView) findViewById(R.id.listProducts);
products.setAdapter(productsAdapter);
editSearch = (EditText)findViewById(R.id.searchLine);
editSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String charsToSearch = editSearch.getText().toString().toLowerCase(Locale.getDefault());
productsAdapter.filter(charsToSearch);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
String charsToSearch = editSearch.getText().toString().toLowerCase(Locale.getDefault());
productsAdapter.filter(charsToSearch);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.search, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
ProductArrayAdapter which has the filter() method inside.
public class ProductArrayAdapter extends ArrayAdapter<Product> {
ArrayList<Product> products;
Context context;
int resource;
public ProductArrayAdapter(Context context, int resource,
ArrayList<Product> products) {
super(context, resource, products);
this.context=context;
this.resource=resource;
this.products=products;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
this.products.clear();
if (charText.length() == 0) {
this.products.addAll(SearchActivity.viewList);
} else {
for (Product singleProduct : SearchActivity.viewList) {
if (singleProduct.getName().toLowerCase(Locale.getDefault())
.contains(charText)) {
products.add(singleProduct);
}
}
}
notifyDataSetChanged();
}
static class ViewContainer {
public TextView txtName;
public TextView txtDescription;
public TextView txtPrice;
public ImageView imgProduct;
public ImageView imgOnSale;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewContainer viewContainer;
View rowView = convertView;
// means that if it is the first time and we didn't yet inflate the
// view, so inflate it now. rowView gets the already built or non-exist
// convertView.
if (rowView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
rowView = inflater.inflate(resource, null);
viewContainer = new ViewContainer();
/*viewContainer.textName = (TextView) rowView
.findViewById(this.textViewResource);*/
viewContainer.txtName = (TextView) rowView
.findViewById(R.id.txtName);
viewContainer.txtDescription = (TextView) rowView
.findViewById(R.id.txtDescription);
viewContainer.txtPrice = (TextView) rowView
.findViewById(R.id.txtPrice);
viewContainer.imgProduct = (ImageView) rowView
.findViewById(R.id.productPic);
viewContainer.imgOnSale = (ImageView) rowView
.findViewById(R.id.onSaleImage);
// adding tag to each rowView , tag can be Object therefore
// viewContainer = Object.
rowView.setTag(viewContainer);
} else {
viewContainer = (ViewContainer) (rowView.getTag());
}
Toast.makeText(getContext(), products.get(1).getCategory(), Toast.LENGTH_LONG).show();
Toast.makeText(getContext(), products.get(2).getCategory(), Toast.LENGTH_LONG).show();
viewContainer.txtName.setText(products.get(position).getName());
viewContainer.txtDescription.setText(products.get(position).getDescription());
viewContainer.txtPrice.setText("Price: " + (products.get(position).getPrice().toString()));
viewContainer.imgProduct.setImageResource(products.get(position).getImage());
viewContainer.imgOnSale.setImageResource(R.drawable.logo_icon);
return rowView;
}
I think the main problem is with the viewContainer part.
Appreciate your help !
Thank you Jay, just edited my code, now it does filter some items, but it seems like it doesn't
filter by the right chars, for example , when I search the letter 'r' it does get 'r' as the charSequence but it shows only the first item , and not the correct one .
here are the edited relevant lines :
on the textChangeListener I entered :
#Override
public void afterTextChanged(Editable s) {
String charsToSearch = editSearch.getText().toString().toLowerCase();
productsAdapter.getFilter().filter(charsToSearch);
}
and on the ProductArrayAdapter I changed the getView() method to :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewContainer viewContainer;
//View rowView = convertView;
// means that if it is the first time and we didn't yet inflate the
// view, so inflate it now. rowView gets the already built or non-exist
// convertView.
if (convertView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(resource, parent, false);
viewContainer = new ViewContainer();
viewContainer.txtName = (TextView) convertView
.findViewById(R.id.txtName);
viewContainer.txtDescription = (TextView) convertView
.findViewById(R.id.txtDescription);
viewContainer.txtPrice = (TextView) convertView
.findViewById(R.id.txtPrice);
viewContainer.imgProduct = (ImageView) convertView
.findViewById(R.id.productPic);
viewContainer.imgOnSale = (ImageView) convertView
.findViewById(R.id.onSaleImage);
// adding tag to each rowView , tag can be Object therefore
// viewContainer = Object.
convertView.setTag(viewContainer);
} else {
viewContainer = (ViewContainer) (convertView.getTag());
}
viewContainer.txtName.setText(products.get(position).getName());
viewContainer.txtDescription.setText(products.get(position).getDescription());
viewContainer.txtPrice.setText("Price: " + (products.get(position).getPrice().toString()));
viewContainer.imgProduct.setImageResource(products.get(position).getImage());
viewContainer.imgOnSale.setImageResource(R.drawable.logo_icon);
return convertView;
}
Any Ideas?
Remove your filter method. That is not the correct way to handle filtering with an adapter. The ArrayAdapter already supports a basic filtering mechanism. Simply do:
productsAdapter.getFilter.filter(charsToSearch);
For each product stored in the adapter, it'll do a:
singleProduct.toString().toLowerCase().startsWith(charsToSearch);
If the startsWith() logic works for you, a quick working solution would be to override the toString() method for your Product class and have it return getName(). Otherwise, there are really only two solutions available if you want a more custom solution for the filtering logic:
Write your own adapter from scratch using BaseAdapter and have it implement the Filterable interface. While a very basic implementation isn't too bad, it can be quite daunting if you never did it before.
Utilize an existing 3rd party library which allows you to add your own filtering logic.
Also note, when working with the ArrayAdapter it's very dangerous to keep your own copy of the list outside of what's constructed with the super. Especially when filtering is concerned. There's no guarantee that the list used to construct the adapter is the same one you are referencing externally. For further reading, go here.
For your getView() method, make sure you use getItem(position) instead of directly referencing products. Placing Toasts inside there is also not a good idea. When displaying your list, you will end up seeing a ton of Toasts pop up all at once. If you need debuging statements, use Log instead. Also, you need to adjust the following lines:
rowView = inflater.inflate(resource, null);
viewContainer = new ViewContainer();
To this instead:
viewContainer = inflater.inflate(resouce, parent, false);
You don't need that rowView variable at all. Just remove completely from the method and replace with viewContainer. Otherwise, your getView() method looks fine.
Related
This is example from Android for beginners book. I think that problem is with mNoteAdapter but I can't find where it exactly is. I tried to use adapter from other source and it was working(I mean click) so I could see at least log in logcat. How does mNoteAdapter affect on possibility of seeing users click by app? How can I find where problem is?
mNoteAdapter = new NoteAdapter();
ListView listNote = (ListView) findViewById(R.id.listView);
listNote.setAdapter(mNoteAdapter);
listNote.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View view, int
whichItem, long id) {
Log.e("CLICK", "CliCK");
}
});
}
Here is a piece of NoteAdapter class
public class NoteAdapter extends BaseAdapter {
List<Note> noteList = new ArrayList<Note>();
#Override
public int getCount() {
}
#Override
public Note getItem(int whichItem) {
}
#Override
public long getItemId(int whichItem) {
}
#Override
public View getView(int whichItem, View view, ViewGroup viewGroup) {
if (view == null) {
LayoutInflater inflater = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.listitem, viewGroup, false);
}
TextView txtTitle = (TextView) view.findViewById(R.id.txtTitle);
ImageView ivImportant = (ImageView) view.findViewById(R.id.imageViewImportant);
Note tempNote = noteList.get(whichItem);
if (!tempNote.isImportant()) {
ivImportant.setVisibility(View.GONE);
}
txtTitle.setText(tempNote.getTitle());
return view;
}
public void addNote(Note n) {
}
}
There are many ways to display items as list on Android..
--> ListView, RecyclerView etc.
Lists need a source right? Let's assume that your source is an array of 1000 elements. Your ListView has to have as many columns to display all of them right?
Adapter is responsible for taking the array, and assigning each element to every list placeholders
This row was added to the top of .xml file
android:descendantFocusability="blocksDescendants"
I want my listView to be updated after clicking on a row (or any event, but let's focus on click).
I did something, but it updates more than one row (maybe it updates the first visible row and the one after the last visible...).
Here is the full code
Activity code
DatabaseHandler colisageBase;
ListView listView;
List<Site> sites;
String id_tournee;
SiteAdapter siteAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_site_choice);
Intent intent = getIntent();
id_tournee = intent.getStringExtra("idTourneeSelectionnee");
this.listView = findViewById(R.id.list_view_site);
this.colisageBase = new DatabaseHandler(this);
sites = colisageBase.selectAllSite(id_tournee);
siteAdapter = new SiteAdapter(SiteChoiceActivity.this, sites);
listView.setAdapter(siteAdapter);
colisageBase.closeDB();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Site selectedSite = sites.get(position);
selectedSite.setIsBarred(true);
sites.set(position, selectedSite);
siteAdapter.notifyDataSetChanged();
//goToOperationActivity(selectedSite.SiteOut());
}
});
Adapter code
public class SiteAdapter extends ArrayAdapter<Site> {
public SiteAdapter(Context context, List<Site> sites) {
super(context, 0, sites);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_site,parent, false);
}
SiteViewHolder viewHolder = (SiteViewHolder) convertView.getTag();
if(viewHolder == null){
viewHolder = new SiteViewHolder();
viewHolder.heure_supposee = convertView.findViewById(R.id.heure_supposee);
viewHolder.libelle_site = convertView.findViewById(R.id.libelle_site);
viewHolder.logo_telephone = convertView.findViewById(R.id.logo_phone);
convertView.setTag(viewHolder);
}
Site site = getItem(position);
viewHolder.heure_supposee.setText(site.getHeure_supposee());
viewHolder.libelle_site.setText(site.getLibelle_site());
viewHolder.logo_telephone.setVisibility(View.INVISIBLE);
if (site.getSur_appel().equals("O")) viewHolder.logo_telephone.setVisibility(View.VISIBLE);
if (site.isBarred()) viewHolder.libelle_site.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG);
return convertView;
}
#Override
public void notifyDataSetChanged()
{
super.notifyDataSetChanged();
}
private class SiteViewHolder{
public TextView heure_supposee;
public TextView libelle_site;
public ImageView logo_telephone;
}
}
Please suggest what's wrong with the code.
The answer was given in the comments by I_A_Mok, but i have to add more details:
In the case of a cell, when you do an action in an "if" condition , you usually have to do the opposite in an "else" condition.
In my case, after my condition where I strike through text, I had to add an else condition where I don't strike through text.
if (site.isBarred()){
viewHolder.libelle_site.setPaintFlags(viewHolder.libelle_site.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}else {
viewHolder.libelle_site.setPaintFlags(viewHolder.libelle_site.getPaintFlags() & (~ Paint.STRIKE_THRU_TEXT_FLAG));
}
Here's my getView function in a custom class extending ArrayAdapter.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Thing p = getItem(position);
Thing.ThingStatus thingStatus = p.getStatus();
int thingStatusIcon; // change to thingStatusResource
switch (thingStatus) {
case A:
thingStatusIcon = ICON_A;
break;
case B:
thingStatusIcon = ICON_B;
break;
default:
thingStatusIcon = ICON_C;
break;
}
// Check if an existing view is being reused, otherwise inflate the view
ThingRowHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
// If there's no view to re-use, inflate a brand new view for row
viewHolder = new ThingRowHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.thing_list_item, parent, false);
// put these on the top like the colors
viewHolder.thingIcon = (ImageView) convertView.findViewById(R.id.thing_icon);
viewHolder.thingId = (TextView) convertView.findViewById(R.id.thing_id_item);
viewHolder.thingStatus = (TextView) convertView.findViewById(R.id.thing_status_item);
// Cache the viewHolder object inside the fresh view
convertView.setTag(viewHolder);
} else {
// View is being recycled, retrieve the viewHolder object from tag
viewHolder = (ThingRowHolder) convertView.getTag();
}
viewHolder.thingId.setText(p.getLpId());
viewHolder.thingStatus.setText(thingStatus.toString());
viewHolder.thingIcon.setImageResource(thingStatusIcon);
viewHolder.position = position;
return convertView;
}
I'm trying to add an onClick event listener for each row in my ListView. I tried setting the listener on convertView both inside the if statement and outside the else statement. I got mixed results. Sometimes the onClick wouldn't fire at all. Other times it would report the wrong position. I've scoured SO for examples of this and I'm surprised such a common functionality isn't well documented and/or not working in my case.
Any help would be much appreciated!
edit:
private class ThingRowHolder {
ImageView thingIcon;
TextView thingId;
TextView thingStatus;
}
edit 2:
private void refreshList() {
ArrayList<Thing> things = mThingContainer.getThings();
Collections.sort(things);
mThingListAdapter.refreshThings(things);
}
edit 3:
mThingListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ThingListAdapter.ThingRowHolder holder =
(ThingListAdapter.ThingRowHolder) view.getTag();
Thing p = mThingContainer.getThings().get(holder.position);
}
});
Set position as tag to your view,
convertview.setTag(R.id.thing_icon, position);
Now in your onClick(View v),
int pos = (int)v.getTag(R.id.thing_icon);
Thing p = getItem(pos);
You can now use p as desired.
Edit 1 : Updating data in adapter
In your adapter, add the following method :
public void updateData(List<Thing> data) {
if (data != null) {
mData.clear();
mData.addAll(data);
notifyDataSetChanged();
}
}
Now just call updateData method of adapter whenever you need to update the data.
Use these inside your getView method
If you want long click
convertView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {}}
if you want normal click
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {}}
I've been working on creating a single choice ListView populated by a custom ArrayAdapter (which works), except I need to set a pre-determined RadioButton in the ListView as setChecked(true) when the activity launches.
I'm populating my ListView with a List<Server> servers object at inflation that contains a boolean 'default_server' used to determine which row / RadioButton should be setChecked(true).
Selecting the various ListView items after the activity has launched correctly flags the specific RadioButton as setChecked(true) in Single Choice mode as desired.
My code:
ServerActivity.java
public class ServersActivity extends FragmentActivity
//FragmentActivity needed to display dialog fragment when ListView item clicked
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.server_list);
servers = getServers();
lv = (ListView) findViewById(android.R.id.list);
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
adapter = new ServerActivityArrayAdapter(this, R.layout.server_list_item, servers);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// show dialog if not long clicked
if (!longClicked) {
lv.setItemChecked(position, true);
showServerDialog(position);
}
}
});
}
ServerActivityArrayAdapter.java
public class ServerActivityArrayAdapter extends ArrayAdapter<Server> {
private int layout;
private int mSelectedPosition = -1;
private RadioButton mSelectedRB;
private static LayoutInflater inflater;
public ServerActivityArrayAdapter(Context context, int layout, List<Server> servers) {
super(context, layout, servers);
ListArrays listArrays = new ListArrays(context);
this.layout = layout;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
private static class ServerViewHolder {
private TextView textView;
private RadioButton radioButton;
public ServerViewHolder() {
// EMPTY DEFAULT CONSTRUCTOR
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final Server server = this.getItem(position);
final ServerViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(layout, parent, false);
viewHolder = new ServerViewHolder();
viewHolder.textView = (TextView) convertView.findViewById(R.id.tvServerName);
viewHolder.radioButton = (RadioButton) convertView.findViewById(R.id.rbDefault);
convertView.setTag(viewHolder);
} else {
viewHolder = (ServerViewHolder) convertView.getTag();
}
// TODO: SET THE DEFAULT SERVER
viewHolder.radioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (position != mSelectedPosition && mSelectedRB != null) {
mSelectedRB.setChecked(false);
}
mSelectedPosition = position;
notifyDataSetChanged();
mSelectedRB = (RadioButton) v;
server.setDefaultServer(mSelectedRB.isChecked());
}
});
if (mSelectedPosition != position) {
viewHolder.radioButton.setChecked(false);
} else {
viewHolder.radioButton.setChecked(true);
if (mSelectedRB != null && viewHolder.radioButton != mSelectedRB) {
mSelectedRB = viewHolder.radioButton;
}
}
viewHolder.textView.setText(server.getName());
return convertView;
}
}
Again, my List<Server> servers object is populating the ListView, the subsequent dialog popups (when a row is clicked) correctly and the RadioButtons on each row are currently functioning in Single Choice mode. I'm using server.setDefaultServer(mSelectedRB.isChecked()); in the setOnClickListener of ServerActivityArrayAdapter to update which server has default_server(true).
Everything I've tried so far in the ServerActivityArrayAdapter seems to break the Single Choice mode requirement of the RadioButton. How can I fix this?
I did go back and implement Shared Preferences into my project as Mridul suggested, but the solution really didn't require them.
Basically, I updated the constructor of my ServerActivityArrayAdapter class to let me pass the ID of the default server from the ServerActivity class when it's created. Also, I set mSelectionPostion = defServer, so the correct RadioButton in my ListView is checked when everything is inflated.
public ServerActivityArrayAdapter(Context context, int layout, List<Server> servers, int defServer) {
super(context, layout, servers);
ListArrays listArrays = new ListArrays(context);
this.layout = layout;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mSelectedPosition = defServer;
}
I have a problem with changing the background of a view in a ListView.
What I need:
Change the background image of a row onClick()
What actually happens:
The background gets changed (selected) after pressing e.g. the first entry. But after scrolling down the 8th entry is selected too.
Scroll back to the top the first isn't selected anymore. The second entry is selected now.
Continue scrolling and it continues jumping...
What i'm dong in the Code:
I have channels, and onClick() I toggle an attribute of channel boolean selected
and then I change the background.
I'm doing this only onClick() thats why I don't get why it's actuelly happening on other entries too.
One thing I notices is: It seems to be only the "drawing"-part because the item which get selected "by it self" has still the selected value on false
I think it seems to have something to do with the reuse of the views in the custom ListAdapters getView(...)
Code of onClick() in ListActivity:
#Override
protected ViewHolder createHolder(View v) {
// createHolder will be called only as long, as the ListView is not
// filled
TextView title = (TextView) v
.findViewById(R.id.tv_title_channel_list_adapter);
TextView content = (TextView) v
.findViewById(R.id.tv_content_channel_list_adapter);
ImageView icon = (ImageView) v
.findViewById(R.id.icon_channel_list_adapter);
if (title == null || content == null || icon == null) {
Log.e("ERROR on findViewById",
"Couldn't find Title, Content or Icon");
}
ViewHolder mvh = new MyViewHolder(title, content, icon);
// We make the views become clickable
// so, it is not necessary to use the android:clickable attribute in
// XML
v.setOnClickListener(new ChannelListAdapter.OnClickListener(mvh) {
public void onClick(View v, ViewHolder viewHolder) {
// we toggle the enabled state and also switch the the
// background
MyViewHolder mvh = (MyViewHolder) viewHolder;
Channel ch = (Channel) mvh.data;
ch.setSelected(!ch.getSelected()); // toggle
if (ch.getSelected()) {
v.setBackgroundResource(R.drawable.row_blue_selected);
} else {
v.setBackgroundResource(R.drawable.row_blue);
}
// TESTING
Log.d("onClick() Channel", "onClick() Channel: "
+ ch.getTitle() + " selected: " + ch.getSelected());
}
});
return mvh;
}
Code of getView(...):
#Override
public View getView(int position, View view, ViewGroup parent) {
ViewHolder holder;
// When view is not null, we can reuse it directly, there is no need
// to reinflate it.
// We only inflate a new View when the view supplied by ListView is
// null.
if (view == null) {
view = mInflater.inflate(mViewId, null);
// call own implementation
holder = createHolder(view);
// TEST
// we set the holder as tag
view.setTag(holder);
} else {
// get holder back...much faster than inflate
holder = (ViewHolder) view.getTag();
}
// we must update the object's reference
holder.data = getItem(position);
// <EDIT SOLUTION>
if(getItem(position).get_id() == channelList.get(position).get_id()){
if(getItem(position).getSelected())
{
view.setBackgroundResource(R.drawable.row_blue_selected);
}
else{
view.setBackgroundResource(R.drawable.row_blue);
}
}
// </EDIT SOLUTION>
// call the own implementation
bindHolder(holder);
return view;
}
I really would appreciate any idea how to solve this! :)
If more information is needed please tell me.
Thanks in advance!
Let me show you the code that I use for every ListView and properly controlling the click event for changing the background and doing anything further
public class Offices extends Activity {
private ListView listView;
/* selectedListItem will contain the number of items to be selected.
* Your list item OnOlickListener will simply change this variable
* to the position of the clicked item. The Adapter will do the rest
* because you need to refresh the ListView.
*/
private int selectedListItem = -1;
private Handler mHandler = new Handler();
private Vector<String> data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.officeslayout);
data = new Vector<String>();
// Add data as per your requirement
data.add("one");
data.add("two");
data.add("three");
data.add("four");
data.add("Five");
data.add("Six");
data.add("Seven");
data.add("Eight");
data.add("Nine");
data.add("Ten");
listView = (ListView)findViewById(R.id.ListView01);
listView.setDivider(null);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
selectedListItem = position;
((EfficientAdapter)listView.getAdapter()).notifyDataSetChanged();
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
// call any new activity here or do any thing you want here
}
}, 200L);
}
});
listView.setAdapter(new EfficientAdapter(getApplicationContext()));
}
private class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null || convertView.getTag() == null) {
convertView = mInflater.inflate(R.layout.officeslistitemlayout, null);
holder = new ViewHolder();
holder.backgroundView = (ImageView) convertView
.findViewById(R.id.OfficesBackground);
holder.officesTitle = (TextView) convertView
.findViewById(R.id.OfficesName);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if(position == selectedListItem) {
holder.backgroundView.setBackgroundResource(R.drawable.and_gray_bg_listing_selected);
} else {
holder.backgroundView.setBackgroundResource(R.drawable.and_gray_bg_listing);
}
holder.officesTitle.setText(data.get(position));
return convertView;
}
}
static class ViewHolder {
TextView officesTitle;
ImageView backgroundView;
}
}
officeslistitemlayout.xml file will be like following add drawable and design it according to you put the following code in RelativeLayout
<ImageView android:id="#+id/OfficesBackground" android:layout_width="fill_parent"
android:layout_height="45dip"
android:layout_alignParentTop="true"
android:background="#drawable/and_gray_bg_listing"
android:scaleType="fitXY"
></ImageView>
<TextView android:id="#+id/OfficesName" android:layout_width="wrap_content"
android:text="Offices Name"
android:textColor="#000000" android:textStyle="bold"
android:layout_height="wrap_content"
android:layout_centerVertical="true" android:layout_marginLeft="5dip"
></TextView>
Hope it will help :)