小Demo--狸菇凉_

此文章使用mvp模式写的

()里的都是类

      一、有Model包里的bean包(Bean、ItemBean和SpacesItemDecoration)和utils包(MyImageLoadAsyncTask和Utils)

        二、presenter包里的(BasePresenter和F1Presenter)
        三、view包里的activity包(MainActivity和More)、adapter包(MyCarouselAdapter、MyAdapter、MyRecy1Adapter、MyRecy2Adapter和MyGridAdapter)
    application包(MyApplication)、
    adapter包(Fragment_one、Fragment_two、Fragment_three、Fragment_four)
    和iview包是接口(IMVPView、MainIView和MyOnclicklistener)

    一、model包里
    1.Model包里的
    ①Bean类我就不写了,里面需要的记得序列化(Serializable)
    ②ItemBean 类
    public class ItemBean {

    private String text;
    private boolean select;


    public ItemBean(String text, boolean select) {
        this.text = text;
        this.select = select;
    }


    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public boolean isSelect() {
        return select;
    }

    public void setSelect(boolean select) {
        this.select = select;
    }


}

    ③.SpacesItemDecoration类

public class SpacesItemDecoration extends RecyclerView.ItemDecoration {

    private int space;

    public SpacesItemDecoration(int space) {
        this.space = space;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view,
                               RecyclerView parent, RecyclerView.State state) {
        outRect.left = space;
        outRect.right = space;
        outRect.bottom = space;

    }


}
            2.utils包里的
            ①MyImageLoadAsyncTask类
            public class MyImageLoadAsyncTask extends AsyncTask {

    public interface ImageCallBack{
        void callBitmap(Bitmap bitmap);
    }

    //定义变量记住调用者所传递进来的回调监听对象
    private ImageCallBack imageCallBack;
    //构造方法
    public MyImageLoadAsyncTask(ImageCallBack imageCallBack){
        this.imageCallBack = imageCallBack;

    }


    @Override
    protected void onPostExecute(Bitmap bitmap) {
        super.onPostExecute(bitmap);

        if (bitmap != null ){

        }

    }

    @Override
    protected Bitmap doInBackground(String... params) {

        String param = params[0];

        try {
            URL url = new URL(param);

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("GET");
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);

            int responseCode = connection.getResponseCode();

            if (responseCode == 200){

                InputStream inputStream = connection.getInputStream();

                return BitmapFactory.decodeStream(inputStream);

            }


        } catch (Exception e) {
            e.printStackTrace();
        }


        return null;
    }
}
            ②Utils类
    public class Utils {

    public static void getHttp(String url, final GetUtils getUtils, final Class clazz){

        RequestParams requestParams = new RequestParams(url);

        x.http().get(requestParams, new Callback.CommonCallback() {
            @Override
            public void onSuccess(String result) {

                Gson gson = new Gson();
                T t = gson.fromJson(result, clazz);
                getUtils.CallBack(t);


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    public static void setImage(String url, ImageView imageView){
        DisplayImageOptions build = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.ic_launcher)
                .showImageOnFail(R.mipmap.ic_launcher)
                .cacheOnDisk(true)
                .cacheInMemory(false)
                .build();


        ImageLoader.getInstance().displayImage(url, imageView, build);
    }

    public interface GetUtils{

        void CallBack(T t);


    }

}

二、presenter层
        1.BasePresenter类
        public class BasePresenter  {

    private T tbase;

    public T getTbase() {
        return tbase;
    }

    public void setTbase(T tbase) {
        this.tbase = tbase;
    }
}
        2.F1Presenter类

public class F1Presenter extends BasePresenter {



    public void getData() {

        Utils.getHttp(url, new Utils.GetUtils() {
            @Override
            public void CallBack(T t) {
                getTbase().CallBack((Bean) t);
            }
        },Bean.class);

    }
}

    三、view层
    1.activity包
    ①MainActivity类
    public class MainActivity extends AppCompatActivity  {

    private ViewPager view_pager;
    private ArrayList fragments;
    private MyFragement_one myFragement_one;
    private MyFragement_two myFragement_two;
    private MyFragement_three myFragement_three;
    private MyFragement_four myFragement_four;
    private RadioButton rb1;
    private RadioButton rb2;
    private RadioButton rb3;
    private RadioButton rb4;
    private RadioGroup rg;
    private MyAdapter myAdapter;
    private int index;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //联网判断
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        //检查用户的网络情况
        ConnectivityManager cm=(ConnectivityManager) MainActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
        //返回當前可用網絡信息

        NetworkInfo info=cm.getActiveNetworkInfo();
        if(info!=null&&info.isConnected()){
            Toast.makeText(MainActivity.this, "网络可用", Toast.LENGTH_SHORT).show();

        }else{
            Toast.makeText(MainActivity.this, "网络不可用", Toast.LENGTH_SHORT).show();
            builder.setTitle("提醒");
            builder.setMessage("当前网络不可用,点击确定设置网络");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent=new Intent();
                            intent.setClassName("com.android.settings", "com.android.settings.Settings");
                            startActivity(intent);
                        }
                    }
            );
            builder.create().show();
        }





        setContentView(R.layout.activity_main);

        //找视图
        initView();

        //加载数据
        initData();

        //点击监听
        initClick();

    }

    private void initClick() {

        view_pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                switch (position) {

                    case 0: {
                        rb1.setChecked(true);

                    }
                    break;
                    case 1: {
                        rb2.setChecked(true);

                    }
                    break;

                    case 2: {
                        rb3.setChecked(true);

                    }
                    break;

                    case 3: {
                        rb4.setChecked(true);

                    }
                    break;

                }

            }



            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });



        //rg  点击rg跳转
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {

                switch (checkedId){

                    case R.id.rb1:

                        index = 0;

                        break;

                    case R.id.rb2:

                        index = 1;

                        break;

                    case R.id.rb3:

                        index = 2;

                        break;

                    case R.id.rb4:

                        index = 3;

                        break;


                }

                if (view_pager.getCurrentItem() != index){

//                    view_pager.setCurrentItem(index,false);
                    view_pager.setCurrentItem(index);
                }


            }
        });


    }

    private void initData() {

        myFragement_one = new MyFragement_one();
        myFragement_two = new MyFragement_two();
        myFragement_three = new MyFragement_three();
        myFragement_four = new MyFragement_four();

        fragments = new ArrayList<>();

        fragments.add(myFragement_one);
        fragments.add(myFragement_two);
        fragments.add(myFragement_three);
        fragments.add(myFragement_four);


        myAdapter = new MyAdapter(getSupportFragmentManager(),fragments);

        view_pager.setAdapter(myAdapter);


    }

    private void initView() {
        view_pager = (ViewPager) findViewById(R.id.view_pager);
        rb1 = (RadioButton) findViewById(R.id.rb1);
        rb2 = (RadioButton) findViewById(R.id.rb2);
        rb3 = (RadioButton) findViewById(R.id.rb3);
        rb4 = (RadioButton) findViewById(R.id.rb4);
        rg = (RadioGroup) findViewById(R.id.rg);



    }





    }

    ②More
    public class More extends AppCompatActivity implements  MainIView, MyOnclicklistener {

    private TextView my;
    private RecyclerView recy1;
    private TextView other;
    private RecyclerView recy2;
    private GridLayoutManager gridLayoutManager1;
    private MyRecy1Adapter myRecy1Adapter;
    private GridLayoutManager gridLayoutManager2;
    private MyRecy2Adapter myRecy2Adapter;
    private ArrayList one;
    private ArrayList two;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mychannel);

        initView();

        initData();

    }



    //view
    private void initView() {

        my = (TextView) findViewById(R.id.my);
        recy1 = (RecyclerView) findViewById(R.id.recy1);
        other = (TextView) findViewById(R.id.other);
        recy2 = (RecyclerView) findViewById(R.id.recy2);


        int spacingInPixels = 30;

        // recy1的初始化工作
        gridLayoutManager1 = new GridLayoutManager(this, 3);
        recy1.setLayoutManager(gridLayoutManager1);

        recy1.addItemDecoration(new SpacesItemDecoration(spacingInPixels));
        myRecy1Adapter = new MyRecy1Adapter(this);
        myRecy1Adapter.setOnclickListener(this);
        recy1.setAdapter(this.myRecy1Adapter);

       // recy2的初始化工作
        gridLayoutManager2 = new GridLayoutManager(this, 3);
        recy2.setLayoutManager(gridLayoutManager2);
        //设置recycleview之间的间距
        recy2.addItemDecoration(new SpacesItemDecoration(spacingInPixels));
        myRecy2Adapter = new MyRecy2Adapter(More.this);
        myRecy2Adapter.setOnclickListener(this);
        recy2.setAdapter(myRecy2Adapter);



    }

    private void initData() {

        Intent intent = getIntent();
        if (intent != null) {

            one = (ArrayList) intent.getSerializableExtra("one");
            two = (ArrayList) intent.getSerializableExtra("two");

            myRecy1Adapter.setData(one);
            myRecy1Adapter.notifyDataSetChanged();
            myRecy2Adapter.setData(two);
            myRecy2Adapter.notifyDataSetChanged();
        }

    }



    //重写的方法1
    @Override
    public void CallBack(Bean bean) {

    }


    @Override
    public void OnClickListeber(View view, int position, int type) {
        switch (type) {

            case 1:

                //先添加,后移除
                Bean.ResultBean.NationsBean nationsBean = new Bean.ResultBean.NationsBean();
                nationsBean.setName(one.get(position).getName());
                two.add(nationsBean);
                myRecy2Adapter.setData(two);
                myRecy2Adapter.notifyDataSetChanged();

                one.remove(position);
                myRecy1Adapter.setData(one);
                myRecy1Adapter.notifyDataSetChanged();

                break;


            case 2:

                Bean.ResultBean.CategoryBean categoryBean = new Bean.ResultBean.CategoryBean();
                categoryBean.setName(two.get(position).getName());
                one.add(categoryBean);
                myRecy1Adapter.setData(one);
                myRecy1Adapter.notifyDataSetChanged();


                two.remove(position);
                myRecy2Adapter.setData(two);
                myRecy2Adapter.notifyDataSetChanged();

                break;

        }
    }
}

    2.application包
    MyApplication类
    public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        x.Ext.init(this);
        x.Ext.setDebug(BuildConfig.DEBUG);


        File cacheDirectory = StorageUtils.getOwnCacheDirectory(this, Environment.getExternalStorageDirectory().getPath());


        ImageLoaderConfiguration imageLoaderConfiguration = new ImageLoaderConfiguration.Builder(this)
                .diskCacheFileCount(500)
                .diskCacheSize(100 * 1024 * 1024)
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                .diskCache(new UnlimitedDiskCache(cacheDirectory))
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
                .threadPoolSize(3)
                .build();

        ImageLoader.getInstance().init(imageLoaderConfiguration);




    }
}

    3.adapter包
    ①MyCarouselAdapter类
    ublic class MyCarouselAdapter extends PagerAdapter {

    private Context context;
    private ArrayList list = new ArrayList<>();

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

    @Override
    public int getCount() {
        return Integer.MAX_VALUE;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {



    }

    /**
     * 53行错误算数异常。
     *
     */
    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        ImageView imageView = new ImageView(context);
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        DisplayImageOptions builder =new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.ic_launcher)
                .showImageOnFail(R.mipmap.ic_launcher)
                .cacheOnDisk(true)
                .cacheInMemory(false)
                .build();

        //youcuo
        ImageLoader.getInstance().displayImage(list.get(position % list.size()).getPic(),imageView,builder);




        container.addView(imageView);

        return imageView;
    }

    public void setData(List brands) {
        if (brands!=null){
            this.list.addAll(brands);

        }
    }
}   

    ②MyAdapter类

    public class MyAdapter extends FragmentPagerAdapter{


    private Context context;
    private ArrayList list = new ArrayList<>();


    public MyAdapter(FragmentManager fm,  ArrayList list) {
        super(fm);

        this.list = list;
    }

    public MyAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return list.get(position);
    }

    @Override
    public int getCount() {
        return list != null ? list.size() : 0;
    }
}
    ③MyRecy1Adapter类

public class MyRecy1Adapter extends RecyclerView.Adapter {

    private Context context;
    private ArrayList list = new ArrayList<>();
    private boolean isshow = false;
    private More more;

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


    @Override
    public MyViewHoder onCreateViewHolder(ViewGroup parent, int viewType) {

        View inflate = View.inflate(context, R.layout.channel_item, null);

        MyViewHoder myViewHoder = new MyViewHoder(inflate);


        return myViewHoder;
    }

    @Override
    public void onBindViewHolder(final MyViewHoder holder, final int position) {

//        if (isshow){
//
//            if (position == 0 || position == 1) {
//
//                holder.tv.setVisibility(View.GONE);
//
//            } else {
//
//                holder.tv.setVisibility(View.VISIBLE);
//
//            }
//
//        }else {
//            holder.tv.setVisibility(View.GONE);
//        }


        holder.tv.setText(list.get(position).getName());
        holder.tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (more!=null){

                    more.OnClickListeber(holder.tv,position,1);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return list != null ? list.size() : 0;
    }

    public void setOnclickListener(More more) {

        this.more = more;

    }

    public void setData(ArrayList myarr) {

        list.clear();
        if (myarr != null) {

            list.addAll(myarr);
        }


    }


    /**
     * MyViewHoder
     */
    class MyViewHoder extends RecyclerView.ViewHolder {

        private final TextView tv;

        public MyViewHoder(View itemView) {
            super(itemView);


            tv = (TextView) itemView.findViewById(R.id.tv);

        }
    }

}
    ④MyGridAdapter类
    public class MyGridAdapter extends BaseAdapter {

    private Context context;
    private ArrayList list = new ArrayList<>();
    private ViewHoder viewHoder;


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

    @Override
    public int getCount() {
        return list != null ? list.size() :0 ;
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null){

            convertView = View.inflate(context,R.layout.griditem,null);

            viewHoder = new ViewHoder();

            viewHoder.imageView = (ImageView) convertView.findViewById(R.id.image_gf1);
            viewHoder.textView = (TextView) convertView.findViewById(R.id.text_gf1);

            convertView.setTag(viewHoder);

        }else {

            viewHoder = (ViewHoder) convertView.getTag();

        }

        Utils.setImage(list.get((position % list.size())).getPic(), viewHoder.imageView);

        viewHoder.textView.setText(list.get(position).getName());

        return convertView;
    }

    public void setData(List indexProducts) {

        if (indexProducts!=null){
            this.list.clear();
            this.list.addAll(indexProducts);
        }



    }

    class ViewHoder{

        ImageView imageView;
        TextView textView;

    }

}

    ⑤MyRecy2Adapter 类
    public class MyRecy2Adapter extends RecyclerView.Adapter {

    private Context context;
    private ArrayList list = new ArrayList<>();
    private boolean isshow = false;
    private MainActivity mainActivity;
    private More more;

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


    @Override
    public MyViewHoder onCreateViewHolder(ViewGroup parent, int viewType) {

        View inflate = View.inflate(context, R.layout.channel_item, null);

        MyViewHoder myViewHoder = new MyViewHoder(inflate);


        return myViewHoder;
    }

    @Override
    public void onBindViewHolder(final MyViewHoder holder, final int position) {

//        if (isshow){
//
//            if (position == 0 || position == 1) {
//
//                holder.tv.setVisibility(View.GONE);
//
//            } else {
//
//                holder.tv.setVisibility(View.VISIBLE);
//
//            }
//
//        }else {
//            holder.tv.setVisibility(View.GONE);
//        }

        holder.tv.setText(list.get(position).getName());

        holder.tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (more!=null){

                    more.OnClickListeber(holder.tv,position,2);
                }
            }
        });


    }

    @Override
    public int getItemCount() {
        return list != null ? list.size() : 0 ;
    }

    public void setOnclickListener(MainActivity mainActivity) {

        this.mainActivity = mainActivity;

    }

    public void setData(ArrayList myarr) {

        list.clear();
        if (myarr != null) {

            list.addAll(myarr);
        }


    }

    public void setOnclickListener(More more) {

        this.more = more;

    }


    class MyViewHoder extends RecyclerView.ViewHolder{

        private final TextView tv;

        public MyViewHoder(View itemView) {
            super(itemView);


            tv = (TextView) itemView.findViewById(R.id.tv);

        }
    }

}
    4.iview包,,,接口
    ①IMVPView类
    public interface IMVPView {
}
    ②MainIView类

public interface MainIView extends IMVPView{

    void CallBack(Bean bean);


}
    ③MyOnclicklistener类

public interface MyOnclicklistener {

    void OnClickListeber(View view,int position,  int type);

}

 最后的      adapter包
①Fragment_one类

②Fragment_two类(只在这里面写数据了)
public class MyFragement_two extends Fragment implements MainIView {

    private ViewPager viewpager_f1;
    private LinearLayout lin;
    private ArrayList dotList = new ArrayList<>();
    private int oldPosition = 0;
    private GridView grid_view;
    private TextView jing;
    private TextView duo;
    private MyGridAdapter myGridAdapter;
    private F1Presenter f1Presenter;
    private List indexProducts;
    private static int index = 0;
    private boolean istrue = true;
    private MyHandler myHandler;
    private List brands;
    private List category;
    private List nations;
    private MyGridAdapter myGridAdapter1;
    private MyCarouselAdapter myCarouselAdapter1;
    private ArrayList views;
    private int upIndex = 0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment2, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initView();
        iniData();

    }


    //视图
    private void initView() {

        viewpager_f1 = (ViewPager) getView().findViewById(R.id.viewpager_f1);
        lin = (LinearLayout) getView().findViewById(R.id.lin);

        jing = (TextView) getView().findViewById(R.id.jing);
        duo = (TextView) getView().findViewById(R.id.duo);

        grid_view = (GridView) getView().findViewById(R.id.grid_view);

        myGridAdapter = new MyGridAdapter(getActivity());
        grid_view.setAdapter(myGridAdapter);

        //点击更多跳转到频道页面
        duo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (category.size()>0  && nations.size()>0){

                    Intent intent = new Intent(getActivity(), More.class);
                    //传值  因为bean实现序列化  所以可以意图传值
                    intent.putExtra("one", (Serializable) category);
                    intent.putExtra("two", (Serializable) nations);

                    startActivity(intent);

                }


            }
        });


        //监听
        viewpager_f1.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                views.get((upIndex % views.size())).setBackgroundResource(R.drawable.dot_false);
                views.get((position % views.size())).setBackgroundResource(R.drawable.dot_true);
                upIndex = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


    }


    //加载数据
    private void iniData() {
        f1Presenter = new F1Presenter();
        f1Presenter.setTbase(this);
        f1Presenter.getData();

    }


    //此方法可以让viewpager活起来
    private void initPricture() {

        myHandler = new MyHandler((MainActivity) getActivity());

        new Thread() {

            @Override
            public void run() {

                while (istrue) {
                    try {
                        sleep(2000);

                        myHandler.sendEmptyMessage(0);

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();


    }

    //回掉方法
    @Override
    public void CallBack(Bean dataBean) {


        category = dataBean.getResult().getCategory();
        nations = dataBean.getResult().getNations();

        //轮播图数据
        brands = dataBean.getResult().getBrands();
        //gridview数据
        indexProducts = dataBean.getResult().getIndexProducts();
        //设置gridview
        myGridAdapter1 = new MyGridAdapter(getActivity());
        myGridAdapter1.setData(indexProducts);
        grid_view.setAdapter(myGridAdapter1);

        //设置轮播图
        myCarouselAdapter1 = new MyCarouselAdapter(getActivity());
        myCarouselAdapter1.setData(brands);
        viewpager_f1.setAdapter(myCarouselAdapter1);

        if (brands != null) {

            views = new ArrayList<>();
            for (int i = 0; i < brands.size(); i++) {
                View view = new View(getActivity());
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
                view.setLayoutParams(layoutParams);
                views.add(view);
                if (i == 0) {
                    view.setBackgroundResource(R.drawable.dot_true);
                } else {
                    view.setBackgroundResource(R.drawable.dot_false);
                }

                lin.addView(views.get(i));
            }

        }
        initPricture();

    }


    @Override
    public void onPause() {
        super.onPause();
        istrue = false;
        initPricture();
    }

    @Override
    public void onResume() {
        super.onResume();
        istrue = true;
        initPricture();
    }

    //轮播图的 Handler
    private class MyHandler extends Handler {

        private final WeakReference reference;

        public MyHandler(MainActivity mainActivity) {
            reference = new WeakReference<>(mainActivity);

        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (reference.get() != null) {

                switch (msg.what) {

                    case 0: {
                        if (viewpager_f1 != null) {
                            viewpager_f1.setCurrentItem(index, false);
                        }


                        index++;
                    }
                    break;


                }

            }

        }
    }

}
Fragment_three类

Fragment_four类

你可能感兴趣的:(移动开发)