TabLayout和ViewPager实现联动效果以及Pulltorefresh。
先上效果图
<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" > <android.support.design.widget.TabLayout android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabIndicatorColor="@color/red" app:tabMode="scrollable" app:tabSelectedTextColor="@color/red" app:tabTextColor="@color/black"/> <android.support.v4.view.ViewPager android:id="@+id/vp_view" android:layout_width="wrap_content" android:layout_height="wrap_content"/> LinearLayout>
接下来是MyActivity里的视图
public class MainActivity extends AppCompatActivity { private TabLayout mTabLayout; private ViewPager mViewPager; private String[] channels = {"推荐","热点","体育","娱乐","社会","汽车","教育","财经","科技","游戏"}; private String[] Urls={ "http://gank.io/api/data/Android/10/1", "http://gank.io/api/data/Android/10/1", "http://gank.io/api/data/Android/10/1", "http://gank.io/api/data/Android/10/1", "http://gank.io/api/data/Android/10/1", "http://gank.io/api/data/Android/10/1", "http://gank.io/api/data/Android/10/1", "http://gank.io/api/data/Android/10/1", "http://gank.io/api/data/Android/10/1", "http://gank.io/api/data/Android/10/1", }; private LayoutInflater mInflater; private ListmViewList=new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTabLayout = (TabLayout) findViewById(R.id.tabs); mViewPager = (ViewPager) findViewById(R.id.vp_view); mInflater = LayoutInflater.from(this); for (int i = 0; i < channels.length; i++) { //创建栏目的fragment ChannelFragment fragment = new ChannelFragment(); Bundle b = new Bundle(); b.putString("name", channels[i]);//传递名字 b.putString("url", Urls[i]); fragment.setArguments(b); //收集fragment mViewList.add(fragment); //给tablayout添加tab选项卡 mTabLayout.addTab(mTabLayout.newTab().setText(channels[i]));//添加tab选项卡 } FragmentManager fm = getSupportFragmentManager(); MyFragmentPagerAdapter adapter=new MyFragmentPagerAdapter(fm,mViewList); mViewPager.setAdapter(adapter);//关联适配器 mTabLayout.setupWithViewPager(mViewPager);//将Tablayout与Viewpager建立连接 } class MyFragmentPagerAdapter extends FragmentPagerAdapter { private List mViewList; public MyFragmentPagerAdapter(FragmentManager fm, List mViewList) { super(fm); this.mViewList = mViewList; } @Override public Fragment getItem(int position) { return mViewList.get(position); } @Override public int getCount() { return mViewList.size(); } @Override public CharSequence getPageTitle(int position) { return channels[position];//页卡标题 } } }
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <com.handmark.pulltorefresh.library.PullToRefreshListView xmlns:ptr="http://schemas.android.com/apk/res-auto" android:id="@+id/pull_refresh_list" android:layout_width="fill_parent" android:layout_height="fill_parent" android:cacheColorHint="#000000" android:divider="#19000000" android:dividerHeight="4dp" android:fadingEdge="none" android:fastScrollEnabled="false" android:footerDividersEnabled="false" android:headerDividersEnabled="false" android:smoothScrollbar="true" ptr:ptrAnimationStyle="rotate" ptr:ptrHeaderTextColor="#ffffff" ptr:ptrHeaderSubTextColor="#00ffff" ptr:ptrHeaderBackground="@null" ptr:ptrDrawable="@mipmap/ic_launcher"/> LinearLayout>多条目一的视图
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/image" android:layout_width="60dp" android:layout_height="60dp" /> <TextView android:id="@+id/text" android:textSize="20sp" android:layout_width="match_parent" android:layout_height="wrap_content" /> LinearLayout>
多条目二的视图
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/text2" android:textSize="20sp" android:layout_width="match_parent" android:layout_height="wrap_content" /> LinearLayout>
ChannelFreament的类 建立导航栏
public class ChannelFragment extends Fragment{ private String name; private String news_url; private PullToRefreshListView pullToRefreshListView; private List上拉下拉的适配器results; private PullOnRefreshAdapter adapter; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); //接受传过来的值 Bundle bundle = getArguments(); name = (String) bundle.get("name"); news_url = (String) bundle.get("url"); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view=inflater.inflate(R.layout.fragment,null); //获取资源ID pullToRefreshListView=(PullToRefreshListView) view.findViewById(R.id.pull_refresh_list); pullToRefreshData(); //刷新 pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener () { @Override public void onRefresh(PullToRefreshBase refreshView) { pullToRefreshData(); } }); //加载 pullToRefreshListView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() { @Override public void onLastItemVisible() { LoadMoreData(); } }); return view; } //刷新 public void pullToRefreshData(){ new AsyncTask (){ @Override protected String doInBackground(String... strings) { //解析 String str=new NetWorksUtils().getJsonUrlJiexi(news_url+"1"); return str; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); Gson gson = new Gson(); User user = gson.fromJson(s, User.class); results = user.getResults(); //关联适配器 adapter=new PullOnRefreshAdapter(results,getActivity()); pullToRefreshListView.setAdapter(adapter); //停止刷新 pullToRefreshListView.onRefreshComplete(); } }.execute(news_url); } //加载 public void LoadMoreData(){ new AsyncTask (){ @Override protected String doInBackground(String... strings) { //解析 String str=new NetWorksUtils().getJsonUrlJiexi(news_url+"1"); return str; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); Gson gson = new Gson(); User user = gson.fromJson(s, User.class); //新集合 List results2 = user.getResults(); //上拉添加一遍 results.addAll(results2); //刷新适配器 adapter.notifyDataSetChanged(); } }.execute(news_url); } }
public class PullOnRefreshAdapter extends BaseAdapter{ private Listlist; private Context context; public PullOnRefreshAdapter(List list, Context context) { this.list = list; this.context = context; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int i) { return list.get(i); } @Override public long getItemId(int i) { return i; } @Override public int getViewTypeCount() { return 2; } //多条目 @Override public int getItemViewType(int position) { int rs=0; if(list.get(position).getImages()==null){ rs=0; }else if (list.get(position).getImages()!=null){ rs=1; } return rs; } @Override public View getView(int i, View view, ViewGroup viewGroup) { int rs=getItemViewType(i); //等于1有图片展示 if(rs==1){ view=View.inflate(context, R.layout.item,null); ImageView imageView=(ImageView) view.findViewById(R.id.image); TextView textView=(TextView) view.findViewById(R.id.text); textView.setText(list.get(i).getDesc()+"\n"+list.get(i).getCreatedAt()); ImageLoader.getInstance().displayImage(list.get(i).getImages().get(0),imageView); }else if (rs==0){//等于0没有图片 view=View.inflate(context, R.layout.item2,null); TextView textView2=(TextView) view.findViewById(R.id.text2); textView2.setText(list.get(i).getDesc()+"\n"+list.get(i).getCreatedAt()); } return view; } }
public class MyApp extends Application{ @Override public void onCreate() { super.onCreate(); //默认加载图片 ImageLoaderConfiguration configuration=ImageLoaderConfiguration.createDefault(this); ImageLoader.getInstance().init(configuration); } }
public class NetWorksUtils { //解析的方法 public String getJsonUrlJiexi(String jsonStr){ URL url=null; HttpURLConnection httpURLConnection=null; String JsonUrl=""; try { //进行网络解析 url=new URL(jsonStr); httpURLConnection= (HttpURLConnection) url.openConnection(); httpURLConnection.setConnectTimeout(5000); httpURLConnection.setReadTimeout(5000); //获取响应码 int responseCode = httpURLConnection.getResponseCode(); if (responseCode==200){ InputStream inputStream = httpURLConnection.getInputStream(); byte[] bytes = new byte[1024]; int i=0; while ((i=inputStream.read(bytes))!=-1){ JsonUrl +=new String(bytes,0,i); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return JsonUrl; } }