動態新增Fragment程式碼
阿新 • • 發佈:2019-02-14
Fragment是activity的介面中的一部分或一種行為。可以把多個Fragment組合到一個activity中來建立一個多介面並且可以在多個activity中重用一個Fragment。可以把Fragment任務模組化的一段activity,它具有自己的生命週期,接收它自己的事件,並可以在activity執行時被新增或刪除.
一.在MainActivity中(TabLayput與ViewPager結合使用)
package com.example.a12_tablayout_viewpager; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import java.util.ArrayList; import java.util.List; /** * tablayout結合著viewPager來使用 */ public class MainActivity extends AppCompatActivity { private TabLayout tabLayout; private ViewPager viewPager; private List<String> list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tabLayout = (TabLayout) findViewById(R.id.tab_layout); viewPager = (ViewPager) findViewById(R.id.view_pager); /** * top(頭條,預設),shehui(社會),guonei(國內),guoji(國際),yule(娛樂),tiyu(體育)junshi(軍事) * ,keji(科技),caijing(財經),shishang(時尚) */ //tab的標題 list = new ArrayList<>(); list.add("福利"); list.add("Android"); list.add("iOS"); list.add("休息視訊"); list.add("拓展資源"); list.add("前端"); list.add("all"); //Viewpager要展示頁面...設定介面卡 //初始化fragment頁面介面卡 =》new FragmentPagerAdapter //獲取fragment 管理器=》getSupportFragmentManager //getpagetitle 獲取當前頁面顯示的標題是tab對應的標題 position 當前頁面的標誌 //getItem 獲取當前位置對應的fragment viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) { //得到當前頁的標題,,,也就是設定當前頁面顯示的標題是tab對應的標題 @Override public CharSequence getPageTitle(int position) { return list.get(position); } @Override public Fragment getItem(int position) { //一般我們在這個位置對比一下標題是什麼,,,然後返回對應的fragment //初始化fragment 對應position有多少,fragment有多少 NewsFragment newsFragment = new NewsFragment(); //初始化bundle (資料盒子,裝資料元素) Bundle bundle = new Bundle(); //Fragment fragment = null; if (list.get(position).equals("福利")){ //fragment = new TouTiaoFragment(); bundle.putString("name","福利"); }else if (list.get(position).equals("Android")){ bundle.putString("name","Android"); }else if (list.get(position).equals("iOS")){ bundle.putString("name","iOS"); }else if (list.get(position).equals("休息視訊")){ bundle.putString("name","休息視訊"); }else if (list.get(position).equals("拓展資源")){ bundle.putString("name","拓展資源"); }else if (list.get(position).equals("前端")){ bundle.putString("name","前端"); }else if (list.get(position).equals("all")){ bundle.putString("name","all"); } //給fragment 加bundle 資料 //activity與fragment 1.getset,2.介面回撥,3.setArguments ,getAraguments newsFragment.setArguments(bundle); return newsFragment; } @Override public int getCount() { return list.size(); } }); //tablayout要與viewpager關聯 tabLayout.setupWithViewPager(viewPager); } }
二.在Fragment中
package com.example.a12_tablayout_viewpager; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import com.google.gson.Gson; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshListView; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; public class NewsFragment extends Fragment { private PullToRefreshListView listView; private String pagesize="20"; private int page=1; private String mstrings; @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2) @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.news_layout, container, false); listView = (PullToRefreshListView) view.findViewById(R.id.list_view); listView.getRefreshableView(); listView.setMode(PullToRefreshBase.Mode.BOTH); listView.setScrollingWhileRefreshingEnabled(true); listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() { // //完成下拉重新整理操作 @Override public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) { refreshView.postDelayed(new Runnable() { @Override public void run() { page=1; getDataFromNet(mstrings,pagesize,page); listView.onRefreshComplete(); } }, 2000); } //完成上拉重新整理操作 @Override public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) { page++; refreshView.postDelayed(new Runnable() { @Override public void run() { if(mstrings!=null&&pagesize!=null){ getDataFromNet(mstrings,pagesize,page); } listView.onRefreshComplete(); } }, 2000); } }); /* //獲取帶有重新整理的對應控制元件 2 pullToRefreshListView.getRefreshableView(); 3 *//** 4 * 設定重新整理的模式:常用的有三種 5 * PullToRefreshBase.Mode.BOTH //上下拉重新整理都可以 6 * PullToRefreshBase.Mode.PULL_FROM_START //只允許下拉重新整理 7 * PullToRefreshBase.Mode.PULL_FROM_END //只允許上拉重新整理 8 * 9 *//* 10 pullToRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_END); 11 //設定是否允許重新整理的時候可以滑動 12 pullToRefreshListView.setScrollingWhileRefreshingEnabled(true);*/ // PullToRefreshBase.Mode.BOTH //上下拉重新整理都可以 return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Bundle bundle = getArguments(); mstrings = bundle.getString("name", "福利"); getDataFromNet(mstrings,pagesize,page); } private void getDataFromNet(final String string,final String pagesize,final int page) { AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... voids) { String path = "http://gank.io/api/data/"+string+"/"+pagesize+"/"+page+""; try { URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //設定 connection.setRequestMethod("GET"); connection.setReadTimeout(7000); connection.setConnectTimeout(7000); //獲取 int responseCode = connection.getResponseCode(); if (responseCode == 200){ InputStream inputStream = connection.getInputStream(); String json = streamToString(inputStream,"utf-8"); return json; } } catch (Exception e) { e.printStackTrace(); } return ""; } @Override protected void onPostExecute(String json) { //原生json Gson gson = new Gson(); DataDataBean dataDataBean = gson.fromJson(json, DataDataBean.class); List<DataDataBean.ResultsBean> list = dataDataBean.getResults(); if(list!=null){ MyAdapter myAdapter = new MyAdapter(getActivity(), list); listView.setAdapter(myAdapter); } } }; asyncTask.execute(); } private String streamToString(InputStream inputStream,String charset) { try { InputStreamReader inputStreamReader = new InputStreamReader(inputStream,charset); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String s = null; StringBuilder builder = new StringBuilder(); while ((s = bufferedReader.readLine()) != null){ builder.append(s); } bufferedReader.close(); return builder.toString(); } catch (Exception e) { e.printStackTrace(); } return null; } class Myasyn extends AsyncTask<String,String,String>{ @Override protected String doInBackground(String... params) { return null; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); } } }