Android FindFragmentById 返回值总是null

package com.text.fragmentbestpractice;

import java.util.ArrayList;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class TitleFragment extends Fragment implements OnItemClickListener{
private ArrayList newslist;
private TitileAdapter newsAdapter;
private ListView newsTitleListView;
private boolean istwoPane;
public void onAttach(Activity activity){
super.onAttach(activity);
newslist=setNews();
newsAdapter=new TitileAdapter(activity,R.layout.newsitem,newslist);
}
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){
View view=inflater.inflate(R.layout.newslist, container,false);
newsTitleListView=(ListView)view.findViewById(R.id.newslist_view);
newsTitleListView.setAdapter(newsAdapter);
newsTitleListView.setOnItemClickListener(this);
return view;

}
public void onActivityCreated(Bundle savedInstanceState){
    super.onActivityCreated(savedInstanceState);
    if(getActivity().findViewById(R.id.news_content_layout1)!=null){
    //为双页显示
        istwoPane=true;
    }else{
        istwoPane=false;
    }
}

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    // TODO 自动生成的方法存根
    News news=newslist.get(position);
    if(istwoPane){
        ContextFragment newContentFragment=(ContextFragment)getFragmentManager().findFragmentById(R.id.newcontext11); //**为什么getFragmentManager().findFragmentById返回值总是null**
        if(newContentFragment==null){
            Log.e("MyFragment", "newContentFragment is null");
            return;
        }
        newContentFragment.refresh(news.getTitle(), news.getContext());

    }else{
        NewsContextActivity.actionStart(getActivity(), news.getTitle(), news.getContext());
    }
}
public ArrayList<News> setNews(){
    newslist=new ArrayList<News>();
    News news1=new News();
    news1.setTitle("Android is Winner");
    news1.setContext("Android is Winner");
    newslist.add(news1);
    News news2=new News();
    news2.setTitle("Google Android exec poached by China's Xiaomi");
    news2.setContext("China's Xiaomi has poached a key Google executive for the rapidly growing Chinese smartphone maker.");
    newslist.add(news2);
    return newslist;
}

}


查看全部
VickyWinner
VikcyWinner
2015/08/04 13:35
  • android
  • 点赞
  • 收藏
  • 回答
    私信

2个回复