简体   繁体   中英

Android - Accessing custom compound view's class from a List Adapter

I'm writing an android alarm application, and I'm having trouble gaining access to a class I created, which is a custom compound view.

So, I have

// Classes
public class AlarmListActivity extends ListActivity{...}
public class AlarmListAdapter extends BaseAdapter{...}

// My custom compound view class, basically 2 labels and a toggle button
// with an onClickListener outside the toggle button also
public class ToggleMenu extends RelativeLayout{...}

// XML
// The XML layout for AlarmListActivity
activity_alarm_list.xml
// The XML layout for ToggleMenu
toggle_menu.xml

The ToggleMenu works fine in other places, but in the AlarmListAdapter, I get an error when I try to convert the inflated view to a ToggleMenu.

public View getView(int position, View view, ViewGroup parent){
    if(view == null){
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.toggle_menu, parent, true);
    }

    view = (ToggleMenu)view;

    <...>

    return view
}

I have tried switch the boolean in inflate(), and it will give me a different error depending on the value. false is a 'cannot convert RelativeLayout to ToggleMenu error', which I believe is due to the fact that RelativeLayout is the root element in toggle_menu.xml.

So I researched and found that true might be what I need, but I get an error of 'java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView'.

Am I trying to access the ToggleMenu class in the adapter's getView() incorrectly?

I was able to fix this a while back, and thought I would post the answer in case some one stumbled on it with the same problem.

I was trying to inflate the compound layout I made for the ToggleMenu, when I should have been inflating an xml file containing only a view.

I created an xml file containing only that, named alarm_list_item, and I switched

view = inflater.inflate(R.layout.toggle_menu, parent, true);

to

view = inflater.inflate(R.layout.alarm_list_item, parent, true);

and the problem was solved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM