我正在向ListFragment添加标题,但标题不会出现。我尝试添加onCreate和onStart,但我已经设置了我的适配器。我在这里找到了这个Best place to addHeaderView in ListFragment,但它无效。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = getActivity().getLayoutInflater().inflate(R.layout.header,
null);
container.addView(v,0);
rla = new RowListAdapter(getActivity().getLayoutInflater(),
R.layout.itemlayout, rl);
setListAdapter(rla);
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onStart() {
super.onStart();
getListView().setBackgroundResource(R.color.tostadoclaro);
getListView()
.setDivider(getResources().getDrawable(R.drawable.divider));
getListView().setDividerHeight(4);
}
¡¡¡SOLUTION !!!
@Override
public void onActivityCreated(Bundle savedInstanceState) {
View v = getActivity().getLayoutInflater().inflate(R.layout.header,
null);
this.getListView().addHeaderView(v);
rla = new RowListAdapter(getActivity().getLayoutInflater(),
R.layout.itemlayout, rl);
setListAdapter(rla);
super.onActivityCreated(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState){// Empty. Use original.}
答案 0 :(得分:3)
不要将视图添加到容器中。使用addHeaderView(v)。
答案 1 :(得分:0)
完整代码(改编自here):
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView tv = new TextView(getActivity());
tv.setText("Hello");
getListView().addHeaderView(tv);
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,
new String[] { "Hello world" }));
}
@Override
public void onDestroyView() {
setListAdapter(null);
super.onDestroyView();
}