我有一个PreferenceFragment,它显示了动态的首选项列表,像这样实现;

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派生自Preference并显示自定义布局;

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


到目前为止,一切正常。我现在面临的问题是尝试将视图动态添加到SettingsScreen时的问题。
以下内容将导致标题中所述的崩溃(AdapterView不支持UnsupportedOperationException:addView(View));

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


那么如何动态地将视图添加到SettingsScreen?

最佳答案

我想在这里stackoverflow上与Android没什么关系...

无论如何,回答我自己的问题;诀窍不是直接在视图中添加子视图,而是在视图的布局中添加子视图;

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

07-24 09:26