先添加依赖
//fresco 依赖 implementation 'com.facebook.fresco:fresco:1.9.0' //recyclerView的依赖 compile 'com.android.support:recyclerview-v7:26+' //xRecyclerView的依赖 compile 'com.jcodecraeer:xrecyclerview:1.5.9' // OkHttp implementation 'com.squareup.okhttp3:okhttp:3.9.0' //Gson implementation 'com.google.code.gson:gson:2.6.2' implementation 'org.greenrobot:greendao:3.2.2' //省去findViewbyid implementation 'com.jakewharton:butterknife:8.8.1' annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
主布局
<?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.DrawerLayout 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:id="@+id/drawerlayout" android:layout_width="match_parent" android:layout_height="match_parent" > <!-- 主界面 --> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <android.support.v4.view.ViewPager android:id="@+id/main_vp" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"></android.support.v4.view.ViewPager> <RadioGroup android:id="@+id/main_rg" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <RadioButton android:id="@+id/one" android:layout_width="0dp" android:layout_height="40dp" android:layout_weight="1" android:text="推荐" android:button="@null" /> <RadioButton android:id="@+id/two" android:layout_width="0dp" android:layout_height="40dp" android:layout_weight="1" android:text="段子" android:button="@null" /> <RadioButton android:id="@+id/three" android:layout_width="0dp" android:layout_height="40dp" android:layout_weight="1" android:text="发现" android:button="@null" /> <RadioButton android:id="@+id/si" android:layout_width="0dp" android:layout_height="40dp" android:layout_weight="1" android:text="视频" android:button="@null" /> </RadioGroup> </LinearLayout> </android.support.v4.widget.DrawerLayout>
OkHttp
public class OkHttpUtils { private static OkHttpUtils okHttpUtils; private final Handler mhandler; private OkHttpClient client ; private OkHttpUtils(){ // //日志拦截器 // HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(); // httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); mhandler = new Handler(Looper.getMainLooper()); client = new OkHttpClient.Builder() .connectTimeout(5000, TimeUnit.MILLISECONDS) .writeTimeout(5000, TimeUnit.MILLISECONDS) .readTimeout(5000, TimeUnit.MILLISECONDS) // .addInterceptor(httpLoggingInterceptor) .build(); } public static OkHttpUtils getInstance(){ if (okHttpUtils==null){ synchronized (OkHttpUtils.class){ if (okHttpUtils==null){ return okHttpUtils=new OkHttpUtils(); } } } return okHttpUtils; } public void doGet(String url, final OkCallback okCallback) { Request request = new Request.Builder() .get() .url(url) .build(); final Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, final IOException e) { if (okCallback != null) { //切换到主线程 mhandler.post(new Runnable() { @Override public void run() { okCallback.getFailure(e); } }); } } @Override public void onResponse(Call call, final Response response) throws IOException { try { if (response != null && response.isSuccessful()) { final String json = response.body().string(); mhandler.post(new Runnable() { @Override public void run() { if (okCallback != null) { okCallback.getResponse(json); return; } } }); } } catch (IOException e) { e.printStackTrace(); } } }); } public void doPost(String url, Map<String,String> map, final OkCallback okCallback){ FormBody.Builder builder = new FormBody.Builder(); for (String key:map.keySet()) { builder.add(key,map.get(key)); } FormBody formBody = builder.build(); Request request = new Request.Builder() .post(formBody) .url(url) .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, final IOException e) { if (okCallback!=null){ mhandler.post(new Runnable() { @Override public void run() { okCallback.getFailure(e); } }); } } @Override public void onResponse(Call call, final Response response) throws IOException { mhandler.post(new Runnable() { @Override public void run() { try { if (response!=null && response.isSuccessful()){ String s = response.body().string(); if (okCallback!=null){ okCallback.getResponse(s); return; } } }catch (Exception e){ e.printStackTrace(); } if (okCallback!=null){ okCallback.getFailure(new Exception("网络异常")); } } }); } }); } public interface OkCallback{ void getFailure(Exception e); void getResponse(String josn); } }
Fragment适配器
public class MyFragmentAdapter extends FragmentPagerAdapter { private List<Fragment> list; public MyFragmentAdapter(FragmentManager fm, List<Fragment> list) { super(fm); this.list = list; } @Override public Fragment getItem(int position) { return list.get(position); } @Override public int getCount() { return list.size(); } }
MainActivity
public class MainActivity extends AppCompatActivity { private DaoSession daoSession; private PersonDao personBeanDao; int a=5; private ViewPager viewPager; private List<Fragment> fs=new ArrayList<>(); private RadioGroup radioGroup; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); datas(); } private void datas() { TuiJianFragment tuiJianFragment = new TuiJianFragment(); FaXianFragment faXianFragment = new FaXianFragment(); ShiPinFragment shiPinFragment = new ShiPinFragment(); DuanZiFragment duanZiFragment = new DuanZiFragment(); fs.add(tuiJianFragment); fs.add(duanZiFragment); fs.add(faXianFragment); fs.add(shiPinFragment); MyFragmentAdapter myFragmentAdapter = new MyFragmentAdapter(getSupportFragmentManager(), fs); viewPager.setAdapter(myFragmentAdapter); viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { switch (position){ case 0: radioGroup.check(R.id.one); break; case 1: radioGroup.check(R.id.two); break; case 2: radioGroup.check(R.id.three); break; case 3: radioGroup.check(R.id.si); break; } } @Override public void onPageScrollStateChanged(int state) { } }); } private void initView() { viewPager=findViewById(R.id.main_vp); radioGroup=findViewById(R.id.main_rg); radioGroup.check(R.id.one); radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId){ case R.id.one: viewPager.setCurrentItem(0); break; case R.id.two: viewPager.setCurrentItem(1); break; case R.id.three: viewPager.setCurrentItem(2); break; case R.id.si: viewPager.setCurrentItem(3); break; } } }); } }
其中一个Fragment 。xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent"> <LinearLayout android:id="@+id/line" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:background="#0099ff" > <Button android:layout_width="50dp" android:layout_height="wrap_content" android:background="@drawable/user_icon" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="段子" android:gravity="center_horizontal" android:layout_marginLeft="110dp" android:textColor="#fff" /> <Button android:layout_width="80dp" android:layout_height="50dp" android:background="@drawable/edit_icon" android:layout_marginLeft="110dp" /> </LinearLayout> <com.jcodecraeer.xrecyclerview.XRecyclerView android:id="@+id/xrv" android:layout_width="match_parent" android:layout_height="match_parent" > </com.jcodecraeer.xrecyclerview.XRecyclerView> </LinearLayout>
Fragment 的子xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_height="wrap_content"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <com.facebook.drawee.view.SimpleDraweeView android:id="@+id/duanzi_img" android:layout_width="50dp" android:layout_height="50dp" app:roundAsCircle="true" android:background="@mipmap/ic_launcher" /> <LinearLayout android:layout_width="wrap_content" android:orientation="vertical" android:layout_height="wrap_content"> <TextView android:id="@+id/duanzi_tv1" android:text="textetetete" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/duanzi_riqi" android:text="riqiriqiriqi" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <ImageView android:id="@+id/duanzi_add" android:src="@drawable/add_icon" android:layout_width="30dp" android:layout_marginTop="20dp" android:layout_marginLeft="200dp" android:layout_height="30dp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:orientation="vertical" android:layout_height="wrap_content"> <TextView android:id="@+id/duanzi_tv2" android:text="r343434343" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <com.facebook.drawee.view.SimpleDraweeView android:id="@+id/duanzi_img2" android:layout_width="300dp" android:layout_height="200dp" /> </LinearLayout> </LinearLayout>
MyApp
public class MyApp extends Application { @Override public void onCreate() { super.onCreate(); //初始化Fresco ,必须再setContentView之前进行 Fresco.initialize(this); } }
数据的适配器
public class DuanZiAdapter extends RecyclerView.Adapter { private List<DuanZiBean.DataBean> list; public DuanZiAdapter(List<DuanZiBean.DataBean> list) { this.list = list; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView01 = LayoutInflater.from(parent.getContext()).inflate(R.layout.duanzi_item, parent, false); return new ViewHolder(itemView01); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { ((ViewHolder)holder).textView1.setText(list.get(position).getContent()); ((ViewHolder)holder).textView2.setText(list.get(position).getCreateTime()); ((ViewHolder)holder).textView3.setText(list.get(position).getContent()); String picUri = list.get(position).getUser().getIcon(); if (!TextUtils.isEmpty(picUri)) { Uri uri = Uri.parse(picUri); ((ViewHolder) holder).imageView2.setImageURI(uri); ((ViewHolder) holder).imageView1.setImageURI(uri); } } @Override public int getItemCount() { return list==null ? 0:list.size(); } public class ViewHolder extends RecyclerView.ViewHolder{ private TextView textView1,textView2,textView3; private ImageView imageView1,imageView2; public ViewHolder(View itemView) { super(itemView); imageView1= itemView.findViewById(R.id.duanzi_img); imageView2=itemView.findViewById(R.id.duanzi_img2); textView1=itemView.findViewById(R.id.duanzi_tv1); textView2=itemView.findViewById(R.id.duanzi_riqi); textView3=itemView.findViewById(R.id.duanzi_tv2); } } }
Fragment 中的数据展示
public class DuanZiFragment extends Fragment { private static final String TAG = "DuanZiFragment"; @BindView(R.id.line) LinearLayout line; Unbinder unbinder; private XRecyclerView recyclerView; int a=1; private DaoSession daoSession; private PersonDao personDao; public DuanZiFragment() { } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view=inflater.inflate(R.layout.duanzi, null); recyclerView= view.findViewById(R.id.xrv); initView(); return view; } private void initView() { OkHttpUtils.getInstance().doGet(HttpConfig.URL, new OkHttpUtils.OkCallback() { private DuanZiAdapter duanZiAdapter; @Override public void getFailure(Exception e) { } @Override public void getResponse(String josn) { Log.d(TAG, "getResponse: "+josn); Gson gson = new Gson(); DuanZiBean duanZiBean = gson.fromJson(josn, DuanZiBean.class); List<DuanZiBean.DataBean> data = duanZiBean.getData(); duanZiAdapter = new DuanZiAdapter(data); // recyclerView.setAdapter(duanZiAdapter); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext()); recyclerView.setLayoutManager(linearLayoutManager); recyclerView.setAdapter(duanZiAdapter); recyclerView.setPullRefreshEnabled(true); recyclerView.setLoadingMoreEnabled(true); daoSession = DaoManager.instance(getActivity()).getDaoSession(); personDao = daoSession.getPersonDao(); //添加全部数据 for (int i = 0; i < data.size(); i++) { personDao.insert(new Person(null, "" + data.get(i).getContent(), data.get(i).getCreateTime())); } recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() { @Override public void onRefresh() { a=1; initView(); duanZiAdapter.notifyDataSetChanged(); recyclerView.refreshComplete(); } @Override public void onLoadMore() { a++; initView(); duanZiAdapter.notifyDataSetChanged(); recyclerView.refreshComplete(); } }); } }); } //点击查询 @OnClick(R.id.line) public void onViewClicked() { List<Person> list = personDao.queryBuilder() .where(PersonDao.Properties.Id.ge(1)) .build() .list(); Log.d(TAG, "onViewClicked: "+list.get(0).getName1()); } }
先建一个DaoManager类
public class DaoManager { private static DaoManager daoManager; private final DaoSession daoSession; private DaoManager(Context context) { daoSession = DaoMaster.newDevSession(context, "my.db"); } public static DaoManager instance(Context context) { if (daoManager == null) { synchronized (DaoManager.class) { if (daoManager == null) { daoManager = new DaoManager(context); } } } return daoManager; } public DaoSession getDaoSession() { return daoSession; } }
在写个类 建完类 直接点小锤子 生成数据库 然后在MainActivity里面把
网络数据放在GreenDao数据库 在来一个全查
@Entity(nameInDb = "person") public class Person { @Id(autoincrement = true) private Long id; @Property(nameInDb = "name") private String name1; private String time; @Generated(hash = 2048444458) public Person(Long id, String name1, String time) { this.id = id; this.name1 = name1; this.time = time; } @Generated(hash = 1024547259) public Person() { } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getName1() { return this.name1; } public void setName1(String name1) { this.name1 = name1; } public String getTime() { return this.time; } public void setTime(String time) { this.time = time; } }