我正在尝试完成一个教程,并且遇到了一些麻烦。本教程
 实现一个SingleFragmentActivity类来托管一个片段(带有xml文件)。

我的问题在这个SingleFragmentActivity.java类中,有一个对setContentView(int)的调用,该调用引发错误,它说无法找到该方法。 setContentView(int)是否不是Fragment类的一部分?

import android.app.Fragment;


导入android.app.FragmentManager;
导入android.os.Bundle;

public abstract class SingleFragmentActivity extends Fragment {
   protected abstract Fragment createFragment();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fragment);

    FragmentManager manager = getFragmentManager();
    Fragment fragment = manager.findFragmentById(R.id.fragmentContainer);

    if (fragment == null) {
        fragment = createFragment();
        manager.beginTransaction()
            .add(R.id.fragmentContainer, fragment)
            .commit();
    }
  }
}

最佳答案

.app.Fragment的视图已在onCreateView中初始化。基本上,您需要使用充气器来充气您的视图并将其作为onCreateView中的根视图返回。

Reference

链接中的示例

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    if (container == null) {
        // We have different layouts, and in one of them this
        // fragment's containing frame doesn't exist.  The fragment
        // may still be created from its saved state, but there is
        // no reason to try to create its view hierarchy because it
        // won't be displayed.  Note this is not needed -- we could
        // just run the code below, where we would create and return
        // the view hierarchy; it would just never be used.
        return null;
    }

    ScrollView scroller = new ScrollView(getActivity());
    TextView text = new TextView(getActivity());
    int padding = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
            4, getActivity().getResources().getDisplayMetrics());
    text.setPadding(padding, padding, padding, padding);
    scroller.addView(text);
    text.setText(Shakespeare.DIALOGUE[getShownIndex()]);
    return scroller;
}


此外,如果要使用setContentView,请在支持库中使用FragmentActivity

关于java - setContentView(int)不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26457807/

10-10 04:08