listview+DrawerLayout

public class MainActivity extends AppCompatActivity {

    private PullToRefreshListView ptr_lv;
    private DrawerLayout drawer_layout;
    private PtrLvAdapter adapter;
    private Handler myHandler = new Handler();
    private List<Result.DataBean> list = new ArrayList<>();
    private int index = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //查找控件
        initView();
        //侧拉监听
        drawer_layout.setDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {

            }

            @Override
            public void onDrawerOpened(View drawerView) {
                Toast.makeText(MainActivity.this, "侧拉菜单已打开", Toast.LENGTH_SHORT).show();
                Log.i("TAG", "侧拉打开了");
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                Toast.makeText(MainActivity.this, "侧拉菜单已关闭", Toast.LENGTH_SHORT).show();
                Log.i("TAG", "侧拉关闭了");
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });
        //判断网络
        boolean conn = NetStateUtil.isConn(MainActivity.this);
        //true代表网络已连接
        if (conn) {
            Toast.makeText(this, "联网了", Toast.LENGTH_SHORT).show();
            //初始化得到数据
            getNetData();
            //设置适配器
            setAdapter();
            //配置上拉刷新,下拉加载
            setPtrListView();

        } else {
            Toast.makeText(this, "没联网,请连接网络", Toast.LENGTH_SHORT).show();
        }

    }

    private void setPtrListView() {
        ptr_lv.setMode(PullToRefreshBase.Mode.BOTH);

        //配置刷新的设置
        ILoadingLayout startLabels = ptr_lv.getLoadingLayoutProxy(true, false);
        startLabels.setPullLabel("下拉刷新");
        startLabels.setRefreshingLabel("正在拉");
        startLabels.setReleaseLabel("放开刷新");
        ILoadingLayout endLabels = ptr_lv.getLoadingLayoutProxy(false, true);
        endLabels.setPullLabel("上拉刷新");
        endLabels.setRefreshingLabel("正在载入...");
        endLabels.setReleaseLabel("放开刷新...");

        //设置刷新的监听
        ptr_lv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {//下拉刷新的回调
                //下拉刷新的数据,显示在listview列表的最上面
                addtoTop();
                myHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //刷新完成,必须在异步下完成
                        ptr_lv.onRefreshComplete();

                    }
                }, 1000);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {//上拉加载的回调
                //加载更多的数据,添加到集合列表的最后面
                addtoBottom();
                myHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //刷新完成,必须在异步下完成
                        ptr_lv.onRefreshComplete();
                    }
                }, 1000);
            }
        });


    }

    //刷新
    private void addtoTop() {
        //清空集合,重新加载
        list.clear();
        //得到数据
        getNetData();
        //设置适配器
        setAdapter();
    }

    //记载更多
    private void addtoBottom() {
        index += 20;
        MyTask myTask = new MyTask(new MyTask.Icallbacks() {
            @Override
            public void updateUiByjson(String jsonstr) {
                Gson gson = new Gson();
                //解析数据
                Result newsBean = gson.fromJson(jsonstr, Result.class);
                List<Result.DataBean> data = newsBean.getData();
                //将得到的数据放入集合
                list.addAll(data);
            }
        });
        myTask.execute("http://www.93.gov.cn/93app/data.do?channelId=0&startNum=" + index);
        //设置适配器
        setAdapter();
    }

    private void initView() {
        //查找控件
        ptr_lv = (PullToRefreshListView) findViewById(R.id.ptr_lv);
        drawer_layout = (DrawerLayout) findViewById(R.id.drawer_layout);
    }

    //通过网络获取数据
    public void getNetData() {
        MyTask myTask = new MyTask(new MyTask.Icallbacks() {
            @Override
            public void updateUiByjson(String jsonstr) {
                Gson gson = new Gson();
                Result newsBean = gson.fromJson(jsonstr, Result.class);
                List<Result.DataBean> data = newsBean.getData();
                list.addAll(data);
            }
        });
        myTask.execute("http://www.93.gov.cn/93app/data.do?channelId=0&startNum=0");

    }

    //设置适配器
    private void setAdapter() {
        if (adapter == null) {
            //记载适配器
            adapter = new PtrLvAdapter(list, MainActivity.this);
            ptr_lv.setAdapter(adapter);
        } else {
            //更新适配器
            adapter.notifyDataSetChanged();
        }


    }

    
}


//适配器
public class PtrLvAdapter extends BaseAdapter {
    private List<Result.DataBean> list;
    private Context context;
    private final int TYPE_WORD = 0;
    private final int TYPE_IMG = 1;

    public PtrLvAdapter(List<Result.DataBean> list, Context context) {
        this.list = list;
        this.context = context;
    }
    //得到类型数量
    @Override
    public int getViewTypeCount() {
        return 2;
    }
    //判断字段是否为空
    @Override
    public int getItemViewType(int position) {
        if (list.get(position).getIMAGEURL() == null) {
            return TYPE_WORD;
        } else {
            return TYPE_IMG;
        }
    }

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

    @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) {
        //优化
        int type = getItemViewType(position);
        switch (type) {
            case TYPE_WORD:
                ViewHolderWord holderWord;
                if (convertView == null) {

                    convertView = View.inflate(context, R.layout.item_word, null);
                    holderWord = new ViewHolderWord();
                    holderWord.textView = (TextView) convertView.findViewById(R.id.text_item2);
                    convertView.setTag(holderWord);
                } else {
                    holderWord = (ViewHolderWord) convertView.getTag();
                }
                holderWord.textView.setText(list.get(position).getTITLE());
                return convertView;
            case TYPE_IMG:
                ViewHolderImg holderImg;
                if (convertView == null) {

                    convertView = View.inflate(context, R.layout.text_img, null);
                    holderImg = new ViewHolderImg();
                    holderImg.textView = (TextView) convertView.findViewById(R.id.text_item);
                    holderImg.imageView = (ImageView) convertView.findViewById(R.id.img_item);
                    convertView.setTag(holderImg);
                } else {
                    holderImg = (ViewHolderImg) convertView.getTag();
                }
                holderImg.textView.setText(list.get(position).getTITLE());
                ImageLoader.getInstance().displayImage(list.get(position).getIMAGEURL().toString(), holderImg.imageView, ImageLoaderUtil.getImageOptions());
                return convertView;

        }


        return convertView;
    }


    class ViewHolderImg {
        ImageView imageView;
        TextView textView;

    }

    class ViewHolderWord {
        TextView textView;
    }
}



//工具类
public class ImageLoaderUtil {
    /**
     * ImageLoader的配置
     *
     * @param context
     */
    public static void initConfig(Context context) {
        //加载到sd卡上
        File cacheFile = new File(Environment.getExternalStorageDirectory() + "/" + "caches");

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                .memoryCacheExtraOptions(480, 800)//缓存图片最大的长和宽
                .threadPoolSize(2)//线程池的数量
                .threadPriority(4)
                .memoryCacheSize(2 * 1024 * 1024)//设置内存缓存区大小
                .diskCacheSize(20 * 1024 * 1024)//设置sd卡缓存区大小
                .diskCache(new UnlimitedDiskCache(cacheFile))//自定义缓存目录
                .writeDebugLogs()//打印日志内容
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())//给缓存的文件名进行md5加密处理
                .build();

        ImageLoader.getInstance().init(config);

    }

    /**
     * 获取图片设置类
     *
     * @return
     */
    public static DisplayImageOptions getImageOptions() {

        DisplayImageOptions optionsoptions = new DisplayImageOptions.Builder()
                .cacheInMemory(true)//使用内存缓存
                .cacheOnDisk(true)//使用磁盘缓存
                .bitmapConfig(Bitmap.Config.RGB_565)//设置图片格式
                .showImageOnLoading(R.mipmap.ic_launcher)//设置正在下载的图片
                .showImageForEmptyUri(R.mipmap.ic_launcher)//url为空或请求的资源不存在时
                .showImageOnFail(R.mipmap.ic_launcher)//下载失败时显示的图片
                .displayer(new RoundedBitmapDisplayer(30))//设置圆角,参数代表度数
                .build();

        return optionsoptions;

    }
}


//工具类
public class MyTask extends AsyncTask<String, Void, String> {
    //申请一个接口类对象
    private Icallbacks icallbacks;

    //将无参构造设置成私有的,使之在外部不能够调用
    private MyTask() {
    }

    //定义有参构造方法
    public MyTask(Icallbacks icallbacks) {
        this.icallbacks = icallbacks;
    }

    @Override
    protected String doInBackground(String... params) {
        String str = "";

        try {
            //使用HttpUrlConnection
            URL url = new URL(params[0]);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);

            if (connection.getResponseCode() == 200) {
                InputStream inputStream = connection.getInputStream();
                //调用工具类中的静态方法
                str = StreamToString.streamToStr(inputStream, "utf-8");
            }

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

        return str;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        //解析,封装到bean,更新ui组件
        icallbacks.updateUiByjson(s);


    }

    //定义一个接口
    public interface Icallbacks {
        /**
         * 根据回传的json字符串,解析并更新页面组件
         *
         * @param jsonstr
         */
        void updateUiByjson(String jsonstr);
    }

}


//工具类
public class NetStateUtil {
    /*
* 判断网络连接是否已开
* true 已打开  false 未打开
* */
    public static boolean isConn(Context context) {
        boolean bisConnFlag = false;
        ConnectivityManager conManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo network = conManager.getActiveNetworkInfo();
        if (network != null) {
            bisConnFlag = conManager.getActiveNetworkInfo().isAvailable();
        }
        return bisConnFlag;
    }

    /**
     * 当判断当前手机没有网络时选择是否打开网络设置
     *
     * @param context
     */
    public static void showNoNetWorkDlg(final Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setIcon(R.mipmap.ic_launcher)         //
                .setTitle(R.string.app_name)            //
                .setMessage("当前无网络").setPositiveButton("设置", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 跳转到系统的网络设置界面
                Intent intent = null;
                // 先判断当前系统版本
                if (android.os.Build.VERSION.SDK_INT > 10) {  // 3.0以上
                    intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                } else {
                    intent = new Intent();
                    intent.setClassName("com.android.settings", "com.android.settings.WirelessSettings");
                }
                context.startActivity(intent);

            }
        }).setNegativeButton("知道了", null).show();
    }
}

 
//工具类
public class StreamToString {
    public static String streamToStr(InputStream inputStream, String chartSet) {

        StringBuilder builder = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, chartSet));
            String con;
            while ((con = br.readLine()) != null) {
                builder.append(con);
            }

            br.close();
            return builder.toString();


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


        return "";
    }
}


//调用工具类

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        ImageLoaderUtil.initConfig(this);
    }
}


//activity-main

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:ptr="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.hongliang1510c20171026.MainActivity">

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

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="30dp"
                android:background="#00C364"
                android:gravity="center"
                android:text="科目二"
                android:textColor="#fff"
                android:textSize="20dp" />

            <com.handmark.pulltorefresh.library.PullToRefreshListView
                android:id="@+id/ptr_lv"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                ptr:ptrAnimationStyle="flip"
                ptr:ptrDrawable="@drawable/default_ptr_flip"
                ptr:ptrHeaderBackground="#383838"
                ptr:ptrHeaderTextColor="#FFFFFF"></com.handmark.pulltorefresh.library.PullToRefreshListView>

        </LinearLayout>

        <LinearLayout
            android:layout_width="240dp"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:background="#fff"
            android:gravity="center"
            android:orientation="vertical">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="30dp"
                android:src="@mipmap/ic_launcher" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:text="我的消息" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:text="教学视频" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:text="我的成绩" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:text="学车日记" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:text="文章收藏" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:text="文章足迹" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:text="教员中心" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:text="设置" />
        </LinearLayout>

    </android.support.v4.widget.DrawerLayout>



</LinearLayout>


//item_word

<?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:gravity="center_vertical">


    <TextView
        android:id="@+id/text_item2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp"
        android:layout_weight="1"
        android:ellipsize="end"
        android:gravity="center_vertical"
        android:lines="2"
        android:textSize="30dp" />

</LinearLayout>

//text_img

<?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:gravity="center_vertical">

    <ImageView
        android:id="@+id/img_item"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_margin="10dp" />

    <TextView
        android:id="@+id/text_item"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:ellipsize="end"
        android:lines="2"
        android:textSize="20dp" />

</LinearLayout>


/要加的权限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.hongliang1510c20171026">

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

    <application
        android:allowBackup="true"
        android:name=".MyApplication"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值