1

What is happening i have a listview on which i putting background color change on selection.As well as by default i am putting the first listview item selected as

public class OneWayFlightResult extends BaseAdapter {

private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;


public OneWayFlightResult(Activity a, ArrayList<HashMap<String, String>> d) {
    activity = a;
    data=d;
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return data.size();
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
     return position;
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View vi=convertView;
    if(convertView==null)
        vi = inflater.inflate(R.layout.row, null);
    TextView flightTime = (TextView)vi.findViewById(R.id.flightTime); // title
    TextView flightCompanyName = (TextView)vi.findViewById(R.id.flightCompanyName); // title
    TextView flightNumber = (TextView)vi.findViewById(R.id.flightNumber); // title
    ImageView flightLogo = (ImageView)vi.findViewById(R.id.flightLogo);

    HashMap<String, String> flight = new HashMap<String, String>();
    flight = data.get(position);

    flightTime.setText(flight.get(TestActivity.FlightTime));
    flightCompanyName.setText(TestActivity.FlightCompanyName);
    flightNumber.setText(TestActivity.FlightNumber);

    if(position == 0){

        vi.setBackgroundResource(R.drawable.selection_effect);
        vi.setSelected(true);

    }
    return vi;
}

This is XML file i am using in this selection_effect.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_focused="true">
    <shape>
        <solid android:color="#ffffff" />
    </shape>
</item>
    <item>
    <shape>
        <solid android:color="#00a7eb" />
    </shape>
</item>
</selector>

So by default this the first list view is selected.Now when the user select the another listview item the first one remains selected and the other one also got the same effect.So how could change the effect on click of the listview item dynamically .Means by default first item comes up selected when the user selects other item other one get selected the effect from the default one get removed

Developer
  • 6,292
  • 19
  • 55
  • 115
  • my suggestion was completely wrong. – Steve Benett Aug 07 '13 at 13:37
  • 1
    i edited my answer. And you need to delete those `if(position == 0){` and other code which you have used for selection. :) – Chintan Rathod Aug 12 '13 at 13:17
  • @ChintanRathod see this question is quite interesting and need u suggestion http://stackoverflow.com/questions/18571844/gcm-not-sending-the-notifications/18572611?noredirect=1#comment27327447_18572611 – Developer Sep 02 '13 at 11:59
  • @ChintanRathod have u seen my question on comment on that waiting for u reply – Developer Sep 03 '13 at 05:37
  • 4
    Possible duplicate of [How do I clear ListView selection?](https://stackoverflow.com/questions/48253761/how-do-i-clear-listview-selection) – The Dreams Wind Jan 10 '19 at 12:22

4 Answers4

3

I got solution for your problem. Do as following.

1) open your main layout file where ListView you have created.
Add android:choiceMode="singleChoice". This will look like below.

<ListView
    android:id="@+id/listView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:choiceMode="singleChoice" >
</ListView>

2) Open your list_item.xml layout file. In which, to your root view, add android:background="?android:attr/activatedBackgroundIndicator". In my sample project, its look like below.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?android:attr/activatedBackgroundIndicator"
    android:orientation="vertical" >

    //your views

</LinearLayout>

3) Open your activity file. After setting adapter to your ListView, add list.setSelector(R.drawable.selection_effect);. This will look like below.

ListView ls = (ListView) findViewById(R.id.listView1);
ListAdapter adapter = new ListAdapter(this, data);
ls.setAdapter(adapter);
ls.setSelector(R.drawable.selection_effect);

Here, selection_effect is drawable file which you have created in drawable directory. I tested my code. Which is working fine.

4) To select first view by default, remove your code in BaseAdapter and put following code after completing 3rd step.

ls.setItemChecked(0,true);

You need to put it after above code like below.

ListAdapter adapter = new ListAdapter(data);
ls.setAdapter(adapter);
ls.setSelector(R.drawable.selection_effect);
ls.setItemChecked(0, true);

Explanation

ls.setSelector(R.drawable.selection_effect);

This will select row item based on selector you have defined in drawable directory.

ls.setItemChecked(0, true);

This will select first item by default at first time run. After you can select other items by clicking on them.

Chintan Rathod
  • 25,864
  • 13
  • 83
  • 93
  • no no.. after line `ls.setSelector(R.drawable.selection_effect);`, you need to put that code. In `getView` there will be no any code regarding selection. That will automatically handled by selector. :) – Chintan Rathod Aug 12 '13 at 13:12
  • and was my question wrong why these peoples down vote if they don't find the solution ?? – Developer Aug 12 '13 at 13:20
  • @Gaurav, no dear.. i don't know who are they, but they may just down vote because they might found question very simple to solve :( . By the way, those are undisciplined that they are not providing any comment below your question regarding why they are down voting your question. When I was fresher then I also asked lots of questions because I am not getting desired output. Never mind brother. – Chintan Rathod Aug 12 '13 at 13:23
  • 1
    Thanks alot i hope this will help me in future also ..right now it is working fine .hope it will work in future.also otherwise i will sure catch u thank u very much :D – Developer Aug 12 '13 at 13:26
  • @Gaurav, Ready to help. Will that bounty be mine .. ha ha ..kidding you.. coz this is first time I am giving answer in featured questions..:) – Chintan Rathod Aug 12 '13 at 13:27
  • it is showing that i can award it in 18 hrs .i have accepted the answer brother it is yours now...;) – Developer Aug 12 '13 at 13:29
  • @Gaurav, so it is awarded after 18 hours by you my bro. It has time period of 1 day for awarding bounty. No problem. Will wait for it. :) – Chintan Rathod Aug 12 '13 at 13:34
  • @Gaurav, Bigger thing is you remembered... (will remove this comment after some time coz not constructive.. just want to thank you...) – Chintan Rathod Aug 13 '13 at 06:36
  • can you help me on this http://stackoverflow.com/questions/19092631/logout-from-the-application-android – Developer Oct 10 '13 at 06:21
0

You could just declare an int for item clicked which defaults to the first item that starts clicked, then in onclick update accordingly.

int selected = <default>;

set in oncreate etc.

Then you can have onItemClicked listener and do this,

public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
    if (selected != i){
        <listView>.getChildAt(selected).setBackgroundColor(getResources().getColor(android.R.color.background_dark));
        <listView>.getChildAt(i).setBackgroundColor(getResources().getColor(android.R.color.holo_blue_light));
        selected = i;
    }
}

This will change the background colour of the previously selected item back to (in my case) the default android dark theme colour, set the newly selected one to a nice highlighted light blue, and update the selected int to reflect the newly selected item.

rcbevans
  • 7,101
  • 4
  • 30
  • 46
  • 1
    Hang on, this is for multiselect... This isn't what you wanted is it? – rcbevans Aug 07 '13 at 13:40
  • see first requirement : Fist Item must be selected By default when the activity starts.Second requirement if the user select some other item from the list view then the second one will be highlighted and the first one property of being highlighted will be removed .Please help me on this i am stucked in it – Developer Aug 07 '13 at 16:21
  • will u please help me in this – Developer Aug 08 '13 at 05:43
  • This code is not meant to be run inside the adapter, but the parent activity making use of the adapter – rcbevans Aug 08 '13 at 15:07
  • ya i am not running in the inside adapter – Developer Aug 08 '13 at 17:02
0

You can try like this:

after setting adapter for ListView set position to 0 for default selection i.e. listView.setSelection(0); and in onItemClick you get selected position (3rd parameter) of item, so inside onItemClick write listView.setSelection("that 3rd param");

imthegiga
  • 1,126
  • 8
  • 13
  • so the at O position item remains selected and the background is also not changed on the selection of the other item from the listview – Developer Aug 08 '13 at 07:43
0

I have had similar problem with ListView all you do is when item is clicked call a method on adapter, adadpter.SetPosition(position) {mSelectedPsoiton = position; notifyDataSetChanged();}, and in your getView function check if the position is equal to selectedPosition, then set background accordingly this never fails, focus does not work as ur in touch mode always

    //adapter class
  public override View GetView(int position, View convertView, ViewGroup parent) { TextView view = null; int lookupPos = position; if (null == convertView) { view = new TextView(_context); view.SetTextSize(ComplexUnitType.Sp, 20); view.SetPadding(_pixels, _pixels, _pixels, _pixels); } else { view = convertView as TextView; }
        if (position == mSelectedPos )
        {
            view.SetBackgroundResource(Android.Resource.Color.HoloBlueDark);
        }
        else
        {
            view.SetBackgroundResource(Resource.Drawable.listItemSelector);
        }
        return view;
    }
public void SetSelectedPosition(int position) { mSelectedPos = position;
    }
private int mSelectedPos = -1;

// ListView code, _adapter is adapter of listview

listView.SetOnItemClickListener (new OnItemClickListener() { @Override public void onItemClick(AdapterView adapter, View view, int pos, long id) { _adapter.SetSelectionPostion(pos); }

}
GrIsHu
  • 29,068
  • 10
  • 64
  • 102
Pulkit Sethi
  • 1,325
  • 1
  • 14
  • 22
  • made changes, as i am using xamarin so i have c# code tried to make it into java , but everything should be clear from this – Pulkit Sethi Aug 12 '13 at 06:03