Android ListView selection background - android

Okay I'm going absolutely nuts with this. I have a ListView in mode singleChoice, when I click on it I set it to selected. And I set the background to a drawable with a selector (and I tried many states that could correspond to a selected item). However when I select it the background doesn't change and I dont get why. I visited dozens of forums for this but couldn't get an answer. Here's my code:
The ListView in my activity:
<com.gaetanl.aspa.ui.component.ExtensibleListView
android:id="#+id/payment_billing_address_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/item_selectable"
android:choiceMode="singleChoice"></com.gaetanl.aspa.ui.component.ExtensibleListView>
Its class:
public class ExtensibleListView extends ListView {
public ExtensibleListView(Context context) {
this(context, null);
}
public ExtensibleListView(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.listViewStyle);
}
public ExtensibleListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(this, "item " + position + " selected = " + view.isSelected());
view.setSelected(true);
Log.d(this, "selected = " + view.isSelected());
}
});
}
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
The selector:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_activated="true"
android:drawable="#color/colorPrimary" />
<item
android:state_active="true"
android:drawable="#color/colorPrimary" />
<item
android:state_checked="true"
android:drawable="#color/colorPrimary" />
<item
android:state_selected="true"
android:drawable="#color/colorPrimary" />
<item
android:drawable="#android:color/transparent" />
</selector>

Method I:
In your list adapter,create getter and setter methods for position.Then in getView method, compare the position as in below:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item.xml, null);
holder = new ViewHolder(); holder.itemLayout(LinearLyout)convertView.findViewById(R.id.item_layout);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if(position==getPosition()){
holder.itemLayout.setBackgroundColor(ContextCompat.getColor(context,R.color.back_ground_color));
}else{
holder.itemLayout.setBackgroundColor(ContextCompat.getColor(context,R.color.background_unselect));
}
return convertView;
}
public void setPosition(int posit) {
this.position = posit;
}
private int getPosition() {
return this.position;
}
Then in the activity , inside listView's onItemSelected() method: call the adapter's setPositionMethod:
list_view.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
mAdapter.setPosition(i);
mAdapter.notifyDataSetChanged();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Just set the list selector to transparent ..that should do the job.
Method II:
Or may be ,You need a selector like below:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:drawable="#color/color_primary" >
</item>
<item
android:state_focused="true"
android:drawable="#color/color_primary" >
</item>
<item
android:state_selected="true"
android:drawablecolor="#color/color_primary" >
</item>
<item android:color="#color/#color/transparent" >
</item>
</selector>
then put list selector as #drawable/list_selector
But, if that doesn't work then I think you can set the background of item xml layout as
android:background="#drawable/list_selector"

Okay I found the answer. I was stupidly trying to set the ListView background (see code above). What I needed to do was, when creating adapter, to select a view for the items that incorporates variation for selected items. Android has one by default: simple_list_item_single_choice.
So here's the working code:
myListView = ((ListView) findViewById(R.id.listview_id));
ArrayAdapter<String> myAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_single_choice, myList);
myListView.setAdapter(myAdapter);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setSelected(true);
}
});
And then you have it, a list view with radio buttons on the right that check themselves when you click on em.
And here's the ListView in my layout.xml:
<ListView
android:id="#+id/listview_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:choiceMode="singleChoice">
</ListView>

Related

Remove Android Spinner onClick item background [duplicate]

This question already has answers here:
How to customize a Spinner in Android
(6 answers)
Closed 5 years ago.
I'm trying to remove the default highlight effect for Spinner item's onClick. I have my own specific spinner background which have radius in its corners. When I applied the new background, it still has its default background under my custom background. I've tried styling like this:
<style name="ExternalPSpinnerTheme" parent="Widget.AppCompat.Spinner.DropDown">
<item name="android:listSelector">#color/transparent</item>
<item name="android:listChoiceBackgroundIndicator">#color/transparent</item>
<item name="android:listChoiceIndicatorSingle">#color/transparent</item>
<item name="android:selectableItemBackground">#color/transparent</item>
<item name="android:background">#drawable/spinner_sortfriend_background</item>
<item name="android:cacheColorHint">#android:color/transparent</item>
<item name="android:popupBackground">#drawable/spinner_sortfriend_background</item>
<item name="android:dropDownSelector">#color/transparent</item>
</style>
I've tried changing the parent to Widget.AppCompat.Spinner but it didn't work.. PopupBackground and background works tho.
The other question is questioning on how to hide dividers and add its own spinner custom implementation, mine is asking about how to remove the default onClick highlight effect on the background. How did I try to achieve it? This is how:
if (position > 0 &&
(position + 1) < mDataset.size()){
divider.setVisibility(View.VISIBLE);
convertView.setBackground(ContextCompat.getDrawable(context, R.drawable.spinner_dropdown_background_middle_white_to_migrey));
} else if (position == 0){
divider.setVisibility(View.VISIBLE);
convertView.setBackground(ContextCompat.getDrawable(context, R.drawable.spinner_dropdown_background_top_white_to_migrey));
} else if (position + 1 == mDataset.size()){
divider.setVisibility(View.GONE);
convertView.setBackground(ContextCompat.getDrawable(context, R.drawable.spinner_dropdown_background_bottom_white_to_migrey));
}
And I still didn't get the right answer, I even tried the solution in the other question. I just realized something tho, only the background on the first item overlaps with my custom background click effect, but the one at the end of the list doesn't get overlapped.. Weird..
Any solution?
Create custom Spinner Layout in your xml as follows
<RelativeLayout
android:id="#+id/relativeLayout_multiChoiceDropDown"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/drawable_border_profile">
<TextView
android:id="#+id/textView_multiChoiceDropDownText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_marginBottom="#dimen/margin_5dp"
android:layout_marginEnd="#dimen/margin_5dp"
android:layout_marginStart="#dimen/margin_5dp"
android:layout_marginTop="#dimen/margin_5dp"
android:layout_toStartOf="#+id/button_multiChoiceDropDownArrow"
android:padding="#dimen/margin_5dp"
android:text="Select Item"
android:textColor="#color/black"
android:textSize="#dimen/text_size_16"/>
<Button
android:id="#+id/button_multiChoiceDropDownArrow"
android:layout_width="#dimen/profile_multi_choice_width"
android:layout_height="#dimen/profile_multi_choice_height"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_margin="#dimen/margin_5dp"
android:background="#drawable/dropdownarrow"/>
</RelativeLayout>
drawable_border_profile.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#80FFFFFF"/>
<stroke
android:width="0.5dp"
android:color="#color/light_gray"/>
<padding
android:bottom="1dp"
android:left="1dp"
android:right="1dp"
android:top="1dp"/>
</shape>
Then Set OnClickListener on RelativeLayout. On that You can open Popup Window
LayoutInflater inflater = (LayoutInflater)parentActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.pop_up_window, null);
RelativeLayout layout1 = holder.relativeLayout_multiChoiceDropDown;
pw = new PopupWindow(layout, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
pw.setBackgroundDrawable(new BitmapDrawable());
pw.setTouchable(true);
pw.setOutsideTouchable(true);
pw.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
pw.setTouchInterceptor(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event)
{
if (event.getAction() == MotionEvent.ACTION_OUTSIDE)
{
pw.dismiss();
return true;
}
return false;
}
});
pw.setContentView(layout);
pw.showAsDropDown(layout1, -5, 0);
final ListView list = (ListView) layout.findViewById(R.id.dropDownList);
Adapter_DropDown adapter = new Adapter_DropDown(parentActivity, items);
list.setAdapter(adapter);
pop_up_window.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="#+id/PopUpView"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/qatool_basic_info_dropdown"
android:orientation="vertical">
<ListView
android:id="#+id/dropDownList"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#000"
android:dividerHeight="0.5dp">
</ListView>
You can use customArray Adapter
public class Adapter_Spinner extends ArrayAdapter
{
Context context;
List<Response_IdDesc> dataArray;
public Adapter_Spinner(Context context, int textViewResourceId, List<Response_IdDesc> dataArray)
{
super(context, textViewResourceId, dataArray);
this.dataArray = dataArray;
this.context = context;
}
#Override public Response_IdDesc getItem(int position)
{
return dataArray.get(position);
}
#Override public int getCount()
{
return dataArray.size();
}
#Override public int getPosition(Object item)
{
return dataArray.indexOf(item);
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
return getCustomView(position, convertView, parent);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.rowitem_spinner_profile, parent, false);
TextView label = (TextView) view.findViewById(R.id.textview_spinner);
label.setText(dataArray.get(position).DESC);
return view;
}
}
Then set your spinner adapter like this
Adapter_Spinner adapter_spinner = new Adapter_Spinner(parentActivity, R.layout.rowitem_spinner, list);
spinner.setAdapter(adapter_spinner);

Set Background image, if the Custom Listview item is pressed

I am using custom list view using base adapter
<ListView
android:id="#+id/lstHome"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:drawSelectorOnTop="false"
android:cacheColorHint="#3d4241"
android:clickable="true"
android:listSelector="#drawable/listbackground">
</ListView>
and listbackground.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#android:color/transparent" android:state_pressed="false" android:state_selected="false"/>
<item android:drawable="#drawable/list_background" android:state_pressed="true"/>
<item android:drawable="#drawable/list_background" android:state_pressed="false" android:state_selected="true"/>
</selector>
when i click on item the image background is just flashing but i want it should be activated
and show the background.
i used android:attr/activatedBackgroundIndicator in custom listview but it does not work for api below level 11.
Instead of listselector, you can try this:
Create bg_key.xml:
<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="true"
android:drawable="#color/pressed_color"/>
<item
android:drawable="#color/default_color" />
</selector>
Then include this background to your listview:
android:background="#drawable/bg_key"
And then, in your activity, create an onclick listner for your listview:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long arg3) {
view.setSelected(true);
}
}
The color code in bg_key, is up to you..
You will use this custom adapter in you listview
public class CustomAdapter extends ArrayAdapter<Sample> {
public ArrayList<Sample> mlist;
public Context context;
public LayoutInflater inflater;
public int[] i ;
public int start=0;
private LinearLayout layout;
private View view;
private View mLastView;
public CustomAdapter(Context context, int resource, ArrayList<Sample> mlist) {
super(context, resource);
this.mlist = mlist;
start=0;
this.context = context;
i = new int[this.mlist.size()];
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getPosition(Sample item) {
return super.getPosition(item);
}
#Override
public Sample getItem(int position) {
return mlist.get(position);
}
#Override
public int getCount() {
return mlist.size();
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
view = inflater.inflate(R.layout.listitem, null);
layout = (LinearLayout)view.findViewById(R.id.linearlayoutSample);;
TextView text1 = (TextView) view.findViewById(R.id.item1);
TextView text2 = (TextView) view.findViewById(R.id.item2);
layout.setBackgroundColor(Color.BLACK);
text1.setText(mlist.get(position).getListitem1());
text2.setText(mlist.get(position).getListitem2());
layout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(start==0)
{
mLastView = v;
start++;
}
if(start>0)
{
mLastView.setBackgroundColor(Color.BLACK);
mLastView = v;
}
v.setBackgroundColor(Color.GRAY);
}
});
return view;
}
}
you could try this with the previous version of your code:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#android:color/transparent" android:state_pressed="false"
android:state_selected="false"/>
<item android:drawable="#drawable/list_background" android:state_pressed="true"/>
<item android:drawable="#drawable/list_background" android:state_selected="true"/>
<item android:drawable="#drawable/list_background" android:state_active="true"/>
</selector>
Then in the onClick of the view, get the relativeLayout or the LinearLayout inflating the row, and set its activated and also selected property to true, and that way i think you will get a background that remains.
Hope that helps.

Change the TEXT (not background) color of a spinner when an item is selected

I have a spinner with several options, each displaying a simple string. Initially, the text is all white. However, if the user selects an option (causing it to become what is displayed on top), I would like that text to become red.
How can I do this?
EDIT : solved
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
((TextView) arg1).setTextColor(Color.parseColor("#E3170D"));
}
if the user selects an option (causing it to become what is displayed
on top), I would like that text to become red.
So you most likely created OnItemSelectedListener() for your Spinner. So in onItemSelected() method you can simply change text color.
Pseudocode:
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
TextView selectedText = (TextView) parent.getChildAt(0);
if (selectedText != null) {
selectedText.setTextColor(Color.RED);
}
}
Hope it helps.
see this answer here and i will copy and paste it
Create custom View layout (e.g. from TextView)
Create Selector and set it as a background of that view
Set Spinner with custom view
Selector: custom_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true"
android:state_pressed="false"
android:drawable="#color/light_grey" />
<item android:state_focused="true"
android:state_pressed="true"
android:drawable="#color/light_grey" />
<item android:state_focused="false"
android:state_pressed="true"
android:drawable="#color/light_grey" />
<item android:state_selected="true" android:drawable="#color/light_grey"/>
<item android:drawable="#color/white" />
</selector>
Custom View layout: my_simple_item
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:lines="1"
android:padding="5dip"
android:background="#drawable/custom_selector"/>
Initialise Spinner:
String[] items = new String[] {"One", "Two", "Three"};
Spinner spinner = (Spinner) findViewById(R.id.mySpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.my_simple_item, items);
Hope this helps
some of you that using MaterialBetterSpinner and Binding your Layouts,
all the above won't help, try this, hope it helps you:
public class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, int textViewResourceId, List<String> objects) {
super(context, textViewResourceId, objects);
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final YourXMLBinding rowBinding = DataBindingUtil.inflate(inflater, R.layout.yourXML, parent,false);
rowBinding.tv1.setText(mMy.getValues().get(position));
if(position == mMy.getCurrentIndex()) {
rowBinding.tv1.setTypeface(Typer.set(getContext()).getFont(Font.ROBOTO_BOLD));//change font
rowBinding.tv1.setTextColor(ContextCompat.getColor(getContext(), R.color.yourColor));//change color
}
return rowBinding.getRoot();
}
}
yourXML is something like this:
<?xml version="1.0" encoding="utf-8"?>
<layout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#color/colorBackgroundStart">
<TextView
android:id="#+id/tv1"
android:layout_width="0dp"
android:layout_weight="0.7"
android:layout_height="30dp"
android:textColor="#fff"
android:textSize="16dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="8dp"/>
</layout>
create a spinner with this adapter and yourXML :
final MyAdapter adapter = new MyAdapter(getContext(), R.layout.yourXML, s.getValues());
final MaterialBetterSpinner spinner = new MaterialBetterSpinner(getContext());
spinner.setAdapter(adapter);
use this to change the text of selected Text
YOUR_SPINNER.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
TextView selectedText= view.findViewById(R.id.text_view_name_in_Adapter);
selectedText.setTextColor(getResources().getColor(R.color.YOUR_COLOR));
}
}
create like:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false" android:drawable="#color/red" />
<item android:drawable="#android:color/transparent" />
</selector>
and in your activity xml:
<Spinner...............
android:drawSelectorOnTop="true"
android:background="#drawable/sample"/>
Just add the OnItemSelectedListener to your spinner.
qtySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
((TextView) view).setTextColor(Color.BLACK); //Change selected text color
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});

HorizontalListview with image select and unselect

i am getting problem in image select/unselect in listiview.
in my case,
ByDefault->image color(Yellow)
First click->image color(Orange)
Second click->image color(Yellow)
If user click on over way then perfect,but when user first time click on first image and second time click on second image then both image color is orange(that's problem).
In my case only one image color is orange(means selected) at a time.
If you only support HoneyComb and above, it'll easy. Create a StateListDrawable and set it to list view item's background.
selector.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_activated="true" android:drawable="#drawable/item_focus" />
<item android:drawable="#android:color/transparent" />
</selector>
listview item's layout
<ImageView
android:id="#+id/image"
android:layout_width="100dp"
android:layout_height="100dp"
android:padding="5dp" />
and the last, set your listview choice mode to SINGLE
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
2. If you manage to support pre HoneyComb, you will have to write your own layout implement checkable. You do this in order to work-out using checked state. Let take an example with LinearLayout(you can do the same with others).
package com.example.listviewactivestate;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Checkable;
import android.widget.LinearLayout;
public class CustomLinearLayout extends LinearLayout implements Checkable {
private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked };
private boolean checked = false;
public CustomLinearLayout (Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomLinearLayout (Context context) {
super(context);
}
#Override
public boolean isChecked() {
return checked;
}
#Override
public void setChecked(boolean checked) {
this.checked = checked;
refreshDrawableState();
// Propagate to childs
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child instanceof Checkable) {
((Checkable) child).setChecked(checked);
}
}
}
#Override
protected int[] onCreateDrawableState(int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (isChecked()) {
mergeDrawableStates(drawableState, CHECKED_STATE_SET);
}
return drawableState;
}
#Override
public void toggle() {
this.checked = !this.checked;
}
}
Use this custom view in xml
<?xml version="1.0" encoding="utf-8"?>
<com.example.listviewactivestate.CustomLinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/selector"
>
<ImageView
android:id="#+id/image"
android:layout_width="100dp"
android:layout_height="100dp"
android:padding="5dp" />
</com.example.listviewactivestate.CustomLinearLayout >
Change state_activated to state_checked
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="#drawable/item_focus" />
<item android:drawable="#android:color/transparent" />
</selector>
Also set listview choice mode to SINGLE. If it does not work, add onItemClickEvent like this
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
list.setItemChecked(position, true);//make sure click item is set to checked.
}
});

change color of selected listview item

I want to change color of list item when it will press
For that I did like below,
list_item_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
Selected
<item
android:state_focused="true"
android:state_selected="false"
android:drawable="#drawable/list_focused"/>
Pressed
<item
android:state_selected="true"
android:state_focused="false"
android:drawable="#drawable/list_selected" />
</selector>
I have set the color in colors.xml like below,
<drawable name="list_focused">#36C170</drawable>
<drawable name="list_selected">#9EC136</drawable>
and in my ListView I wrote like this,
<ListView
android:id="#+id/list_centers_complete"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cacheColorHint="#android:color/transparent"
android:listSelector="#drawable/list_item_selector" />
but when I am clicking on list item, the whole background color is changed instead of only list item.
How can I solve this?
Is there any way?
Thank you
Apply "#drawable/list_item_selector" to the row of that list(List item) not a List itself..
Something like, your list item (list row)..
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:background="#drawable/list_item_selector">
<TextView android:id="#+id/textForList"
android:layout_height="fill_parent"
android:layout_width="wrap_content"
android:padding="10sp" />
.
.
.
</LinearLayout>
list_item_selector.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true">
<shape>
<solid android:color="#66FFFFFF" />
</shape>
</item>
<item>
<shape>
<solid android:color="#FF666666" />
</shape>
</item>
</selector>
You should be setting the selector to the row and not the listview itself.
<item android:state_activated="true">
<shape android:shape="rectangle">
<solid android:color="#333333" />
<padding android:left="5dp" android:right="5dp" />
</shape></item>
<item><shape android:shape="rectangle">
<solid android:color="#222222" />
</shape></item>
Try with a custom adapter this also helps you to have full control over your items and set a default item selected; listView XML and item XML have no special setup.
public class ListAdapter extends ArrayAdapter<MyObj> {
private final int layoutInflater;
private Context context;
private List<MyObj> items;
private int mSelectedItem = 0;
private int TAG_UNSELECTED = 0;
private int TAG_SELECTED = 1;
public ListAdapter(Context context, int resource, List<MyObj> items) {
super(context, resource, items);
this.context = context;
this.layoutInflater = resource;
this.items = items;
}
public void selectItem(int position) {
mSelectedItem = position;
notifyDataSetChanged();
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
return position == mSelectedItem ? TAG_SELECTED : TAG_UNSELECTED;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(layoutInflater, null);
}
MyObj myObj = items.get(position);
TextView textView = (TextView) v.findViewById(R.id.title);
textView.setText(myObj.title);
int type = getItemViewType(position);
if(type == TAG_SELECTED) {
v.setBackgroundColor(Color.parseColor("#1da7ff"));
textView.setTextColor(Color.parseColor("#ffffff"));
} else {
v.setBackgroundColor(Color.parseColor("#f8f8f8"));
textView.setTextColor(Color.parseColor("#474747"));
}
return v;
}
}
Then in your activity:
ListView listView = (ListView) findViewById(R.id.list_view);
ListAdapter adapter = new ListAdapter(mContext, R.layout.item_layout, list);
listView.setAdapter(adapter);
adapter.selectItem(0); // Default selected item
// Get selected item and update its background
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
adapter.selectItem(position);
}
});
use this
android:background="#drawable/list_item_selector""

Categories

Resources