tomss February 2016

List Selection Item

I made a scroll list with multiple items. When I click on one item the color of the background of that item changes.

public class MyList extends Activity {

PackageManager packMan;
public static ArrayList<ItemList> list;
private ArrayAdapter<ItemList> adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.items);
    init();
    create();
    addClickListener();
}

public void init(){
    if(list==null) {
        list = new ArrayList<ItemList>();
        packMan = getPackageManager();
        Intent i = new Intent(Intent.ACTION_MAIN, null);
        i.addCategory("com.example.example");
        List<ResolveInfo> items = packMan.queryIntentActivities(i, 0);
        for (ResolveInfo ri : items) {
            ItemList item = new ItemList();
            item.addName((String) ri.loadLabel(packMan));
            item.addNamePackage(ri.activityInfo.name);
            item.addIcon(ri.activityInfo.loadIcon(packMan));
            list.add(item);
        }
    }
}


private void create(){
    v = (ListView)findViewById(R.id.list);
    adapter = new ArrayAdapter<ItemList>(this, R.layout.items, list) {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if(convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.items, null);
                ImageView icon = (ImageView) convertView.findViewById(R.id.icon);
                icon.setImageDrawable(list.get(position).getIcon());
                TextView name = (TextView) convertView.findViewById(R.id.name);
                name.setText(list.get(position).getName());
            }
            return convertView;
        }
    };
    v.setAdapter(adapter);
}

private void addClickListener(){
    v.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterVi        

Answers


Diego Martinoia February 2016

From your code it seems that on click on an item you set its background to color DDFFFF, but you never switch them back to their original color once "unselected" . You can either:

  • keep track of the only selected item, and switch it back to white before coloring the new one (good if you only have 1 selected item at any time)

  • Whiten everyone on click, and then color the new one

  • Keep track of the state of each item with a list of booleans (active/inactive), and then override the draw loop to color according to their state

Post Status

Asked in February 2016
Viewed 3,699 times
Voted 10
Answered 1 times

Search




Leave an answer