Search code examples
javaandroidandroid-preferences

Android: addView(View) is not supported in AdapterView


I've got a PreferenceFragment that displays a dynamic list of preferences, implemented like this;

public class ConfigFragment extends PreferenceFragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);

       addPreferencesFromResource(R.xml.settings);

       for(int i = 0; i<items.size();i++) {

          SettingsScreen s = new SettingsScreen(getActivity());

          PreferenceScreen screen = getPreferenceManager().createPreferenceScreen(getActivity());
          screen.setTitle(itemName);
          screen.addPreference(s);
          indicatorCategory.addPreference(screen);
      }
}

SettingsScreen is derived from Preference and shows a custom layout;

public class SettingsScreen extends Preference {

@Override
protected View onCreateView(ViewGroup group) {

    LayoutInflater li = (LayoutInflater)getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );

    View v = li.inflate(R.layout.indicator_config, group, false);

    return v;
}

That works fine thus far. The issue I'm facing now is the when I try to dynamically add views to the SettingsScreen. The following would result in the crash stated in the title (UnsupportedOperationException: addView(View) is not supported in AdapterView);

Button b = new Button(getContext);
group.addView(b);

So how can I dynamically add Views to the SettingsScreen?


Solution

  • Not much going on with Android here on stackoverflow I guess...

    Anyway, to answer my own question; the trick is not to add subviews to the view directly, but rather to the view's layout;

    View v = li.inflate(R.layout.indicator_config, group, false);
    LinearLayout r = (LinearLayout) v.findViewById(R.id.configLayout);
    Button b = new Button(getContext);
    r.addView(b);