Android视图/片段问题

时间:2013-04-09 16:17:59

标签: java android fragment

所以当我按下特定按钮时,我试图在ListView中加载不同的内容,但它只加载我尝试加载的第一个(并且只有在我按下它两次之后)。我找不到我做错了什么。

这是创建视图的代码,我展示了内容:

public class ContentQuery extends Fragment {
    private List<String> contents_list = new ArrayList<String>();
    public static final String TAG = contentQuery.class.getSimpleName();
    private String uri = "";

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View lv = inflater.inflate(R.layout.contents_list, container, false);
        super.onActivityCreated(savedInstanceState);
        getContent(); // Sets contents_list
        ((ListView) lv).setAdapter(new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, contents_list));
        return lv;
    }
}

我认为这可能是因为我应该以某种方式摧毁它但我对android dev来说还是新手。

tag = ContentQuery.TAG;
ContentQuery contentqueryfragment = null;
final Fragment foundFragment = fm.findFragmentByTag(tag);
if (foundFragment != null && uri != old_uri) {
    fragment = foundFragment;
    contentqueryfragment = (ContentQuery) fragment;
    old_uri = uri;          
} else {
    contentqueryfragment = new ContentQuery();
    contentqueryfragment.setUri(uri.toString());
    fragment = contentqueryfragment;
}

之后:

if (fragment.isAdded())
{
    tr.show(fragment);
} else
{
    tr.remove(fragment);
    tr.add(R.id.content, fragment, tag);
    tr.show(fragment);

}
tr.commit();

currentUri = uri;
currentContentFragmentTag = tag;

1 个答案:

答案 0 :(得分:0)

如果需要更新List中的内容,一个好的方法是分离List,ListAdapter和ListView。当需要更新数据时,更新列表的内容并通知适配器列表内容已更改。

例如

ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, contents_list);
((ListView) lv).setAdapter(adapter);

...

button.onClickListener(...) {
   contents_list.clear();

   ... populate list with new data ...

   adapter.notifyDataSetChanged();
}