XCEPTION
XCEPTION

Reputation: 1753

Android Custom ArrayAdapter of list - Java

I am new to android. I have implemented custom ArrayAdapter in my Android Application using view holder. The getView() function of my ArrayAdapter is as follows for reference:

@Override
public View getView(int position, View convertView, final ViewGroup parent) {
    View row = convertView;
    MyClassViewHolder myClassViewHolder;
    MyClass myClass;
    if(row == null) {
        LayoutInflater inflater = ((Activity)mContext).getLayoutInflater();
        row = inflater.inflate(resourceId, parent, false);
        if(resourceId == R.layout.my_row_item) {
            myClassViewHolder = new MyClassViewHolder();
            myClassViewHolder.title = (EditText) row.findViewById(R.id.title);
            myClassViewHolder.switch = (Switch) row.findViewById(R.id.switch);
        }
    } else {
        myViewHolder = (MyViewHolder) row.getTag();
    }
    if(resourceId == R.layout.my_row_item) {
        myClass = (MyClass) myClassList.get(position); //myClassList sent as parameter to constructor of adapter
        if(myClassViewHolder != null && myClass != null) {
            myClassViewHolder.title.setText(myClass.getTitle());
            myClassViewHolder.switch.setChecked(myClass.isEnabled());
            myClassViewholder.id = myClass.getId();
            myClassViewHolder.switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    //GET ID OF THE ROW ITEM HERE
                }
            });
        }
    }
}
  1. First of all I want to associate an id which is from database to every row item to perform actions on them. So please confirm if the way I have done is is right or wrong.
  2. Secondly in the above code I have a String as title and a Switch in every row item. I want to set an onClickListener on each switch. On toggling the switch i want to get the id of the row item which is associated as per point 1.

Thanks in advance. Please let me know if I haven't described my problem properly.

Upvotes: 0

Views: 73

Answers (2)

Darpan
Darpan

Reputation: 5795

You may need to set a tag for each row item and thus you can identify each row. Here is an example -

row.setTag(1);

and to retrive the tag -

row.getTag();

Upvotes: 0

Adrian Totolici
Adrian Totolici

Reputation: 233

Yes your code looks fine as for second part you should make a listener on switch and then get the id form the row and do switch from one id to another.

Upvotes: 1

Related Questions