我正在尝试通过一个教程,并遇到了一些障碍。教程 实现一个SingleFragmentActivity类来托管一个片段(xml文件与它一起使用。
我的问题是在这个SingleFragmentActivity.java类中,有一个调用setContentView(int)抛出一个错误,它说它无法找到该方法。是不是setContentView(int)是Fragment Class的一部分?
import android.app.Fragment;
import android.app.FragmentManager; import 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();
}
}
}
答案 0 :(得分:1)
.app.Fragment
在onCreateView
中初始化了其视图。基本上,您需要使用inflater来扩展您的视图并将其作为onCreateView
中的根视图返回。
链接中的示例
@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
。
答案 1 :(得分:1)
你做错了。 setContentView(int)适用于Activity
,但您的类正在扩展Fragment,因此您需要对xml进行膨胀并返回onCreateView
这是例如:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout. activity_fragment, container, false);
// Do some Initialization
return view;
}
还有一点,请不要使用Activity命名您的片段类。它会让你感到困惑:)
答案 2 :(得分:1)
setContentView
不是Fragment
的成员。要为片段充气,您需要在充气后将视图返回到onCreateView
:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_layout, container, false);
}