首先将TabLayout依赖包导入工程中
compile 'com.android.support:design:24.2.0'
主布局中
<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"/>
Activity中
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 List<ChannelFragment> mViewList=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<ChannelFragment> mViewList;
public MyFragmentPagerAdapter(FragmentManager fm, List<ChannelFragment> 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];//页卡标题
}
}
创建一个Fragment类继承Fragment,注意创建的Fragment当然不能叫Fragment
public class ChannelFragment extends Fragment{
private String name;
private String news_url;
private PullToRefreshListView pullToRefreshListView;
private List<User.ResultsBean> 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<ListView>() {
@Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
pullToRefreshData();
}
});
//加载
pullToRefreshListView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
@Override
public void onLastItemVisible() {
LoadMoreData();
}
});
return view;
}
//刷新
public void pullToRefreshData(){
new AsyncTask<String,Integer,String>(){
@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<String,Integer,String>(){
@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<User.ResultsBean> results2 = user.getResults();
//上拉添加一遍
results.addAll(results2);
//刷新适配器
adapter.notifyDataSetChanged();
}
}.execute(news_url);
}
}
fragment布局中写PullToRefreshListView
<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"/>
创建要解析的Json串的类进行封装,接着创建一个工具类
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;
}
}
创建适配器MyAdapter:
private List<DataBean.DataBea> list;
private Context context;
private LayoutInflater inflater;
public MyAdapter(List<DataBean.DataBea> list, Context context) {
this.list = list;
this.context = context;
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public int getItemViewType(int position) {
int rs = 0;
if(position%2==0){
rs = 0;
}else if(position%2==1){
rs = 1;
}
return rs;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
int rs = getItemViewType(position);
ViewHoder1 hoder1;
ViewHoder2 hoder2;
if(rs==0){
if(convertView==null){
hoder1 = new ViewHoder1();
convertView = inflater.inflate(R.layout.item1, null);
hoder1.image = (ImageView) convertView.findViewById(R.id.image);
hoder1.tv1 = (TextView) convertView.findViewById(R.id.tv1);
convertView.setTag(hoder1);
}else{
hoder1 = (ViewHoder1) convertView.getTag();
}
ImageLoader.getInstance().displayImage(list.get(position).getImg(),hoder1.image);
hoder1.tv1.setText(list.get(position).getUserAge()+"\n"+list.get(position).getTopTime()+"\n"+
list.get(position).getRecommend()+"\n"+list.get(position).getUrl()+"\n"+
list.get(position).getCreateTime()+"\n"+list.get(position).getHxKey()+"\n"+
list.get(position).getYulin()+"\n"+list.get(position).getStar()+"\n"+
list.get(position).getTitle()+"\n"+list.get(position).getOccupation()+"\n"+
list.get(position).getImpressEditId()+"\n"+list.get(position).getImpressType()+"\n"+
list.get(position).getReplyTimes()+"\n"+list.get(position).getRemark()+"\n"+
list.get(position).getClick()+"\n"+list.get(position).getIntroduction()+"\n"+
list.get(position).getSource()+"\n"+list.get(position).getUserName()+"\n"+
list.get(position).getReporter()+"\n"+list.get(position).getStatus()+"\n"+
list.get(position).getContent());
}else if(rs==1){
if(convertView==null){
hoder2 = new ViewHoder2();
convertView = inflater.inflate(R.layout.item2, null);
hoder2.tv2 = (TextView) convertView.findViewById(R.id.tv2);
convertView.setTag(hoder2);
}else{
hoder2 = (ViewHoder2) convertView.getTag();
}
hoder2.tv2.setText(list.get(position).getUserAge()+"\n"+list.get(position).getTopTime()+"\n"+
list.get(position).getRecommend()+"\n"+list.get(position).getUrl()+"\n"+
list.get(position).getCreateTime()+"\n"+list.get(position).getHxKey()+"\n"+
list.get(position).getYulin()+"\n"+list.get(position).getStar()+"\n"+
list.get(position).getTitle()+"\n"+list.get(position).getOccupation()+"\n"+
list.get(position).getImpressEditId()+"\n"+list.get(position).getImpressType()+"\n"+
list.get(position).getReplyTimes()+"\n"+list.get(position).getRemark()+"\n"+
list.get(position).getClick()+"\n"+list.get(position).getIntroduction()+"\n"+
list.get(position).getSource()+"\n"+list.get(position).getUserName()+"\n"+
list.get(position).getReporter()+"\n"+list.get(position).getStatus()+"\n"+
list.get(position).getContent());
}
return convertView;
}
class ViewHoder1{
ImageView image;
TextView tv1;
}
class ViewHoder2{
TextView tv2;
}
给PIllToRefreshListView加优化需要在写俩个子布局
第一个
<ImageView
android:id="@+id/image"
android:layout_width="60dp"
android:layout_height="60dp" />
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
第二个
<TextView
android:id="@+id/text2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
在创建一个类用来网络加载图片
public class MyApp extends Application{
@Override
public void onCreate() {
super.onCreate();
//默认加载图片
ImageLoaderConfiguration configuration=ImageLoaderConfiguration.createDefault(this);
ImageLoader.getInstance().init(configuration);
}
}