TabLayout+PullToRefresh+数据库缓存+频道管理

TabLayout+PullToRefresh+数据库缓存+频道管理

记得加权限!导依赖!!!

创建基类

public abstract class BaseActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(onResID());
        onView();
        onData();
    }

    protected abstract int onResID();
    protected abstract void onView();
    protected abstract void onData();
}

public abstract class BaseFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=View.inflate(getContext(),onResID(),null);
        onView(view);
        onData();
        return view;
    }

    protected abstract int onResID();
    protected abstract void onView(View view);
    protected abstract void onData();
}

主页面

<LinearLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <android.support.v4.widget.DrawerLayout
        android:id="@+id/draw"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <FrameLayout
                android:id="@+id/frag"
                android:layout_weight="1"
                android:layout_width="match_parent"
                android:layout_height="0dp"></FrameLayout>
            <RadioGroup
                android:id="@+id/radio"
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <RadioButton
                    android:id="@+id/button"
                    android:drawableTop="@drawable/selector"
                    android:button="@null"
                    android:text="首页"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:padding="5dp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
                <RadioButton
                    android:id="@+id/button2"
                    android:drawableTop="@drawable/selector"
                    android:button="@null"
                    android:text="自选"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:padding="5dp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
                <RadioButton
                    android:id="@+id/button3"
                    android:drawableTop="@drawable/selector"
                    android:button="@null"
                    android:text="行情"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:padding="5dp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
                <RadioButton
                    android:id="@+id/button4"
                    android:drawableTop="@drawable/selector"
                    android:button="@null"
                    android:text="咨询"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:padding="5dp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
                <RadioButton
                    android:id="@+id/button5"
                    android:drawableTop="@drawable/selector"
                    android:button="@null"
                    android:text="交易"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:padding="5dp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
            </RadioGroup>
        </LinearLayout>

        <LinearLayout
            android:background="#999"
            android:layout_gravity="left"
            android:layout_width="300dp"
            android:layout_height="match_parent">
            <com.bwei.xlistview.XlistView
                android:id="@+id/xlistview"
                android:layout_width="match_parent"
                android:layout_height="match_parent"></com.bwei.xlistview.XlistView>
        </LinearLayout>
    </android.support.v4.widget.DrawerLayout>

</LinearLayout>
public class MainActivity extends BaseActivity implements DrawerLayout.DrawerListener, RadioGroup.OnCheckedChangeListener {


    private DrawerLayout draw;
    private RadioGroup radioGroup;
    private FragmentManager manager;
    private Frag_01 frag_01;
    private Frag_02 frag_02;
    private Frag_03 frag_03;
    private Frag_04 frag_04;
    private Frag_05 frag_05;
    private String path="http://mnews.gw.com.cn/wap/data/news/xbsjxw/page_1.json";
    private XlistView xlistView;

    @Override
    protected int onResID() {
        return R.layout.activity_main;
    }

    @Override
    protected void onView() {
        draw = (DrawerLayout)findViewById(R.id.draw);
        radioGroup = (RadioGroup)findViewById(R.id.radio);
        draw.addDrawerListener(this);
        radioGroup.setOnCheckedChangeListener(this);
        xlistView = (XlistView)findViewById(R.id.xlistview);

    }

    @Override
    protected void onData() {
        manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        frag_01 = new Frag_01();
        frag_02 = new Frag_02();
        frag_03 = new Frag_03();
        frag_04 = new Frag_04();
        frag_05 = new Frag_05();
        transaction.add(R.id.frag, frag_01);
        transaction.add(R.id.frag, frag_02);
        transaction.add(R.id.frag, frag_03);
        transaction.add(R.id.frag, frag_05);
        transaction.add(R.id.frag, frag_04);
        transaction.show(frag_04).hide(frag_01).hide(frag_02).hide(frag_03).hide(frag_05);
        transaction.commit();
        getData();
    }

    private void getData() {
        MyAsyncTask myAsyncTask=new MyAsyncTask();
        myAsyncTask.execute();
    }

    private class MyAsyncTask extends AsyncTask<String,Integer,String>{

        @Override
        protected String doInBackground(String... strings) {
            try {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(50000);
                conn.setReadTimeout(5000);
                conn.setRequestMethod("GET");
                if (conn.getResponseCode() == 200) {
                    InputStream inputStream = conn.getInputStream();
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    byte[] bytes = new byte[1024];
                    int len = 0;
                    while ((len = inputStream.read(bytes)) != -1) {
                        stream.write(bytes, 0, len);
                    }
                    stream.close();
                    inputStream.close();
                    String data = stream.toString();
                    return data;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            try {
                JSONArray jsonArray = new JSONArray(s);
                JSONObject jsonObject = jsonArray.getJSONObject(0);
                String data = jsonObject.toString();
                Log.i("xxx", data);
                Gson gson = new Gson();
                Datas datas = gson.fromJson(data, Datas.class);
                List<Datas.DataBean> data1 = datas.getData();
                PullAdapter pullAdapter = new PullAdapter(MainActivity.this, data1);
                xlistView.setAdapter(pullAdapter);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onDrawerSlide(@NonNull View view, float v) {

    }

    @Override
    public void onDrawerOpened(@NonNull View view) {

    }

    @Override
    public void onDrawerClosed(@NonNull View view) {

    }

    @Override
    public void onDrawerStateChanged(int i) {

    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        FragmentTransaction transaction = manager.beginTransaction();
        switch (checkedId){
            case R.id.button:
                transaction.show(frag_01).hide(frag_04).hide(frag_02).hide(frag_03).hide(frag_05);
                break;
            case R.id.button2:
                transaction.show(frag_02).hide(frag_04).hide(frag_01).hide(frag_03).hide(frag_05);
                break;
            case R.id.button3:
                transaction.show(frag_03).hide(frag_04).hide(frag_02).hide(frag_01).hide(frag_05);
                break;
            case R.id.button4:
                transaction.show(frag_04).hide(frag_01).hide(frag_02).hide(frag_03).hide(frag_05);
                break;
            case R.id.button5:
                transaction.show(frag_05).hide(frag_04).hide(frag_02).hide(frag_03).hide(frag_01);
                break;
        }
        transaction.commit();
    }
}

创建fragment

public class Frag_01 extends BaseFragment {
    @Override
    protected int onResID() {
        return R.layout.frag_02;
    }

    @Override
    protected void onView(View view) {

    }

    @Override
    protected void onData() {

    }
}

public class Frag_04 extends BaseFragment {

    private TabLayout tab;
    private ViewPager pager;
    private ImageView img;
    private ArrayList<ChannelItem> tabData;


    @Override
    protected int onResID() {
        return R.layout.frag_01;
    }

    @Override
    protected void onView(View view) {
        tab = (TabLayout)view.findViewById(R.id.tab);
        pager = (ViewPager)view.findViewById(R.id.pager);
        ArrayList<String> tabList=getTabList();
        tabData = DBUtil.getTabData(getActivity());
        pager.setAdapter(new TabAdapter(getChildFragmentManager(),tabData));
        pager.setOffscreenPageLimit(tabList.size());
        tab.setupWithViewPager(pager);
        img = (ImageView)view.findViewById(R.id.img);
    }

    private ArrayList<String> getTabList() {
        ArrayList<String> tablist=new ArrayList<>();
        tablist.add("新闻");
        tablist.add("快讯");
        tablist.add("头条");
        tablist.add("精编公告");
        tablist.add("美股");
        tablist.add("港股");
        tablist.add("基金");
        tablist.add("理财");
        return tablist;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        tabData.clear();
        ArrayList<ChannelItem> tabData = DBUtil.getTabData(getActivity());
        pager.setAdapter(new TabAdapter(getChildFragmentManager(), tabData));

    }

    @Override
    protected void onData() {
        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(getActivity(),ChannelActivity.class),0);

            }

        });
    }}


public class Fragments extends BaseFragment {
    private String path = "http://mnews.gw.com.cn/wap/data/news/";
    private Handler handler = new Handler();
    private int type;
    private int page = 1;
    private PullToRefreshListView pull;
    private ArrayList<Datas.DataBean> list = null;
    private String arr[] = {"xbsjxw", "txs", "toutiao", "news/mobile/jbgg", "news/mobile/mgxw", "news/mobile/ggxw", "news/mobile/jjxw", "news/mobile/lcxw"};

    @Override
    protected int onResID() {
        return R.layout.fragments;
    }

    @Override
    protected void onView(View view) {
        int position=getArguments().getInt("position");
        position=position%3;
        type=position+1;
        pull = (PullToRefreshListView)view.findViewById(R.id.pull);
        pull.setPullToRefreshEnabled(true);
        pull.setMode(PullToRefreshBase.Mode.BOTH);
    }

    @Override
    protected void onData() {
        pull.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                boolean network = NetWork.isNetwork(getActivity());
                if (network){
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            page=1;
                            getAsync(path + arr[type] + "/page_" + page + ".json");
                            pull.onRefreshComplete();
                        }
                    },2000);
                }else {
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            pull.onRefreshComplete();
                        }
                    },2000);
                }
            }
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                boolean network = NetWork.isNetwork(getActivity());
                if (network) {
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            page++;
                            getAsync(path + arr[type] + "/page_" + page + ".json");
                            pull.onRefreshComplete();
                        }
                    }, 2000);
                } else {
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            pull.onRefreshComplete();
                        }
                    }, 2000);
                }
            }
        });
        getInterent();
    }

    private void getInterent() {
        NetInterent netInterent = new NetInterent();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        getActivity().registerReceiver(netInterent, filter);
    }

    private class NetInterent extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            boolean network = NetWork.isNetwork(getActivity());
            if (network) {
                getAsync(path + arr[type] + "/page_" + page + ".json");
            } else {
                Dao mySqlDao = new Dao(getActivity());
                ArrayList<Datas.DataBean> select = mySqlDao.select();
                PullAdapter pullAdapter = new PullAdapter(getActivity(), select);
                pull.setAdapter(pullAdapter);
            }
        }
    }
    private void getAsync(String s) {
        MyAsyncTask myAsyncTask=new MyAsyncTask();
        myAsyncTask.execute(s);
    }
    private class MyAsyncTask extends AsyncTask<String,Integer,String>{

        @Override
        protected String doInBackground(String... strings) {
            return Conntent.isNetConnection(strings[0]);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            try {
                JSONArray jsonArray = new JSONArray(s);
                JSONObject jsonObject = jsonArray.getJSONObject(0);
                String data = jsonObject.toString();
                Log.i("xxx", data);
                Gson gson = new Gson();
                Datas datas = gson.fromJson(data, Datas.class);
                List<Datas.DataBean> data1 = datas.getData();
                Dao mySqlDao = new Dao(getActivity());
                if (page == 1) {
                    list = new ArrayList<>();
                    mySqlDao.delete();
                    mySqlDao.add(data1);
                }
                list.addAll(data1);
                PullAdapter pullAdapter = new PullAdapter(getActivity(), list);
                pull.setAdapter(pullAdapter);
                pull.setSelection(pullAdapter.getCount() - data1.size());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

布局
frag01

<LinearLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#ff0"
    tools:context=".MainActivity">



</LinearLayout>

frag02

<LinearLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

                <android.support.design.widget.TabLayout
                    app:tabMode="scrollable"
                    android:id="@+id/tab"
                    android:layout_width="0dp"
                    android:layout_weight="5"
                    android:layout_height="50dp"></android.support.design.widget.TabLayout>

                <ImageView
                    android:id="@+id/img"
                    android:layout_width="50dp"
                    android:layout_height="wrap_content"
                    android:src="@drawable/kind_liner" />
        </LinearLayout>

        <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"></android.support.v4.view.ViewPager>



</LinearLayout>

fragments

<LinearLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <com.handmark.pulltorefresh.library.PullToRefreshListView
        android:id="@+id/pull"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></com.handmark.pulltorefresh.library.PullToRefreshListView>
</LinearLayout>

网络判断

public class NetWork {
    public static boolean isNetwork(Context context) {
        ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = conn.getActiveNetworkInfo();
        if (info != null) {
            return info.isAvailable();
        }
        return false;
    }
}

public class Conntent {
    public static String isNetConnection(String path) {
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(50000);
            conn.setReadTimeout(5000);
            conn.setRequestMethod("GET");
            if (conn.getResponseCode() == 200) {
                InputStream inputStream = conn.getInputStream();
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = inputStream.read(bytes)) != -1) {
                    stream.write(bytes, 0, len);
                }
                stream.close();
                inputStream.close();
                String data = stream.toString();
                return data;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

适配器

public class TabAdapter extends FragmentPagerAdapter {


    ArrayList<ChannelItem> list;

    public TabAdapter(FragmentManager fm, ArrayList<ChannelItem> tabData) {
        super(fm);
        this.list=tabData;
    }

    @Override
    public Fragment getItem(int i) {
        Fragments fragments=new Fragments();
        Bundle bundle=new Bundle();
        bundle.putInt("position",i);
        fragments.setArguments(bundle);
        return fragments;
    }

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

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return list.get(position).getName();
    }
}

public class PullAdapter extends BaseAdapter {
    private Context context;
    private List<Datas.DataBean> list;
    private static final int TYPE_ONE = 0;
    private static final int TYPE_TWO = 1;
    public PullAdapter(Context context, List<Datas.DataBean> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public int getViewTypeCount() {
        return 2;
    }

    @Override
    public int getItemViewType(int position) {
        return position % 2;
    }
    @Override
    public int getCount() {
        return list.size();
    }

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = null;
        int itemViewType = getItemViewType(position);
        if (convertView == null) {
            switch (itemViewType) {
                case TYPE_ONE:
                    convertView = View.inflate(context, R.layout.item_list2, null);
                    viewHolder = new ViewHolder();
                    viewHolder.img1 = convertView.findViewById(R.id.img1);
                    viewHolder.title1 = convertView.findViewById(R.id.title1);
                    convertView.setTag(viewHolder);
                    break;
                case TYPE_TWO:
                    convertView = View.inflate(context, R.layout.item_list, null);
                    viewHolder = new ViewHolder();
                    viewHolder.title2 = convertView.findViewById(R.id.title2);
                    convertView.setTag(viewHolder);
                    break;
            }
        } else {
            switch (itemViewType) {
                case TYPE_ONE:
                    viewHolder = (ViewHolder) convertView.getTag();
                    break;
                case TYPE_TWO:
                    viewHolder = (ViewHolder) convertView.getTag();
                    break;
            }
        }
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .cacheOnDisk(true)
                .showImageForEmptyUri(R.mipmap.ic_launcher_round)
                .showImageOnFail(R.mipmap.ic_launcher_round)
                .build();
        //赋值
        switch (itemViewType) {
            case TYPE_ONE:
                viewHolder.title1.setText(list.get(position).getTitle());
                String img = list.get(position).getImg();
                ImageLoader.getInstance().displayImage(list.get(position).getImg(), viewHolder.img1, options);
                break;
            case TYPE_TWO:
                viewHolder.title2.setText(list.get(position).getTitle());
                break;
        }
        return convertView;
    }
    class ViewHolder {
        TextView title1, title2;
        ImageView img1;
    }
}

适配器布局
item_list

<LinearLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/title2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hhhhhh"
        android:textSize="20sp" />
</LinearLayout>

item_list2

<LinearLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/img1"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@mipmap/ic_launcher" />

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

ImageLoader

public class MyAppliaction extends ChannelApplication {
    @Override
    public void onCreate() {
        super.onCreate();
        File file = StorageUtils.getCacheDirectory(this);
        ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this)
                .threadPoolSize(5 * 1024 * 1024)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .diskCache(new UnlimitedDiskCache(file))
                .diskCacheFileCount(50)
                .diskCacheSize(50 * 1024 * 1024)
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                .build();
        ImageLoader.getInstance().init(configuration);
    }
}

数据库

public class MySQLite extends SQLiteOpenHelper {

    public MySQLite(Context context) {
        super(context, "bw", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table moni2(title text,url text)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

dao

public class Dao {
    private SQLiteDatabase db;

    public  Dao(Context context) {
        MySQLite mySql = new MySQLite(context);
        db = mySql.getWritableDatabase();
    }

    public void add(List<Datas.DataBean> dataBeans) {
        for (int i = 0; i < dataBeans.size(); i++) {
            ContentValues values = new ContentValues();
            values.put("title", dataBeans.get(i).getTitle());
            values.put("url", dataBeans.get(i).getUrl());
            db.insert("moni2", null, values);
        }
    }

    public ArrayList<Datas.DataBean> select() {
        ArrayList<Datas.DataBean> list = new ArrayList<>();
        Cursor moni2 = db.query("moni2", null, null, null, null, null, null, null);
        if (moni2.moveToFirst()){
            do{
                Datas.DataBean bean = new Datas.DataBean();
                bean.setTitle(moni2.getString(moni2.getColumnIndex("title")));
                bean.setUrl(moni2.getString(moni2.getColumnIndex("url")));
                list.add(bean);
            }while (moni2.moveToNext());
        }
        return list;
    }

    public void delete(){
        db.delete("moni2",null,null);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44310357/article/details/86560713