Android: addView(View) is not supported in AdapterView

空扰寡人 提交于 2019-12-08 09:34:47

问题


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?


回答1:


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);


来源:https://stackoverflow.com/questions/31142530/android-addviewview-is-not-supported-in-adapterview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!