安卓

安卓原生开发之列表页面实现

2018-12-12  本文已影响56人  测试老杨

思路

1、列表页面(MainActivity)为登录成功的跳转页面
2、使用httpclient发送分页查询的异步请求
3、开发分页查询的接口,对app客户端发送的请求进行处理
4、使用SwipeRefreshLayout组件
5、SwipeRefreshLayout组件只接受一个子组件:即需要刷新的那个组件。使用一个侦听机制来通知拥有该组件的监听器有刷新事件发生,换句话说我们的Activity必须实现通知的接口。该Activity负责处理事件刷新和刷新相应的视图。一旦监听者接收到该事件,就决定了刷新过程中应处理的地方。
6、如果要展示一个“刷新动画”,它必须调用setRefrshing(true),否则取消动画就调用setRefreshing(false)。


image.png

参考资料:

下拉刷新、分页,AsyncTask
android官方下拉刷新控件SwipeRefreshLayout的使用

列表页面设计

Java代码如下:

package com.yangzc.myerp;


import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;

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

import cz.msebera.android.httpclient.Header;


public class MainActivity extends AppCompatActivity implements AbsListView.OnScrollListener {
    private SwipeRefreshLayout swipeRefreshLayout;
    private ListView lv;
    private ArrayAdapter adapter;
    private List<String> list;
    private View footerView;
    private AsyncHttpClient ahc;
    private int page=1;
    private int visibleLastIndex;//用来可显示的最后一条数据的索引

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0x101:
                    if (swipeRefreshLayout.isRefreshing()){
                        adapter.notifyDataSetChanged();
                        swipeRefreshLayout.setRefreshing(false);//设置不刷新
                    }
                    break;
            }
        }
    };

    class MyTextHttpResponseHandler extends TextHttpResponseHandler{
        @Override
        public void onFailure(int statusCode, Header[] headers, String responseBody, Throwable error) {
            //super.onFailure(statusCode, headers, responseBody, error);
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, String responseBody) {
            System.out.println("服务器返回的内容为:"+responseBody);
            //JSONObject obj = (JSONObject)JSON.parse(responseBody);
            JSONArray arr = JSON.parseArray(responseBody);
            for(Object o:arr){
                JSONObject emp = (JSONObject)o;
                JSONObject dept = (JSONObject)emp.get("dept");
                list.add(dept.getString("city")+"-"+dept.getString("dName")+"-"+emp.getString("name"));
            }
            handler.sendEmptyMessage(0x101);//通过handler发送一个更新数据的标记
            //吐司Android studio与web后台数据交互获得的值
            Toast.makeText(MainActivity.this, "刷新了"+arr.size()+"条数据", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        swipeRefreshLayout =  findViewById(R.id.main_srl);
        lv = findViewById(R.id.main_lv);
        footerView = getLayoutInflater().inflate(R.layout.loading_layout,null);
        lv.addFooterView(footerView);
        lv.setOnScrollListener(this);
        list = new ArrayList<>();
        String path="http://192.168.1.14:8080/myerp/list.action?page="+page;
        //创建客户端工具
        ahc=new AsyncHttpClient();
        adapter = new ArrayAdapter(this,R.layout.simple_list,
                android.R.id.text1,list);
        lv.setAdapter(adapter);
        //发送请求
        ahc.get(path,new MyTextHttpResponseHandler());
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page++;
                String path="http://192.168.1.14:8080/myerp/list.action?page="+page;
                //设值提交方式
                ahc.get(path,new MyTextHttpResponseHandler());
                handler.sendEmptyMessage(0x101);//通过handler发送一个更新数据的标记
            }
        });
        lv.removeFooterView(footerView);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if(adapter.getCount() == visibleLastIndex && scrollState == SCROLL_STATE_IDLE){
            //new LoadDataThread().start();
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        visibleLastIndex = firstVisibleItem + visibleItemCount - 1;//减去最后一个加载中那条
    }


}

activity_main.xml配置如下:

<RelativeLayout 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"
    tools:context=".MainActivity" >

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/main_srl"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">


        <ListView
            android:id="@+id/main_lv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </ListView>
    </android.support.v4.widget.SwipeRefreshLayout>


</RelativeLayout>

loading_layout.xml配置如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ProgressBar
        style="?android:attr/progressBarStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/progressBar"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="正在玩命加载中...."
        android:id="@+id/textView2"/>

</RelativeLayout>

simple_list.xml配置如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@android:id/text1"
        android:textColor="#00F"
        android:textSize="30sp"/>

</RelativeLayout>

开发分页查询的接口

后台代码如下:

package com.myerp.handler;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.myerp.dao.EmployeeDAO;
import com.myerp.dao.UserDAO;
import com.myerp.model.Employee;
import com.myerp.model.MyPage;


public class ActionServlet2 extends HttpServlet {
    
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        //1.获取URI
        String uri = request.getRequestURI();
        HttpSession session = request.getSession(); 
        //2.截取URI中的动作
        uri = uri.substring(uri.lastIndexOf("/"),uri.lastIndexOf("."));
        if(uri.equals("/login")){
            //判断用户名和密码
            String uname = request.getParameter("name");
            String pwd = request.getParameter("pwd");
            UserDAO udao = new UserDAO(); 
            try{
                //登录认证
                if(udao.auth(uname,pwd)==false){
                    //登录失败
                    //request.setAttribute("msg","用户名或密码不正确");
                    response.getWriter().print("{\"result\":\"fail\",\"message\":\"用户或密码错误\"}");
                }else{
                    //登录成功,记录用户信息到session中
                    session.setAttribute("uname",uname);
                    //session过期时间设置为5分钟
                    session.setMaxInactiveInterval(300);
                    response.getWriter().print("{\"result\":\"success\",\"message\":\"登录成功\"}");
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }else if(uri.equals("/list")) {
            int pageNum = 1;
            MyPage<Employee> page = null;
            List<Employee> emps = null;
            if(request.getParameter("page")!=null){
                pageNum = Integer.parseInt(request.getParameter("page"));
            }
            //创建dao对象
            EmployeeDAO dao = new EmployeeDAO();
            //调用findAll()方法获取数据
            try {
                page = dao.findAllByPage(pageNum,15);
                emps = page.getList();
                System.out.println(JSON.toJSONString(emps));
                response.getWriter().print(JSON.toJSONString(emps));
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

测试

image.png
image.png
image.png
上一篇下一篇

猜你喜欢

热点阅读