Fragment用findViewById得到空值解决办法

来源:互联网 发布:mac怎样新建文件夹 编辑:程序博客网 时间:2024/06/06 00:40

参考:http://www.cnblogs.com/Ken-Cai/p/4186660.html

public class CompanyListFragment  extends Fragment {  private Activity activity;   private ListView companyListView;  @Override  public View onCreateView(LayoutInflater infalter, ViewGroup container, Bundle savedInstanceState) {    View view = infalter.inflate(R.layout.companylist_for_sport, container, false);    companyListView = (ListView)view.findViewById(R.id.companyListView);    return view;  }}

注意1:  是在 onCreateView 中

注意2:  是 view.findViewById 而不是 activity.findViewById


为了能在别的方法中调用,最好写成:

public class CompanyListFragment  extends Fragment {  private Activity activity;   private ListView companyListView;    private View view;  @Override  public View onCreateView(LayoutInflater infalter, ViewGroup container, Bundle savedInstanceState) {    view = infalter.inflate(R.layout.companylist_for_sport, container, false);    companyListView = (ListView)view.findViewById(R.id.companyListView);    return view;  }    public void mothedA(){        ListView = (ListView)view.findViewById(R.id.companyListView);    }}


0 0