Skip to content Skip to sidebar Skip to footer

Android Java: Unable To Selectively Highlight Rows In A Listview Via Onscroll Listener

I have another blocker as I study Android Development. This time my problem is when I wanted to 'selectively' highlight a row in a ListView populated by data from an adapter. This

Solution 1:

Change

ArrayAdapter<String> adapter = newArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stringArray);

to

// Define this at class level as --> private FriendsAdapter adapter = null;
adapter = newFriendsAdapter(Main.this, stringArray);

add this method in your activity

privatevoidsetResetSelection(int index, boolean setSelection){
    Viewv= listview_SelectFriends.getChildAt(index);
    if(v != null){
        TextViewname= (TextView) v.findViewById(R.id.name);
        if(setSelection)
            name.setBackgroundResource(R.color.red);
        else
            name.setBackgroundResource(R.color.transparent);
    }
}

and create a new class as

publicclassFriendsAdapterextendsBaseAdapter {
privateLayoutInflater mInflater;
privateArrayList<String> mFriends;
privateArrayList<String> mSelectedFriends = newArrayList<String>();

publicGoodPeopleAdapter(Context context, ArrayList<String> friends) {
    mInflater = LayoutInflater.from(context);
    mFriends= friends;
}

publicvoidsetSelectedFriends(ArrayList<String> selectedFriends){
    mSelectedFriends = selectedFriends;
}

@Overridepublic int getCount() {
    return mFriends.size();
}

@OverridepublicObjectgetItem(int position) {
    return mFriends.get(position);
}

@Overridepublic long getItemId(int position) {
    return position;
}

@OverridepublicViewgetView(int position, View convertView, ViewGroup parent) {
    View view;
    ViewHolder holder;
    if(convertView == null) {
        view = mInflater.inflate(R.layout.row_layout, parent, false);
        holder = newViewHolder();
        holder.name = (TextView)view.findViewById(R.id.name);
        view.setTag(holder);
    } else {
        view = convertView;
        holder = (ViewHolder)view.getTag();
    }

    String name = mFriends.get(position);
    holder.name.setText(name);

    if(mSelectedFriends.contains(name))
        holder.name.setBackgroundResource(R.color.red) // red is in color xml by default, change according to your choicereturn view;
}

privateclassViewHolder {
    publicTextView name;
}
}

Add following line at the end of method onItemClick

adapter.setSelectedFriends(arr_FriendsShare);

Add this in the if part of onItemClick

setResetSelection(position, true);

and this in else part

setResetSelection(position, false);

Also create a new xml layout with name row_layout with a textview with id name.

Post a Comment for "Android Java: Unable To Selectively Highlight Rows In A Listview Via Onscroll Listener"