1. 程式人生 > >4.8.4 在Android 中fragment中獲取上下文

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<LeiBieEntity> {
    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<LeiBieEntity.DataEntity.ReturnDataEntity.RankinglistEntity>()); 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<LeiBieEntity> response, Retrofit retrofit) { //ProgressBar 設定不現實,將下拉重新整理停止回收回去 progressBar.setVisibility(View.GONE); swipeRefreshLayout.setRefreshing(false); //獲取返回的資料,將該資料更新到adapter 中去, LeiBieEntity.DataEntity data = response.body().getData(); List<LeiBieEntity.DataEntity.ReturnDataEntity.RankinglistEntity> 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); } }