4.8.4 在Android 中fragment中获取上下文

View ret = inflater.inflate(R.layout.fragment_liebie,container,false);

然后 使用 ret.getContext() 就可以了。


++++++++++++++++++++++++++++++++++++++++++++++

public class LeiBieFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, Callback {
    private LeiBieAdapter adapter;
    private ImageView refresh;
    private final static int REFRESH=1;
    private SwipeRefreshLayout swipeRefreshLayout;//下拉刷新
    private Handler handler;
    private ProgressBar progressBar;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View ret = inflater.inflate(R.layout.fragment_liebie,container,false);

        //获取recyclerView,并且设置adapter
        RecyclerView recyclerView = (RecyclerView) ret.findViewById(R.id.leibie_recycleView);
        adapter = new LeiBieAdapter(ret.getContext(),new ArrayList());
        recyclerView.setAdapter(adapter);

        //获取progressBar
        progressBar = (ProgressBar) ret.findViewById(R.id.leibie_progressbars);

        //初始化主线程的handler,为了防止第一次加载的时候有问题,将这个 加载设置为可以刷新的
        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch(msg.what){
                    case REFRESH:
                        run();
                        break;
                }
            }
        };

        Message message = new Message();
        message.what=REFRESH;
        handler.sendMessage(message);

        //获取下拉刷新的组建SwipeRefreshLayout,并且设置监听方法
        swipeRefreshLayout= (SwipeRefreshLayout)ret.findViewById(R.id.leibie_swiperefreshlayout);
        swipeRefreshLayout.setOnRefreshListener(this);
        return ret;
    }

    //handler 里面调用的方法,就是通过HttpUtils请求网络数据,
    public void run(){
        HttpUtils.getLeiBieService().getLeiBie(1446).enqueue(this);
    }

    //HttpUtils请求成功后进行的处理,包括,将ProgressBar 设置不现实,将下拉刷新停止回收回去
    //更新adapter的数据,从而更新recyclerView
    @Override
    public void onResponse(Response response, Retrofit retrofit) {
        //ProgressBar 设置不现实,将下拉刷新停止回收回去
        progressBar.setVisibility(View.GONE);
        swipeRefreshLayout.setRefreshing(false);

        //获取返回的数据,将该数据更新到adapter 中去,
        LeiBieEntity.DataEntity data = response.body().getData();
        List rankinglist = data.getReturnData().getRankinglist();
        adapter.addAll(rankinglist);
    }

    //网络请求失败
    @Override
    public void onFailure(Throwable t) {

        progressBar.setVisibility(View.GONE);
        swipeRefreshLayout.setRefreshing(false);

        t.printStackTrace();
        Toast.makeText(getContext(),"网络调皮了",Toast.LENGTH_LONG).show();
    }

    //下拉刷新的时候执行,给主线程的handler传递一个message
    @Override
    public void onRefresh() {
        Message message = new Message();
        message.what=REFRESH;
        handler.sendMessage(message);
    }
}

你可能感兴趣的:(4,android,应用,系统开发)