效果图

RecycierView 点击条目 Eventbus传值给第二个activity,吐司展示RecycierView 点击条目 Eventbus传值给第二个activity,吐司展示

首页RecycierView 点击条目 Eventbus传值给第二个activity,吐司展示

Retrofit的post方式展示recyclerview,fresco加载图片,添加到数据库greendao,

点击条目发送Eventbus黏性事件给SecondActivity,吐司展示字段

涉及到了greendao,在工程的gradle里面加入两行(蓝色的)

buildscript {
    
    repositories {
        google()
        jcenter()
        mavenCentral() // add repository
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
在项目的gradle里面做更改,并且导入依赖(标红的)

apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao' // apply plugin
android {
    compileSdkVersion 26



    defaultConfig {
        applicationId "com.example.exercise_05_retrofit_greendao_eventbus_fresco"
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}
greendao {
    targetGenDir 'src/main/java'
    daoPackage 'com.example.exercise_05_retrofit_greendao_eventbus_fresco.dao'// 自己的包名.dao
    schemaVersion 1
}
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

   //butterknife两个依赖
    compile 'com.jakewharton:butterknife:8.8.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

     //retrofit的两个依赖
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'

    //eventbus的依赖
    compile 'org.greenrobot:eventbus:3.1.1'
    //fresco的依赖 
    compile 'com.facebook.fresco:fresco:1.5.0'

    //greendao两个依赖
    compile 'org.greenrobot:greendao:3.2.2'
    compile 'net.zetetic:android-database-sqlcipher:[email protected]'
     //recyclerview依赖
    compile 'com.android.support:recyclerview-v7:25.3.1'

 }
新建IApplication 继承Application ,并在清单文件中配置

  1. public class IApplication extends Application  
  1. <application  
  2.         android:name=".appli.IApplication"  

清单文件中加入权限

  1. <uses-permission android:name="android.permission.INTERNET" />  

请求网络获得的数据生成实体类bean(标红的需要写)

@Entity//必须写的
public class ListBean {
           
@Id(autoincrement =true)//自增
privateLong id;//自己加的字段
private String icon;
private String name;
private int pcid;
private int pscid;
点击锤子按钮RecycierView 点击条目 Eventbus传值给第二个activity,吐司展示会生成dao下面的三个类

新建接口GetDataService ,这里提供了两种方法,get传参 post传参

  1. public interface GetDataService {  
  2.     /**  
  3.      * post请求  
  4.      * https://www.zhaoapi.cn/product/getProductCatagory?cid=1  
  5.      */  
  6.     @FormUrlEncoded  
  7.     @POST("/product/getProductCatagory")  
  8.    Call<OldBean> post(@Field("cid") String cid);  
  9.   
  10.     /**  
  11.      * get请求  
  12.      * https://www.zhaoapi.cn/product/getProductCatagory?cid=1  
  13.      */  
  14.     @GET("/product/getProductCatagory")  
  15.     Call<OldBean> get(@Query("cid") String cid);  
  16. }  

IApplication里面的一系列初始化配置

  1. public class IApplication extends Application{  
  2.   
  3.     public static GetDataService service;  
  4.     public static DaoSession session;  
  5.   
  6.     @Override  
  7.     public void onCreate() {  
  8.         super.onCreate();  
  9.         //一系列的初始化配置  
  10.   
  11.         //1.fresco的初始化配置  
  12.         Fresco.initialize(this);  
  13.   
  14.         //2.retrofit的初始化  
  15.         Retrofit retrofit = new Retrofit.Builder()  
  16.                 .baseUrl("https://www.zhaoapi.cn")  
  17.                 .addConverterFactory(GsonConverterFactory.create())  
  18.                 .build();  
  19.         //操作网络请求的对象  
  20.         service = retrofit.create(GetDataService.class);  
  21.   
  22.   
  23.         //3.初始化greendao  
  24.         DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this,"tablename");  
  25.   
  26.         Database database = helper.getWritableDb();  
  27.   
  28.         //new出session  
  29.         session = new DaoMaster(database).newSession();  
  30.   
  31.     }  
  32. }  
使用MVP ,此处省略了presenter层,model层里面调用IApplication类的请求网络

  1. public class MyModel {  
  2.   
  3.   //请求网络数据  
  4.     public void getData(final ModelCallBack modelCallBack) {  
  5.         //调用application里面的请求网络的对象  
  6.         //传接口后面拼接的参数 key的值 ,,,post  
  7.       /*  Call<OldBean> call = IApplication.service.post("1");  
  8.   
  9.         call.enqueue(new Callback<OldBean>() {  
  10.             @Override  
  11.             public void onResponse(Call<OldBean> call, Response<OldBean> response) {  
  12.                 //response.body 就是一个bean对象了,不需要解析了  
  13.                 OldBean oldBean = response.body();  
  14.                 modelCallBack.success(oldBean);  
  15.   
  16.               *//*  //在这里 就已经添加到了数据库,在view层查询数据库展示recyview  
  17.                 //调用iapplication里面的数据库的对象  
  18.                 IApplication.session.getListBeanDao().insertInTx(oldBean.getResult().getList());*//*  
  19.             }  
  20.   
  21.             @Override  
  22.             public void onFailure(Call<OldBean> call, Throwable t) {  
  23.                 modelCallBack.failure(new Exception(""));  
  24.             }  
  25.         });*/  
  26.   
  27.         //-------------------------  
  28.         //传接口后面拼接的参数 key的值 ,,,get  
  29.         Call<OldBean> call = IApplication.service.get("2");  
  30.   
  31.         call.enqueue(new Callback<OldBean>() {  
  32.             @Override  
  33.             public void onResponse(Call<OldBean> call, Response<OldBean> response) {  
  34.                 //response.body 就是一个bean对象了,不需要解析了  
  35.                 OldBean oldBean = response.body();  
  36.                 modelCallBack.success(oldBean);  
  37.   
  38.               /*  //在这里 就已经添加到了数据库,在view层查询数据库展示recyview  
  39.                 //调用iapplication里面的数据库的对象  
  40.                 IApplication.session.getListBeanDao().insertInTx(oldBean.getResult().getList());*/  
  41.             }  
  42.   
  43.             @Override  
  44.             public void onFailure(Call<OldBean> call, Throwable t) {  
  45.                 modelCallBack.failure(new Exception(""));  
  46.             }  
  47.         });  
  48.     }  
  49. }  

回调到view层MainActivity

  1. public class MainActivity extends AppCompatActivity implements ViewCallBack{  
  2.   
  3.     @BindView(R.id.recy_view)  
  4.     RecyclerView recyView;  
  5.     private MyPresenter myPresenter;  
  6.     private RecyAdapter recyAdapter;  
  7.   
  8.     @Override  
  9.     protected void onCreate(Bundle savedInstanceState) {  
  10.         super.onCreate(savedInstanceState);  
  11.         setContentView(R.layout.activity_main);  
  12.         ButterKnife.bind(this);  
  13.   
  14.         myPresenter = new MyPresenter(this);  
  15.         myPresenter.getData();  
  16.   
  17.         recyView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));  
  18.   
  19.         recyAdapter = new RecyAdapter(this);  
  20.   
  21.         recyView.setAdapter(recyAdapter);  
  22.     }  
  23.   
  24.     @Override  
  25.     public void success(OldBean oldBean) {  
  26.         //在这里 就已经添加到了数据库,在view层查询数据库展示recyview  
  27.         //调用iapplication里面的数据库的对象  
  28.         IApplication.session.getListBeanDao().insertInTx(oldBean.getData().get(0).getList());  
  29.   
  30.         //添加完查询  
  31.         List<ListBean> list = IApplication.session.getListBeanDao().loadAll();  
  32.   
  33.         //查询打印出来  
  34.         for(ListBean bean:list){  
  35.             System.out.println(bean.toString());  
  36.         }  
  37.        recyAdapter.addData(list);//将从数据库里查询出的数据展示出来  
  38. //       recyAdapter.addData(oldBean.getData().get(0).getList());//直接展示  
  39.     }  
  40.   
  41.     @Override  
  42.     public void failure(Exception e) {  
  43.   
  44.     }  
  45. }  
activity_main.xml

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  3.     xmlns:tools="http://schemas.android.com/tools"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent"  
  6.     tools:context="com.example.exercise_05_retrofit_greendao_eventbus_fresco.MainActivity">  
  7.   
  8.   <android.support.v7.widget.RecyclerView  
  9.       android:id="@+id/recy_view"  
  10.       android:layout_width="match_parent"  
  11.       android:layout_height="match_parent"/>  
  12.   
  13. </LinearLayout>  
recy_item.xml

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:orientation="horizontal"  
  4.     android:gravity="center_vertical"  
  5.     android:layout_height="match_parent">  
  6.   
  7.     <com.facebook.drawee.view.SimpleDraweeView  
  8.         android:id="@+id/recy_simple_view"  
  9.         android:layout_width="100dp"  
  10.         android:layout_height="100dp" />  
  11.   
  12.     <TextView  
  13.         android:layout_marginLeft="20dp"  
  14.         android:textSize="23sp"  
  15.         android:id="@+id/recy_text"  
  16.         android:layout_width="match_parent"  
  17.         android:layout_height="wrap_content" />  
  18. </LinearLayout>  
recy的适配器RecyAdapter里面

  1. public class RecyAdapter extends RecyclerView.Adapter<RecyAdapter.MyViewHolder> {  
  2.   
  3.   
  4.     private List<ListBean> listDa;  
  5.     Context context;  
  6.   
  7.     public RecyAdapter(Context context) {  
  8.         this.context = context;  
  9.     }  
  10.   
  11.     //添加数据的方法  
  12.     public void addData(List<ListBean> list) {  
  13.         if (listDa == null) {  
  14.             listDa = new ArrayList<>();  
  15.         }  
  16.         listDa.addAll(list);  
  17.         notifyDataSetChanged();  
  18.     }  
  19.   
  20.     @Override  
  21.     public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {  
  22.         View view = View.inflate(context, R.layout.recy_item, null);  
  23.         MyViewHolder myViewHolder = new MyViewHolder(view);  
  24.         return myViewHolder;  
  25.     }  
  26.   
  27.     @Override  
  28.     public void onBindViewHolder(MyViewHolder holder, final int position) {  
  29.   
  30.         holder.recySimpleView.setImageURI(listDa.get(position).getIcon());  
  31.         holder.recyText.setText(listDa.get(position).getName());  
  32.   
  33.         //条目点击事件  
  34.         holder.itemView.setOnClickListener(new View.OnClickListener() {  
  35.             @Override  
  36.             public void onClick(View view) {  
  37.                 //eventbus传递黏性事件给mainactivity2  
  38.                 //传一个eventbusbean对象过去  
  39.                 EventBusBean eventBusBean = new EventBusBean(listDa.get(position).getName());  
  40.                 EventBus.getDefault().postSticky(eventBusBean);  
  41.                 //跳转  
  42.            context.startActivity(new Intent(context, SecondActivity.class));  
  43.   
  44.   
  45.             }  
  46.         });  
  47.     }  
  48.   
  49.     @Override  
  50.     public int getItemCount() {  
  51.         return listDa == null ? 0 : listDa.size();  
  52.     }  
  53.   
  54.     static class MyViewHolder extends RecyclerView.ViewHolder{  
  55.         @BindView(R.id.recy_simple_view)  
  56.         SimpleDraweeView recySimpleView;  
  57.         @BindView(R.id.recy_text)  
  58.         TextView recyText;  
  59.   
  60.         MyViewHolder(View view) {  
  61.             super(view);  
  62.             ButterKnife.bind(this, view);  
  63.         }  
  64.     }  
  65.   
  66.   
  67. }  

Eventbus新建EventBusBean类传值

  1. public class EventBusBean {  
  2.     private String name;  
  3.   
  4.     public EventBusBean(String name) {  
  5.         this.name = name;  
  6.     }  
  7.   
  8.     public String getName() {  
  9.         return name;  
  10.     }  
  11.   
  12.     public void setName(String name) {  
  13.         this.name = name;  
  14.     }  
  15. }  

recyadapter的itemView点击事件里面,Eventbus发布一个黏性事件

public void onBindViewHolder(MyViewHolder holder, final int position) {

    holder.recySimpleView.setImageURI(listDa.get(position).getIcon());
    holder.recyText.setText(listDa.get(position).getName());

    //条目点击事件
    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //eventbus传递黏性事件给mainactivity2
            //传一个eventbusbean对象过去
            EventBusBean eventBusBean = new EventBusBean(listDa.get(position).getName());
            EventBus.getDefault().postSticky(eventBusBean);
            //跳转
       context.startActivity(new Intent(context, SecondActivity.class));

}
    });
SecondActivity里面注册黏性事件,并吐司,取消注册

  1. public class SecondActivity extends AppCompatActivity {  
  2.   
  3.     @Override  
  4.     protected void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.activity_second);  
  7.   
  8.         //这里面注册eventbus  
  9.         EventBus.getDefault().register(this);  
  10.     }  
  11.   
  12.     //接收订阅 ,,参数是bean  
  13.     @Subscribe(sticky=true)  
  14.     public void event(EventBusBean eventBusBean){  
  15.         Toast.makeText(this,eventBusBean.getName(),Toast.LENGTH_LONG).show();  
  16.     }  
  17.   
  18.     @Override  
  19.     protected void onDestroy() {  
  20.         super.onDestroy();  
  21.         EventBus.getDefault().unregister(this);  
  22.     }  
  23. }  



相关文章:

  • 2022-01-11
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-18
  • 2022-12-23
  • 2022-12-23
  • 2022-01-17
猜你喜欢
  • 2021-03-25
  • 2021-12-20
  • 2021-10-01
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-04-14
相关资源
相似解决方案