fragment联动与RecycleView请求数据(包含retrofit,Fresco,EventBus与GreenDao结合MVP)

本文介绍了一个Android项目,其中结合了MVP模式、Fragment联动、RecycleView、Retrofit网络请求、Fresco图片加载、EventBus事件总线以及GreenDao数据库操作。详细讲述了依赖配置、权限设置、界面布局、数据模型以及各个组件的使用方法,提供了一个简单的Demo示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目需要的依赖以及一些权限配置;

权限:

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

 依赖:

compile 'com.jakewharton:butterknife:7.0.0'
    compile 'org.greenrobot:eventbus:3.1.1'
    compile 'com.facebook.fresco:fresco:0.14.1'
    compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'
    compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
    compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
    compile'org.greenrobot:greendao:3.0.1'
    compile'org.greenrobot:greendao-generator:3.0.0'
greendao的配置:

如何配置:http://blog.youkuaiyun.com/guoleisb10/article/details/78690374

 greendao {
        schemaVersion 1
        daoPackage 'com.bawei.guolei.zhoukaomonidemo.dao'
        targetGenDir 'src/main/java'
    }
apply plugin: 'org.greenrobot.greendao'
classpath 'org.greenrobot:greendao-gradle-plugin:3.0.0'


项目布局:


activity_main:放置fragment底部按钮:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
  >
    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/group"
        />

    <RadioGroup
        android:id="@+id/group"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#118a8a8a"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/radio_01"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:button="@null"
            android:checked="true"
            android:gravity="center"
            android:text="首页" />


        <RadioButton
            android:id="@+id/radio_02"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:button="@null"
            android:gravity="center"
            android:text="想法" />

        <RadioButton
            android:id="@+id/radio_03"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:button="@null"
            android:gravity="center"
            android:text="市场" />

        <RadioButton
            android:id="@+id/radio_04"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:button="@null"
            android:gravity="center"
            android:text="通知" />
        <RadioButton
            android:id="@+id/radio_05"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:button="@null"
            android:gravity="center"
            android:text="更多" />
    </RadioGroup>




</RelativeLayout>


fragment_01:

<?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"
    android:orientation="vertical"
    >
<android.support.v7.widget.RecyclerView
    android:id="@+id/recycleView"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</android.support.v7.widget.RecyclerView>

</LinearLayout>
其他fragment都为空白所以没必要了

跳转传值页面:

activity_main2:

<?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="horizontal"
   >
    <com.facebook.drawee.view.SimpleDraweeView
        android:id="@+id/simple"
        android:layout_width="100dp"
        android:layout_height="100dp" />
    <TextView
    android:id="@+id/text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
</LinearLayout>


RecycleView列表布局:

item_layout:

<?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"
    android:orientation="horizontal"
    >



    <com.facebook.drawee.view.SimpleDraweeView
            android:id="@+id/image_view"
            android:layout_width="100dp"
            android:layout_height="100dp" />
    <TextView
        android:id="@+id/text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />







</LinearLayout>


项目接口:http://v.juhe.cn/toutiao/index?type=%22+data+%22&key=2f092bd9ce76c0257052d6d3c93c11b4

Bean类如下

中间是greenDao生成Bean:

最下是EventBus的Bean类:


主代码:

MainActicity:fragment的显示及使用;


import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.bawei.guolei.zhoukaomonidemo.fragment.Fragment_01;
import com.bawei.guolei.zhoukaomonidemo.fragment.Fragment_02;
import com.bawei.guolei.zhoukaomonidemo.fragment.Fragment_03;
import com.bawei.guolei.zhoukaomonidemo.fragment.Fragment_04;
import com.bawei.guolei.zhoukaomonidemo.fragment.Fragment_05;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends FragmentActivity{
    private ViewPager viewPager;
    private RadioGroup radioGroup;
    private List<Fragment> list;
    private MyAdapter myAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewPager = (ViewPager) findViewById(R.id.pager);
        radioGroup = (RadioGroup) findViewById(R.id.group);

        list = new ArrayList<>();
        list.add(new Fragment_01());
        list.add(new Fragment_02());
        list.add(new Fragment_03());
        list.add(new Fragment_04());
        list.add(new Fragment_05());
        myAdapter = new MyAdapter(getSupportFragmentManager(),list);
        viewPager.setAdapter(myAdapter);
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                radioGroup.check(radioGroup.getChildAt(position).getId());

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i){
                    case R.id.radio_01:
                        viewPager.setCurrentItem(0,false);
                        break;
                    case R.id.radio_02:
                        viewPager.setCurrentItem(1,false);
                        break;
                    case R.id.radio_03:
                        viewPager.setCurrentItem(2,false);
                        break;
                    case R.id.radio_04:
                        viewPager.setCurrentItem(3,false);
                        break;
                    case R.id.radio_05:
                        viewPager.setCurrentItem(4,false);
                        break;
                }
            }
        });
        viewPager.setOffscreenPageLimit(5);

    }//网络判断
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected())
            {
                // 当前网络是连接的
                if (info.getState() == NetworkInfo.State.CONNECTED)
                {
                    // 当前所连接的网络可用
                    Toast.makeText(context,"当前所连接的网络可用",Toast.LENGTH_SHORT).show();
                    return true;
                }
            }
        }
        Toast.makeText(context,"网络不可用",Toast.LENGTH_SHORT).show();
        return false;
    }

}


Main2Activity:接受传值的类:


import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.Bind;
import butterknife.ButterKnife;

public class Main2Activity extends AppCompatActivity {

    @Bind(R.id.simple)
    SimpleDraweeView simple;
    @Bind(R.id.text_view)
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
    }
    @Subscribe(sticky = true)
    public void event(EventBean eventBean){
        simple.setImageURI(eventBean.getUrl());
        textView.setText(eventBean.getTitle());
        Toast.makeText(this,""+eventBean.getUrl()+""+eventBean.getTitle(),Toast.LENGTH_SHORT).show();





    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}


初始化Application:IApplication:


import android.app.Application;

import com.bawei.guolei.zhoukaomonidemo.dao.DaoMaster;
import com.bawei.guolei.zhoukaomonidemo.dao.DaoSession;
import com.facebook.drawee.backends.pipeline.Fresco;

import org.greenrobot.greendao.database.Database;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Lenovo on 2017/12/2.
 */
public class IApplication extends Application {

    public static IGetDataBase iGetDataBase;
    public static DaoSession session;

    @Override
    public void onCreate() {
        super.onCreate();
        Fresco.initialize(this);

        Retrofit retrofit=new Retrofit.Builder().baseUrl("http://v.juhe.cn")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        iGetDataBase = retrofit.create(IGetDataBase.class);

        DaoMaster.DevOpenHelper helper=new DaoMaster.DevOpenHelper(this,"test");
        Database database=helper.getWritableDb();
        session = new DaoMaster(database).newSession();


    }
}

retrofit接口:

IGetDataBase:

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

/**
 * Created by Lenovo on 2017/12/2.
 */
public interface IGetDataBase {
    /**
     * get请求
     * @param key
     * @return
     */
    @GET("/toutiao/index")
    Call<Bean> get(@Query("key") String key);
}


fragment及RecycleView的adapter类:

MyAdapter:fragmentAdapter:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import java.util.List;

/**
 * Created by Lenovo on 2017/12/2.
 */
public class MyAdapter extends FragmentPagerAdapter{

    List<Fragment> list;

    public MyAdapter(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();
    }

}

IAdapter:


import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bawei.guolei.zhoukaomonidemo.Bean.Bean;
import com.bawei.guolei.zhoukaomonidemo.Bean.DataBean;
import com.bawei.guolei.zhoukaomonidemo.EventBean;
import com.bawei.guolei.zhoukaomonidemo.Main2Activity;
import com.bawei.guolei.zhoukaomonidemo.R;
import com.facebook.drawee.view.SimpleDraweeView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Lenovo on 2017/12/2.
 */
public class IAdapter extends RecyclerView.Adapter<IAdapter.IViewHolder> {
    private Context context;

    List<DataBean> list;

    public IAdapter(Context context) {
        this.context = context;
    }

    public void addData(Bean bean) {
        if (list == null) {
            list = new ArrayList<>();
        }
        list.addAll(bean.getResult().getData());
        notifyDataSetChanged();

    }


    @Override
    public IAdapter.IViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = View.inflate(context, R.layout.item_layout, null);


        return new IViewHolder(view);
    }

    @Override
    public void onBindViewHolder(IAdapter.IViewHolder holder, final int position) {
               holder.imageView.setImageURI(list.get(position).getThumbnail_pic_s());
               holder.textView.setText(list.get(position).getTitle());
        holder.imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EventBus.getDefault().postSticky(new EventBean(list.get(position).getThumbnail_pic_s(),list.get(position).getTitle()));
                 context.startActivity(new Intent(context,Main2Activity.class));

            }
        });

    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }
     static class IViewHolder extends RecyclerView.ViewHolder{
         @Bind(R.id.image_view)
         SimpleDraweeView imageView;
         @Bind(R.id.text_view)
         TextView textView;
         public IViewHolder(View itemView) {
             super(itemView);
             ButterKnife.bind(this,itemView);
         }
     }

}


greenDao所生成的dao包:自动生成:

有些区别就不写了,展示一下:



fragment_01中放置RecycleView的调用及使用:

Fragment_01 :fragment的使用一定要继承Fragment;其他Fragment都为空,就不写了


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.bawei.guolei.zhoukaomonidemo.Bean.Bean;
import com.bawei.guolei.zhoukaomonidemo.Bean.DataBean;
import com.bawei.guolei.zhoukaomonidemo.IApplication;
import com.bawei.guolei.zhoukaomonidemo.R;
import com.bawei.guolei.zhoukaomonidemo.adapter.IAdapter;
import com.bawei.guolei.zhoukaomonidemo.presenter.MainPresenter;
import com.bawei.guolei.zhoukaomonidemo.view.IMainView;

import java.util.List;

import static com.bawei.guolei.zhoukaomonidemo.MainActivity.isNetworkAvailable;


/**
 * Created by Lenovo on 2017/12/2.
 */
public class Fragment_01 extends Fragment implements IMainView{

    private RecyclerView recyclerView;
    private MainPresenter presenter;
    private IAdapter adapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view=inflater.inflate(R.layout.fram_layout01,container,false);
        recyclerView = view.findViewById(R.id.recycleView);
        presenter = new MainPresenter(this);
        presenter.get();
        adapter = new IAdapter(getActivity());
        LinearLayoutManager manager=new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false);


       //网络判断
        boolean b=isNetworkAvailable(getActivity());
        if (b){
            recyclerView.setAdapter(adapter);
            recyclerView.setLayoutManager(manager);
            List<DataBean> listBeans= IApplication.session.getDataBeanDao().loadAll();
            for (DataBean bean:listBeans){
                System.out.println(bean.toString());
            }

        }else{
            Toast.makeText(getActivity(),"当前网络不可用,请检查网络!",Toast.LENGTH_SHORT).show();
        }



        return view;
    }
    @Override
    public void onSuccess(Bean bean) {
        adapter.addData(bean);


    }

    @Override
    public void onFailure(Exception e) {

    }
}

MVP的结合使用:一定不要忘记分包:(展示一下)


M层:model包:

MainModel:model接口类

/**
 * Created by Lenovo on 2017/12/2.
 */
public interface MainModel {
}



ModelCallBack:CallBack接口:其中包括成功与失败的方法

/**
 * Created by Lenovo on 2017/12/2.
 */
public interface ModelCallBack {
    public void onSuccess(Bean bean);
    public void onFailure(Exception e);
}


MainModelIpml:调用CallBack接口中的方法:


import com.bawei.guolei.zhoukaomonidemo.Bean.Bean;
import com.bawei.guolei.zhoukaomonidemo.IApplication;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Lenovo on 2017/12/2.
 */
public class MainModelIpml {
    public void getDatas(final ModelCallBack callBack){
        Call<Bean> call= IApplication.iGetDataBase.get("2f092bd9ce76c0257052d6d3c93c11b4");

        call.enqueue(new Callback<Bean>() {
            @Override
            public void onResponse(Call<Bean> call, Response<Bean> response) {
                Bean bean=response.body();
                callBack.onSuccess(bean);

                IApplication.session.getDataBeanDao().insertInTx(bean.getResult().getData());


            }

            @Override
            public void onFailure(Call<Bean> call, Throwable t) {

                callBack.onFailure(new Exception(""));
            }
        });



    }
}


V层:view包:

IMainView :v层接口:

/**
 * Created by Lenovo on 2017/12/2.
 */
public interface IMainView {
    public void onSuccess(Bean bean);
    public void onFailure(Exception e);


}


P层:presenter包:

MainPresenter:连接M层与V层的中间层:

import com.bawei.guolei.zhoukaomonidemo.Bean.Bean;
import com.bawei.guolei.zhoukaomonidemo.model.MainModelIpml;
import com.bawei.guolei.zhoukaomonidemo.model.ModelCallBack;
import com.bawei.guolei.zhoukaomonidemo.view.IMainView;

/**
 * Created by Lenovo on 2017/12/2.
 */
public class MainPresenter {

    private IMainView iView;
    private MainModelIpml modelIpml;
    public MainPresenter(IMainView view){
        this.iView=view;
        this.modelIpml=new MainModelIpml();


    }

    public void get(){
        modelIpml.getDatas(new ModelCallBack() {
            @Override
            public void onSuccess(Bean bean) {
                if (iView!=null){
                    iView.onSuccess(bean);
                }
            }

            @Override
            public void onFailure(Exception e) {
                if (iView!=null){
                    iView.onFailure(e);
                }

            }
        });

    }
}

最后效果如下:

简单的Demo就完成了。


























评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值