展示效果:
展示代码如下:
布局:
1.activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v4.widget.DrawerLayout
android:id="@+id/draw"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="@+id/frag"
/>
<RadioGroup
android:id="@+id/radi"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<RadioButton
android:id="@+id/radi1"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:button="@null"
android:drawableTop="@drawable/sele"
android:text="首页"
android:textSize="20sp"
android:padding="8dp"
android:gravity="center"
/>
<RadioButton
android:id="@+id/radi2"
android:layout_width="0dp"
android:layout_weight="1"
android:drawableTop="@drawable/sele"
android:layout_height="match_parent"
android:button="@null"
android:text="小视频"
android:textSize="20sp"
android:padding="8dp"
android:gravity="center"
/>
<RadioButton
android:id="@+id/radi3"
android:layout_width="0dp"
android:layout_weight="1"
android:drawableTop="@drawable/sele"
android:layout_height="match_parent"
android:button="@null"
android:text="我的"
android:textSize="20sp"
android:padding="8dp"
android:gravity="center"
/>
</RadioGroup>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="left"
android:orientation="vertical"
android:background="#ccc"
>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/celist"
></ListView>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
2.ce_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="horizontal"
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="150dp"
android:layout_height="150dp"
android:id="@+id/img"
/>
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="150dp"
android:gravity="center"
android:textSize="20sp"
android:id="@+id/tit"
/>
</LinearLayout>
3.frag_one.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.design.widget.TabLayout
android:id="@+id/tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
app:tabGravity="fill"
app:tabTextColor="#000"
app:tabMode="fixed"
app:tabSelectedTextColor="@color/r"
app:tabIndicatorColor="@color/c"
/>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="@+id/pager"
/>
</LinearLayout>
4.frag_two.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="25sp"
android:text="页面二"
android:gravity="center"
/>
</LinearLayout>
5.frag_three.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="25sp"
android:text="页面三"
android:gravity="center"
/>
</LinearLayout>
6.tab_one.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<com.handmark.pulltorefresh.library.PullToRefreshListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/pull"
></com.handmark.pulltorefresh.library.PullToRefreshListView>
</LinearLayout>
7.tab_two.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="页面2"
android:textSize="25sp"
/>
</android.support.constraint.ConstraintLayout>
主方法:
1. MainActivity:
package com.bawei.week3;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.bawei.week3.adapter.MyAdapter;
import com.bawei.week3.bean.Datas;
import com.bawei.week3.bean.JsonBean;
import com.bawei.week3.frag.Frag_One;
import com.bawei.week3.frag.Frag_Three;
import com.bawei.week3.frag.Frag_Two;
import com.bawei.week3.http.Http;
import com.google.gson.Gson;
import java.util.ArrayList;
public class MainActivity extends FragmentActivity {
private RadioGroup radi;
private Frag_One f1;
private Frag_Two f2;
private Frag_Three f3;
private ListView list;
private DrawerLayout draw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//找控件
draw = findViewById(R.id.draw);
list = findViewById(R.id.celist);
radi = findViewById(R.id.radi);
//设置默认
radi.check(radi.getChildAt(0).getId());
draw.addDrawerListener(new DrawerLayout.DrawerListener() {
@Override
public void onDrawerSlide(@NonNull View view, float v) {
}
@Override
public void onDrawerOpened(@NonNull View view) {
Toast.makeText(MainActivity.this,"侧拉打开",Toast.LENGTH_LONG).show();
}
@Override
public void onDrawerClosed(@NonNull View view) {
Toast.makeText(MainActivity.this,"侧拉关闭",Toast.LENGTH_LONG).show();
}
@Override
public void onDrawerStateChanged(int i) {
}
});
//管理者
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//添加
f1 = new Frag_One();
f2 = new Frag_Two();
f3 = new Frag_Three();
transaction.add(R.id.frag,f1);
transaction.add(R.id.frag,f2);
transaction.add(R.id.frag,f3);
//显示
transaction.hide(f2).hide(f3).show(f1);
//提交
transaction.commit();
//设置点击切换
radi.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
FragmentTransaction transaction1 = getSupportFragmentManager().beginTransaction();
switch (i){
case R.id.radi1:
transaction1.hide(f2).hide(f3).show(f1);
break;
case R.id.radi2:
transaction1.hide(f1).hide(f3).show(f2);
break;
case R.id.radi3:
transaction1.hide(f2).hide(f1).show(f3);
break;
}
transaction1.commit();
}
});
//判断有没有网络
boolean work = Http.isWork(MainActivity.this);
if(work){
//请求数据
Http.HttpSycTask("http://api.expoon.com/AppNews/getNewsList/type/1/p/1", new Http.calltasks() {
@Override
public void getData(String s) {
//解析
Gson gson=new Gson();
JsonBean jsonBean = gson.fromJson(s, JsonBean.class);
ArrayList<Datas> data = jsonBean.getData();
//适配器
list.setAdapter(new MyAdapter(data,MainActivity.this));
}
});
}
}
}
2.数据库DAO类和MYSQL类:
2.1Dao类:
package com.bawei.week3.sql;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
/**
* @Auther: 祁壮壮
* @Date: 2019/1/14 19:25:27
* @Description:
*/
public class Dao {
private final SQLiteDatabase db;
public Dao(Context con){
Mysql mysql = new Mysql(con);
db = mysql.getWritableDatabase();
}
public long insert(String table, String nullColumnHack, ContentValues values) {
return db.insert(table, nullColumnHack, values);
}
public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy){
return db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
}
}
2.2Mysql类:
package com.bawei.week3.sql;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* @Auther: 祁壮壮
* @Date: 2019/1/14 19:25:40
* @Description:
*/
public class Mysql extends SQLiteOpenHelper {
public Mysql(Context context){
super(context,"bw.db",null,1);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("create table news(id integer primary key autoincrement,name text,tit text,img text)");
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
3.工具类http:
package com.bawei.week3.http;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
/**
* @Auther: 祁壮壮
* @Date: 2019/1/14 19:36:38
* @Description:
*/
public class Http {
//判断有没有网络的方法
public static boolean isWork(Context con){
if (con!=null){
ConnectivityManager manager = (ConnectivityManager)con.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info!=null){
return info.isAvailable();
}
}
return false;
}
//AsyTask方法
public static void HttpSycTask(String str, final calltasks ca){
new AsyncTask<String,Integer,String>(){
@Override
protected String doInBackground(String... strings) {
return Http.isquest(strings[0]);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
ca.getData(s);
}
}.execute(str);
}
public interface calltasks{
void getData(String s);
}
public static String isquest(String strUrl){
try{
URL url = new URL(strUrl);
HttpURLConnection connection =(HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setRequestMethod("GET");
int code = connection.getResponseCode();
if (code==200){
InputStream stream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream,"utf-8"));
StringBuilder builder = new StringBuilder();
String str="";
while ((str=reader.readLine())!=null){
builder.append(str);
}
return builder.toString();
}
connection.disconnect();
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
4.App类:
package com.bawei.week3.app;
import android.app.Application;
import android.graphics.Bitmap;
import android.os.Environment;
import com.bawei.week3.R;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.display.CircleBitmapDisplayer;
import java.io.File;
/**
* @Auther: 祁壮壮
* @Date: 2019/1/14 19:55:25
* @Description:
*/
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
String path = Environment.getExternalStorageDirectory().getPath() + "Tupian";
File file = new File(path);
DisplayImageOptions options=new DisplayImageOptions.Builder()
//加载时的占位图
.showImageOnLoading(R.mipmap.zhan)
//加载失败的失败图
.showImageOnFail(R.mipmap.shibai)
//圆形
.displayer(new CircleBitmapDisplayer())
.bitmapConfig(Bitmap.Config.ARGB_8888)
.build();
ImageLoaderConfiguration configuration=new ImageLoaderConfiguration.Builder(this)
.defaultDisplayImageOptions(options)
//内存缓存的图片的大小
.memoryCacheSize(2*1024*1024)
//内存缓存的图片的尺寸
.memoryCacheExtraOptions(200,200)
//配置加载图片的数量
.threadPoolSize(3)
//配置加载图片的优先级
.threadPriority(1000)
//缓存路径
.diskCache(new UnlimitedDiskCache(file))
//缓存数量
.diskCacheFileCount(50)
//缓存格式
.diskCacheFileNameGenerator(new Md5FileNameGenerator())
.diskCacheSize(50*1024*1024)
.build();
//实例
ImageLoader imageLoader = ImageLoader.getInstance();
//初始化
imageLoader.init(configuration);
}
}
5.MyAdapter类:
package com.bawei.week3.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.bawei.week3.R;
import com.bawei.week3.bean.Datas;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.ArrayList;
/**
* @Auther: 祁壮壮
* @Date: 2019/1/14 20:28:33
* @Description:
*/
public class MyAdapter extends BaseAdapter {
private ArrayList<Datas> arr;
private Context con;
public MyAdapter(ArrayList<Datas> arr, Context con) {
this.arr = arr;
this.con = con;
}
@Override
public int getCount() {
return arr.size();
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder vh;
if(view==null){
view=LayoutInflater.from(con).inflate(R.layout.ce_item,null);
vh=new ViewHolder();
vh.img=view.findViewById(R.id.img);
vh.tit=view.findViewById(R.id.tit);
view.setTag(vh);
}else{
vh= (ViewHolder) view.getTag();
}
vh.tit.setText(arr.get(i).getNews_title());
ImageLoader.getInstance().displayImage(arr.get(i).getPic_url(),vh.img);
return view;
}
static class ViewHolder{
ImageView img;
TextView tit;
}
}
6.frag类:
6.1:Frag_one
package com.bawei.week3.frag;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
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.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bawei.week3.R;
import com.bawei.week3.frag.tab.Tab_One;
import com.bawei.week3.frag.tab.Tab_Two;
import java.util.ArrayList;
/**
* @Auther: 祁壮壮
* @Date: 2019/1/14 20:36:37
* @Description:
*/
public class Frag_One extends Fragment {
private TabLayout tab;
private ViewPager pager;
private ArrayList<Fragment> arr;
private ArrayList<String> tit;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_one,container,false);
tab = view.findViewById(R.id.tab);
pager = view.findViewById(R.id.pager);
arr = new ArrayList<>();
arr.add(new Tab_One());
arr.add(new Tab_Two());
tit = new ArrayList<>();
tit.add("关注");
tit.add("推荐");
pager.setAdapter(new FragmentPagerAdapter(getActivity().getSupportFragmentManager()) {
@Override
public Fragment getItem(int i) {
return arr.get(i);
}
@Override
public int getCount() {
return arr.size();
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return tit.get(position);
}
});
//绑定
tab.setupWithViewPager(pager);
return view;
}
}
6.2:Frag_two
package com.bawei.week3.frag;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bawei.week3.R;
/**
* @Auther: 祁壮壮
* @Date: 2019/1/14 20:37:08
* @Description:
*/
public class Frag_Two extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_two,container,false);
return view;
}
}
6.3Frag_three
package com.bawei.week3.frag;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bawei.week3.R;
/**
* @Auther: 祁壮壮
* @Date: 2019/1/14 20:37:28
* @Description:
*/
public class Frag_Three extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_three,container,false);
return view;
}
}
6.1.1Tab_one
package com.bawei.week3.frag.tab;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;
import com.bawei.week3.R;
import com.bawei.week3.adapter.MyAdapter;
import com.bawei.week3.bean.Datas;
import com.bawei.week3.bean.JsonBean;
import com.bawei.week3.http.Http;
import com.bawei.week3.sql.Dao;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import java.util.ArrayList;
/**
* @Auther: 祁壮壮
* @Date: 2019/1/14 20:37:58
* @Description:
*/
public class Tab_One extends Fragment {
private PullToRefreshListView pull;
private Dao dao;
private String str="http://api.expoon.com/AppNews/getNewsList/type/1/p/2";
private String str1="http://api.expoon.com/AppNews/getNewsList/type/1/p/3";
private MyAdapter adapter;
private ArrayList<Datas> data;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_one,container,false);
pull = view.findViewById(R.id.pull);
pull.setMode(PullToRefreshBase.Mode.BOTH);
pull.setScrollingWhileRefreshingEnabled(true);
dao = new Dao(getActivity());
boolean work = Http.isWork(getActivity());
if (work){
Http.HttpSycTask(str, new Http.calltasks() {
@Override
public void getData(String s) {
Gson gson = new Gson();
JsonBean bean = gson.fromJson(s, JsonBean.class);
data = bean.getData();
if(dao.query("news",null,null,null,null,null,null).moveToFirst()){
}else{
for(Datas beana: data){
ContentValues values=new ContentValues();
values.put("tit",beana.getNews_title());
values.put("img",beana.getPic_url());
values.put("name",beana.getNews_summary());
dao.insert("news",null,values);
}
}
adapter = new MyAdapter(data, getActivity());
pull.setAdapter(adapter);
}
});
}else {
Cursor cursor = dao.query("news",null,null,null,null,null,null);
data = new ArrayList<>();
if (cursor.moveToFirst()){
do {
String img = cursor.getString(cursor.getColumnIndex("img"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String tit = cursor.getString(cursor.getColumnIndex("tit"));
data.add(new Datas(name,tit,img));
}while (cursor.moveToNext());
}
cursor.close();
Toast.makeText(getActivity(),"没有网络",Toast.LENGTH_LONG).show();
adapter = new MyAdapter(data,getActivity());
pull.setAdapter(adapter);
}
pull.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
@Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {//下拉刷新
//判断有没有网络
boolean work1 = Http.isWork(getActivity());
if(work1){
Http.HttpSycTask(str, new Http.calltasks() {
@Override
public void getData(String s) {
//解析
Gson gson=new Gson();
JsonBean bean = gson.fromJson(s, JsonBean.class);
data = bean.getData();
//适配器
adapter = new MyAdapter(data,getActivity());
pull.setAdapter(adapter);
//列表刷新时调用
pull.onRefreshComplete();
}
});
}else {
Toast.makeText(getActivity(),"没有网络",Toast.LENGTH_LONG).show();
}
}
@Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {//上拉加载
//判断有没有网络
if(Http.isWork(getActivity())){
Http.HttpSycTask(str1, new Http.calltasks() {
@Override
public void getData(String s) {
//解析
Gson gson=new Gson();
JsonBean bean = gson.fromJson(s, JsonBean.class);
ArrayList<Datas> data1 = bean.getData();
data.addAll(data1);
adapter.notifyDataSetChanged();
//列表刷新时调用
pull.onRefreshComplete();
}
});
}else{
Toast.makeText(getActivity(),"没有网络",Toast.LENGTH_LONG).show();
}
}
});
return view;
}
}
6.1.2Tab_two
package com.bawei.week3.frag.tab;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bawei.week3.R;
/**
* @Auther: 祁壮壮
* @Date: 2019/1/14 20:38:13
* @Description:
*/
public class Tab_Two extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_two,container,false);
return view;
}
}
7.记住一定要写权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
android:name=".app.App"