Skip to content Skip to sidebar Skip to footer

How To Mark Views In A Listview?

I have an app with a list view. The listview works fine. The problem starts, when I want the list to start with some of the rows marked. I can mark a row, if I press on it. But, d

Solution 1:

You can achive this by using custom adapter. Here is the workaround.

  • Initialize your custom adapter
  • Add some flag for marked device names.
  • Override the getView() & check for the flag. And set the background of the list item accordingly.

Reply if you don't get it or face any complexity.

Update:

Here is a sample adapter. I didn't compile the code. So there might be some errors.

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

publicclassTestAdapterextendsBaseAdapter
{
    ArrayList<String> deviceNames;
    ArrayList<Boolean> selected;
    Context context;

    publicTestAdapter(Context context)
    {
        this.context = context;
        deviceNames = newArrayList<String>();
        selected = newArrayList<Boolean>();
    }

    publicvoidaddDeviceToList(String deviceName, boolean isSelected)
    {
        deviceNames.add(deviceName);
        selected.add(isSelected);
        notifyDataSetChanged();
    }

    public int getCount()
    {
        return deviceNames.size();
    }

    publicObjectgetItem(int position)
    {
        return deviceNames.get(position);
    }

    public long getItemId(int position)
    {
        return position;
    }

    publicViewgetView(int position, View convertView, ViewGroup parent)
    {
        TextView tv = newTextView(context);
        tv.setText(deviceNames.get(position));
        if(selected.get(position) == true)
        {
            tv.setBackgroundColor(Color.parseColor("#ff0000"));
        }
        return tv;
    }
}

Now create adapter object and set the adapter to listView. And add single item by calling addDeviceToList() method.

Solution 2:

That seems to nasty but i think you want to modify the views inside listview before loading it

The thing is, that your list won't have children as long as the list is not displayed to the user.so you may not modify the view before showing it to the user

But if you really need to communicate with the views on a such low level you could try to attach a scroll listener to your list:

@OverridepublicvoidonScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
    for (inti=0; i < visibleItemCount; i++) {
        Viewchild= getChildAt(i);
        Now edit this view 

    }
}

Post a Comment for "How To Mark Views In A Listview?"