Demo1:Fresco+Butterknife_greenDao+EventBus

github:https://github.com/LGQ1001/greendao_Demo
底层的build.gradle
buildscript {
    
    repositories {
        google()
        jcenter()
        mavenCentral() // add repository
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'

        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

本层build.gradle

apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao'
 compile 'com.google.code.gson:gson:2.2.4'
    implementation 'com.squareup.okhttp3:okhttp:3.11.0'
    compile 'com.android.support:design:27.+'
    implementation 'com.android.support:support-v4:27.+'
    implementation 'com.jakewharton:butterknife:8.8.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
    implementation 'org.greenrobot:greendao:3.2.2'
    implementation 'com.facebook.fresco:fresco:0.12.0'
    // 在 API < 14 上的机器支持 WebP 时,需要添加
    compile 'com.facebook.fresco:animated-base-support:0.12.0'
    // 支持 GIF 动图,需要添加
    implementation 'com.facebook.fresco:animated-gif:0.12.0'
    // 支持 WebP (静态图+动图),需要添加
    implementation 'com.facebook.fresco:animated-webp:0.12.0'
    implementation 'com.facebook.fresco:webpsupport:0.12.0'
    //xrecyclerview
    implementation 'com.jcodecraeer:xrecyclerview:1.5.9'
}
configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        def requested = details.requested
        if (requested.group == 'com.android.support') {
            if (!requested.name.startsWith("multidex")) {
                details.useVersion '27.1.1'
            }
        }
    }
}

依赖
<uses-permission android:name="android.permission.INTERNET" />
<application
    android:name=".app.app"

布局

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.bwie.main.zk1_lian02.activity.MainActivity">

    <FrameLayout
        android:id="@+id/fram_layout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="9" />

    <RadioGroup
        android:id="@+id/rap"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/rap1"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="首页"
            android:textSize="25dp"
            android:gravity="center"
            android:button="@null"/>

        <RadioButton
            android:id="@+id/rap2"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="购物车"
            android:textSize="25dp"
            android:gravity="center"
            android:button="@null"/>

        <RadioButton
            android:id="@+id/rap3"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="附近"
            android:textSize="25dp"
            android:gravity="center"
            android:button="@null"/>

        <RadioButton
            android:id="@+id/rap4"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="我的"
            android:textSize="25dp"
            android:gravity="center"
            android:button="@null"/>

    </RadioGroup>

</LinearLayout>

activity_fragment1.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.bwie.main.zk1_lian02.fragment.Fragment1">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycleview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

include1.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:fresco="http://schemas.android.com/tools"
    android:orientation="vertical">

    <com.facebook.drawee.view.SimpleDraweeView
        android:id="@+id/my_image_view"
        android:layout_width="150dp"
        android:layout_height="150dp"
        fresco:placeholderTmage="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/bt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="title1"
        android:textSize="20sp"/>

</LinearLayout>

代码
MainActivity
public class MainActivity extends AppCompatActivity {

    @BindView(R.id.fram_layout)
    FrameLayout frameLayout;
    private FragmentManager manager;
    private RadioGroup rap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        rap = findViewById(R.id.rap);
        //创建对象
        final Fragment1 fragment1 = new Fragment1();
        final Fragment2 fragment2 = new Fragment2();
        final Fragment3 fragment3 = new Fragment3();
        final Fragment4 fragment4 = new Fragment4();
        //创建默认提交事务
        manager = getSupportFragmentManager();
        manager.beginTransaction().replace(R.id.fram_layout,fragment1).commit();
        rap.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                FragmentTransaction transaction = manager.beginTransaction();
                switch (i){
                    case R.id.rap1:
                        transaction.replace(R.id.fram_layout,fragment1);
                        break;
                    case R.id.rap2:
                        transaction.replace(R.id.fram_layout,fragment2);
                        break;
                    case R.id.rap3:
                        transaction.replace(R.id.fram_layout,fragment3);
                        break;
                    case R.id.rap4:
                        transaction.replace(R.id.fram_layout,fragment4);
                        break;
                }
                //提交事务
                transaction.commit();
            }
        });
    }
}

bean

news -》forment数据

work

@Entity
public class work {
    @Id(autoincrement = true)
    Long id;
    @Property
    String imgurl;
    @Property
    String title1;

Build  -》Make project

app

public class app extends Application {

    private DaoSession daoSession;
    private static app app;

    @Override
    public void onCreate() {
        super.onCreate();
        //上下文
        app = app.this;
        //初始化
        Fresco.initialize(this);
        //获得具体事务
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this,"bwie");
        //获得可读可写数据库
        SQLiteDatabase db = helper.getWritableDatabase();
        //配置默认信息
        DaoMaster daoMaster = new DaoMaster(db);
        //做增删改查
        daoSession = daoMaster.newSession();
    }
    public static app getinstance(){
        if (app == null){
            app = new app();
        }
        return app;
    }
    //提供方法
    public DaoSession daoSession(){
        return daoSession;
    }
}

HttpUtils

public class HttpUtils {
    //成员变量
    private static HttpUtils httpUtils;
    private OkHttpClient okHttpClient;
    //私有构造
    private HttpUtils(){
        okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new longinterceptor())
                .build();
    }
    //拦截器方法
    class longinterceptor implements Interceptor{

        @Override
        public Response intercept(Chain chain) throws IOException {
            //请求对象
            Request request = chain.request();
            //创建方法
            String method = request.method();
            //添加日志信息
            Log.i("xxx",method+"");
            //接收对象
            Response response = chain.proceed(request);
            return response;
        }
    }
    //单例
    public static HttpUtils getinstance(){
        if (httpUtils == null){
            synchronized (HttpUtils.class){
                if (httpUtils == null){
                    httpUtils = new HttpUtils();
                }
            }
        }
        return httpUtils;
    }
    //post方法
    public void getpost(String path, Callback callback){
        Request request = new Request.Builder().url(path).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(callback);
    }
}

mvp

icontract

public interface icontract {
    //iview层
    public interface iview{
        void showdata(List<work> works);
    }
    //imoudle层
    public interface imoudle{
        //接口
        public interface oncalllisten{
            //请求方法
            void responsemsg(List<work> works);
        }
        //方法
        void requestdata(oncalllisten oncalllisten);
    }
    //ipresebnter层
    public interface ipresebnter<iview>{
        //关联
        void attachview(iview iview);
        //取消
        void detachview(iview iview);
        //逻辑方法
        void requestinfo();
    }
}

moudleimp

public class moudleimp implements icontract.imoudle{

    private String path = "https://www.apiopen.top/meituApi?page=1";

    @Override
    public void requestdata(final oncalllisten oncalllisten) {
        //获取数据库存
        final workDao workDao = app.getinstance().daoSession().getWorkDao();
        //全查
        final List<work> works = workDao.loadAll();
        //判断
        if (works.size()>0){
            //进行接口回传
            oncalllisten.responsemsg(works);
            return;
        }
        //查不到进行网络请求
        HttpUtils httpUtils = HttpUtils.getinstance();
        httpUtils.getpost(path, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //失败
                oncalllisten.responsemsg(null);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //成功
                String json = response.body().string();
                //进行解析
                Gson gson = new Gson();
                //获取数据
                news news = gson.fromJson(json, news.class);
                Log.i("eee",news+"");
                //得到对象
                List<com.bwie.main.zk1_lian02.bean.news.DataBean> data = news.getData();
                //创建新集合进行回传
                ArrayList<work> works1 = new ArrayList<>();
                //进行遍历
                for (int i = 0; i < data.size(); i++) {
                    //获取数据
                    String url = data.get(i).getUrl();
                    String desc = data.get(i).getType();
                    //创建对象
                    work work = new work();
                    work.setImgurl(url);
                    work.setTitle1(desc);
                    //添加到集合中
                    works1.add(work);
                }
                //接口回传
                oncalllisten.responsemsg(works1);
                //存到数据库
                workDao.insertInTx(works1);
            }
        });
    }

presenterimp

public class presenterimp implements icontract.ipresebnter<icontract.iview>{

    private WeakReference<icontract.iview> iviewWeakReference;
    private  icontract.iview iview;
    private moudleimp moudleimp;
    private WeakReference<icontract.imoudle> weakReference;

    @Override
    public void attachview(icontract.iview iview) {
        this.iview = iview;
        moudleimp = new moudleimp();
        //创建弱引用
        iviewWeakReference = new WeakReference<>(iview);
        weakReference = new WeakReference<icontract.imoudle>(moudleimp);
    }

    @Override
    public void detachview(icontract.iview iview) {
        //取消关联
        iviewWeakReference.clear();
        weakReference.clear();
    }

    @Override
    public void requestinfo() {
        //接口回调
        moudleimp.requestdata(new icontract.imoudle.oncalllisten() {
            @Override
            public void responsemsg(List<work> works) {
                //v层里面的方法
                iview.showdata(works);
                Log.i("xxx",works+"");
            }
        });
    }
}

adapter

myadapter

public class myadapter extends RecyclerView.Adapter<myadapter.oneholder>{

    private Context context;
    private List<work> list;

    public myadapter(Context context, List<work> list) {
        this.context = context;
        this.list = list;
    }

    @NonNull
    @Override
    public oneholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.include1, null);
        //创建对象
        oneholder oneholder = new oneholder(view);
        return oneholder;
    }

    @Override
    public void onBindViewHolder(@NonNull oneholder holder, int position) {
        holder.bt.setText(list.get(position).getTitle1());
        //获取路径
        Uri uri = Uri.parse(list.get(position).getImgurl());
        //设置图片
        holder.my_image_view.setImageURI(uri);
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    //创建类
    class oneholder extends RecyclerView.ViewHolder{

        private final TextView bt;
        private final SimpleDraweeView my_image_view;

        public oneholder(View itemView) {
            super(itemView);
            //创建视图
            bt = itemView.findViewById(R.id.bt);
            my_image_view = itemView.findViewById(R.id.my_image_view);
        }
    }

Fragment1

public class Fragment1 extends Fragment implements icontract.iview{

    @BindView(R.id.recycleview)
    RecyclerView recycleview;
    Unbinder unbinder;
    private presenterimp presenterimp;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_fragment1,container,false);
        unbinder = ButterKnife.bind(this, view);
        presenterimp = new presenterimp();
        presenterimp.attachview(this);
        presenterimp.requestinfo();

        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        presenterimp.detachview(this);
    }

    @Override
    public void showdata(final List<work> works) {
        //强制切回主线程
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //创建布局管理器
                GridLayoutManager manager = new GridLayoutManager(getActivity(), 2, GridLayoutManager.VERTICAL, false);
                //添加布局管理器
                recycleview.setLayoutManager(manager);
                //创建适配器
                myadapter myadapter = new myadapter(getActivity(),works);
                //添加适配器
                recycleview.setAdapter(myadapter);
            }
        });
    }
}

猜你喜欢

转载自blog.csdn.net/QQ849410011/article/details/82318737
今日推荐