对WebView接口的实现

2021-07-17 05:06

阅读:538

标签:upd   添加   bottom   service   itemid   interface   can   near   hand   

MainActivity

package www.wulian1.com.webview;

import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {

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

        WebView webView=(WebView)findViewById(R.id.wv_zknu);         webView.loadUrl("http://10.10.192.58:83/zknu84/index.html");

        //webView.getSettings().setUseWideViewPort(true);         //webView.getSettings().setLoadWithOverviewMode(true);     } }

MyAdapter

package www.wulian1.com.webview;

import android.app.Activity; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView;

import java.util.List;

/**  * Created by Administrator on 2017/5/18.  */ public class MyAdapter extends BaseAdapter {     public List stuList;     public Activity activity;     public MyAdapter(List stuList,Activity activity){         this.stuList=stuList;         this.activity=activity;     }     public void setList(List stuList)     {         this.stuList=stuList;     }     @Override     public int getCount() {         return this.stuList.size();     }

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

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

    @Override     public View getView(int position, View convertView, ViewGroup parent) {         View view=activity.getLayoutInflater().inflate(R.layout.adapter_item,null);         TextView tv_name=(TextView)view.findViewById(R.id.tv_name);         TextView tv_age=(TextView)view.findViewById(R.id.tv_age);         tv_name.setText(this.stuList.get(position).getName());         tv_age.setText(this.stuList.get(position).getAge()+"");         return view;     } }

PhpActivity

package www.wulian1.com.webview;

import android.content.SharedPreferences; import android.icu.text.IDNA; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.Toast;

import com.google.gson.Gson; import com.google.gson.reflect.TypeToken;

import org.json.JSONObject; import org.xml.sax.ErrorHandler;

import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.util.List;

public class PHPActivity extends AppCompatActivity {

    ListView listView;     List stuList=null;

    private Handler handler = new Handler() {         @Override         public void handleMessage(Message msg) {             super.handleMessage(msg);             String abc = (String) msg.obj;             Toast.makeText(PHPActivity.this, "我输出的字符:" + abc, Toast.LENGTH_SHORT).show();             switch (msg.what) {                 case 200:                     //获取到数据                     //List stuList=(List)msg.obj;                     if(stuList!=null &&stuList.size()>0) {                         MyAdapter myAdapter = new MyAdapter(stuList, PHPActivity.this);                         listView.setAdapter(myAdapter);                     }                     else                     {                         Toast.makeText(PHPActivity.this,"没有数据",Toast.LENGTH_SHORT).show();                     }                     break;                 case 2:                     //获取失败                     Toast.makeText(PHPActivity.this,"获取数据失败",Toast.LENGTH_SHORT).show();                     break;                 case 0:                     //获取发生异常                     Toast.makeText(PHPActivity.this,"获取数据异常",Toast.LENGTH_SHORT).show();                     break;                 default:                     //其他情况                     Toast.makeText(PHPActivity.this,"获取数据异常",Toast.LENGTH_SHORT).show();             }         }     };

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

        listView=(ListView)findViewById(R.id.lv_1);         SharedPreferences sp=this.getSharedPreferences("WebView",MODE_PRIVATE);         String dataString=sp.getString("name","");         if (!"".equals(dataString)){             Gson gson=new Gson();             try{                 JSONObject jsonObject=new JSONObject(dataString);                 String timestamp=jsonObject.getString("timestamp");                 StuManage stuManage=gson.fromJson(dataString,StuManage.class);                 Long nowtimestamp=System.currentTimeMillis();                 Long offday=(nowtimestamp - stuManage.getTimestamp())/(1000*60*60*24);                 Log.d("84","offday="+offday);                 if (offday

        Button btn_getstring = (Button) findViewById(R.id.btn_1);         Button btn_getjson = (Button) findViewById(R.id.btn_2);

        btn_getjson.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                 if (getDataFromCache()) {                     //拿到数据,绑定数据                     MyAdapter myAdapter=new MyAdapter(stuList,PHPActivity.this);                     listView.setAdapter(myAdapter);

                    Log.d("84","cache");                 } else {                     getDataFromService();                     Log.d("84","Service");                 }

                //   Toast.makeText(PHPActivity.this,"准备完成",Toast.LENGTH_SHORT).show();             }         });     }

    private void dataget() {         if (getDataFromCache()){             MyAdapter myAdapter=new MyAdapter(stuList,PHPActivity.this);             listView.setAdapter(myAdapter);         }else {             getDataFromService();         }     }

    public String readInfoStream(InputStream input) throws Exception {         if (input == null) {             throw new Exception("输入流为null");         }         //字节数组         byte[] bcache = new byte[2048];         int readSize = 0;//每次读取的字节长度         int totalSize = 0;//总字节长度         ByteArrayOutputStream infoStream = new ByteArrayOutputStream();         try {             //一次性读取2048字节             while ((readSize = input.read(bcache)) > 0) {                 totalSize += readSize;

                //将bcache中读取的input数据写入infoStream                 infoStream.write(bcache, 0, readSize);             }         } catch (IOException e1) {             throw new Exception("输入流读取异常");         } finally {             try {                 //输入流关闭                 input.close();             } catch (IOException e) {                 throw new Exception("输入流关闭异常");             }         }

        try {             return infoStream.toString("utf-8");         } catch (UnsupportedEncodingException e) {             throw new Exception("输出异常");         }     }

    private boolean getDataFromCache() {         try {             SharedPreferences sharedPreferences = PHPActivity.this.getSharedPreferences("WebView", MODE_PRIVATE);             String data = sharedPreferences.getString("data", "");             //JSONObject jsonObject=new JSONObject(data);             //String code=jsonObject.get("code").toString();             if (data != "") {                 // String datas=jsonObject.get("datas").toString();                 Gson gson = new Gson();                 stuList = gson.fromJson(data, new TypeToken>() {                 }.getType());                 return true;             } else {                 stuList = null;                 return false;             }         } catch (Exception e) {             e.printStackTrace();             stuList = null;             return false;         }     }

    private void getDataFromService() {         final String path = "http://10.10.192.58:83/Json/Json.php";         new Thread() {             @Override             public void run() {                 super.run();                 try {                     URL url = new URL(path);                     HttpURLConnection conn = (HttpURLConnection) url.openConnection();                     conn.setRequestMethod("GET");                     conn.setConnectTimeout(5000);                     Log.d("84", "try -1");                     int code = conn.getResponseCode();                     if (code == 200) {                         Log.d("84", "code==200");                         InputStream inputStream = conn.getInputStream();                         String abc = readInfoStream(inputStream);                         Gson gson = new Gson();                         stuList = gson.fromJson(abc, new TypeToken>() {                         }.getType());                         SharedPreferences sharedPreferences = getSharedPreferences("WebView", MODE_PRIVATE);                         SharedPreferences.Editor editor = sharedPreferences.edit();                         editor.putString("studata", abc);

                        //StuManage stuManage=new StuManage();                         //stuManage.setTimestamp(System.currentTimeMillis());                         //Gson gson=new Gson();

                        Log.d("84", "stulist 获取数据正常");                         Message message = new Message();                         message.obj = abc;                         message.what = 200;                         handler.sendMessage(message);                     } else {                         Message message = new Message();                         message.what = 2;                         handler.sendMessage(message);                         Log.d("84", "请求失败");                     }                 } catch (Exception e) {                     Message message = new Message();                     message.what = 0;                     handler.sendMessage(message);                     Log.d("84", "Exception");                 }             }         }.start();     } }

StudentListactivity

package www.wulian1.com.webview;

import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.ListView; import android.widget.Toast;

import com.google.gson.Gson; import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List;

import www.wulian1.com.webview.MyViews.AutoListView;

 

public class StudentListactivity extends AppCompatActivity  implements AutoListView.OnLoadListener,AutoListView.OnRefreshListener {       List stuList=null;      int pageindex=1;       AutoListView autoListView;      MyAdapter myAdapter;       //定义一个在主线程和子线程直接进行通信的一个**东西  handler       private Handler handler=new Handler(){         @Override         public void handleMessage(Message msg) {             super.handleMessage(msg);             switch (msg.what)             {                 case 200:                     //完成数据绑定                 if(stuList!=null)                 {                     //绑定数据                     if(myAdapter==null)                     {                         myAdapter=new MyAdapter(stuList,StudentListactivity.this);                         autoListView.setAdapter(myAdapter);                         Log.d("zh","autoListView.setAdapter 第一绑定 ");                     }                     else                     {                         myAdapter.setList(stuList);                         myAdapter.notifyDataSetChanged();                         Log.d("zh","加载更多后, notifyDataSetChanged ");                     }

                }                     else                 {                     Toast.makeText(StudentListactivity.this,"没有数据",Toast.LENGTH_SHORT).show();                 }                     autoListView.onRefreshComplete();                     autoListView.onLoadComplete();

                    break;                 case  -1:                     //获取失败                     Toast.makeText(StudentListactivity.this,"获取失败",Toast.LENGTH_SHORT).show();                     break;                 case -2:                     //获取发生异常                     Toast.makeText(StudentListactivity.this,"获取发生异常",Toast.LENGTH_SHORT).show();                     break;                 default:                    //其他情况                     Toast.makeText(StudentListactivity.this,"获取发生异常",Toast.LENGTH_SHORT).show();             }

        }     };

    @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_studentlist);         autoListView=(AutoListView) findViewById(R.id.lv_stulist);         autoListView.setOnRefreshListener(this);         autoListView.setOnLoadListener(this);         //从缓存获取数据 //        if(getDataFromCache()) //        { //            //绑定数据 //            StuAdapter stuAdapter=new StuAdapter(stulist,StudentListactivity.this); //            autoListView.setAdapter(stuAdapter); //        } //        else //        {             //从服务器获取数据             getDataFromService(1);

        //}

    }     private  String inputstream2string(InputStream inputStream)     {         try {             ByteArrayOutputStream baos=new ByteArrayOutputStream();             int length=0;             byte[] buffer=new byte[1024];             while((length=inputStream.read(buffer))!=-1){                 baos.write(buffer, 0, length);             }             inputStream.close();             baos.close();             //或者用这种方法             //byte[] result=baos.toByteArray();             //return new String(result);             return baos.toString();         } catch (Exception e) {             e.printStackTrace();             return "获取失败";         }     }     ///返回true 说明成功从cache拿到数据 返回false 说明没有拿到     private boolean getDataFromCache()     {         try {             SharedPreferences sp = StudentListactivity.this.getSharedPreferences("person", MODE_PRIVATE);             String data = sp.getString("studata", "");  //所有信息             JSONObject jsonObject=new JSONObject(data);             String studata= jsonObject.getString("data");             //是否过期

            if (data != "") {                 Gson gson = new Gson();                 stuList = gson.fromJson(data, new TypeToken>() {                 }.getType());                 //暂时没有时间过期的判断                 return true;             } else {                 stuList=null;                 return false;             }         }catch (Exception ex)         {             ex.printStackTrace();             stuList=null;             return false;         }

    }     private  void getDataFromService(int pindex )     {         final String  path="http://10.10.192.58:83/Json/Stu.php?pageindex="+pindex;         Log.d("zh","path= "+path);         // 开线程         new Thread(){             @Override             public void run() {                 super.run();                 //获取数据                 try {                     URL url = new URL(path);                     HttpURLConnection conn=(HttpURLConnection)url.openConnection();                     conn.setRequestMethod("GET");  //必须大写                     conn.setConnectTimeout(5000);                     Log.d("zh","try -1 ");                     int code=conn.getResponseCode();                     if(code==200)                     {                         Log.d("zh","code==200 ");                         //请求成功                         InputStream inputStream=conn.getInputStream();                         //然后把输入流转为字符串 。上网找一个把流转为字符串的函数                         String abc=inputstream2string(inputStream);                         //解析json字符串                         //先拿到code 。 判断code是否等于200                         //  {"code":200,"pageindex":10,"isover":1,"data":[{"name":"\u5f20\u5b8f90","age":91},{"name":"\u5f20\u5b8f91","age":92},{"name":"\u5f20\u5b8f92","age":93},{"name":"\u5f20\u5b8f93","age":94},{"name":"\u5f20\u5b8f94","age":95},{"name":"\u5f20\u5b8f95","age":96},{"name":"\u5f20\u5b8f96","age":97},{"name":"\u5f20\u5b8f97","age":98},{"name":"\u5f20\u5b8f98","age":99},{"name":"\u5f20\u5b8f99","age":100}]}

                        JSONObject jsonObject=new JSONObject(abc);                         if(jsonObject.getString("code").equals("200"))                         {                             //如果等于200。 服务器数据有效的

                            String studata= jsonObject.getString("data");                             Gson gson=new Gson();

                            //studata=[{"name":"\u5f20\u5b8f90","age":91},。。。。]                             List   stulist_temp = gson.fromJson(studata, new TypeToken>(){}.getType());                             // 程序如果走到这个位置 。说明数据符合json格式。这时候我要把数据使用sharedpreference保存起来                             //android 内存缓存                             SharedPreferences sp=getSharedPreferences("person",MODE_PRIVATE); //person是文件名.                             SharedPreferences.Editor  editor=sp.edit();                             editor.putString("studata",abc);//按照关键字 studata。  把字符串保存起来                             //修改当前yema                             pageindex= Integer.parseInt(jsonObject.getString("pageindex"));                             Log.d("zh","获取的为第"+pageindex+"页的数据");                             if(pageindex>1)                             {                                 stuList.addAll(stulist_temp);                                 Log.d("zh","合并数据");                             }                             else                             {                                 stuList= new ArrayList();                                 stuList=stulist_temp;                                 Log.d("zh","新数据");                             }                             //把数据存储到                             Log.d("zh","stulist 获取数据正常");                             Message message=new Message();                             message.obj=abc;  //定义带有数据的消息                             message.what=200; //200代码获取数据正常                             handler.sendMessage(message);                             Log.d("zh","发送消息正常");                         }                         else                         {                             //返回码不是200的情况                             Message message=new Message();                             message.obj=abc;  //定义带有数据的消息                             message.what=202; //200代码获取数据正常                             handler.sendMessage(message);                             Log.d("zh","发送消息正常");                         }                     }                     else                     {                         //请求失败                         Message message=new Message();                         message.what=-1; //-1  代码获取数据失败                         handler.sendMessage(message);                         Log.d("zh","请求失败");                     }                 }                 catch (Exception ex)                 {                     Message message=new Message();                     message.what=-2; //-1  代码获取数据时发生异常情况                     //发送消息                     handler.sendMessage(message);                     Log.d("zh","Exception");

                }             }         }.start();

    }

    @Override     public void onLoad() {         int pageindex_temp= pageindex+1;         getDataFromService(pageindex_temp);         Log.d("zh","onLoad----加载更多");     }

    @Override     public void onRefresh() {         pageindex=1;

        getDataFromService(pageindex);         Log.d("zh","onRefresh----下拉刷新");

    } }

StuManage

package www.wulian1.com.webview;

/**  * Created by Administrator on 2017/5/18.  */ public class StuManage {     String name;     int age;     long timestamp;

    public long getTimestamp() {         return timestamp;     }

    public void setTimestamp(long timestamp) {         this.timestamp = timestamp;     }

    public int getAge() {         return age;     }

    public void setAge(int age) {         this.age = age;     }

    public String getName() {         return name;     }

    public void setName(String name) {         this.name = name;     } }

Utils

package www.wulian1.com.webview;

import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale;

/**  * Created by Administrator on 2017/5/22.  */ public class Utils {     public static String getCurrentTime(String format) {         Date date = new Date();         SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());         String currentTime = sdf.format(date);         return currentTime;     }

    public static String getCurrentTime() {         return getCurrentTime("yyyy-MM-dd  HH:mm:ss");     } }

MyViews

AutoListView

 

package www.wulian1.com.webview.MyViews;

 

import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.widget.AbsListView; import android.widget.ImageView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView;

 

import www.wulian1.com.webview.R; import www.wulian1.com.webview.Utils;

 

/**  * Created by Administrator on 2017/5/25.  */ public class AutoListView extends ListView implements AbsListView.OnScrollListener {

 

    // 区分当前操作是刷新还是加载     public static final int REFRESH = 0;     public static final int LOAD = 1;

 

    // 区分PULL和RELEASE的距离的大小     private static final int SPACE = 20;

 

    // 定义header的四种状态和当前状态     private static final int NONE = 0;     private static final int PULL = 1;     private static final int RELEASE = 2;     private static final int REFRESHING = 3;     private int state;

 

    private LayoutInflater inflater;     private View header;     private View footer;     private TextView tip;     private TextView lastUpdate;     private ImageView arrow;     private ProgressBar refreshing;

 

    private TextView noData;     private TextView loadFull;     private TextView more;     private ProgressBar loading;

 

    private RotateAnimation animation;     private RotateAnimation reverseAnimation;

 

    private int startY;

 

    private int firstVisibleItem;     private int scrollState;     private int headerContentInitialHeight;     private int headerContentHeight;

 

    // 只有在listview第一个item显示的时候(listview滑到了顶部)才进行下拉刷新, 否则此时的下拉只是滑动listview     private boolean isRecorded;     private boolean isLoading;// 判断是否正在加载     private boolean loadEnable = true;// 开启或者关闭加载更多功能     private boolean isLoadFull;     private int pageSize = 10;

 

    private OnRefreshListener onRefreshListener;     private OnLoadListener onLoadListener;

 

    public AutoListView(Context context) {         super(context);         initView(context);     }

 

    public AutoListView(Context context, AttributeSet attrs) {         super(context, attrs);         initView(context);     }

 

    public AutoListView(Context context, AttributeSet attrs, int defStyle) {         super(context, attrs, defStyle);         initView(context);     }

 

    // 下拉刷新监听     public void setOnRefreshListener(OnRefreshListener onRefreshListener) {         this.onRefreshListener = onRefreshListener;     }

 

    // 加载更多监听     public void setOnLoadListener(OnLoadListener onLoadListener) {         this.loadEnable = true;         this.onLoadListener = onLoadListener;     }

 

    public boolean isLoadEnable() {         return loadEnable;     }

 

    // 这里的开启或者关闭加载更多,并不支持动态调整     public void setLoadEnable(boolean loadEnable) {         this.loadEnable = loadEnable;         this.removeFooterView(footer);     }

 

    public int getPageSize() {         return pageSize;     }

 

    public void setPageSize(int pageSize) {         this.pageSize = pageSize;     }

 

    // 初始化组件     private void initView(Context context) {

 

        // 设置箭头特效         animation = new RotateAnimation(0, -180,                 RotateAnimation.RELATIVE_TO_SELF, 0.5f,                 RotateAnimation.RELATIVE_TO_SELF, 0.5f);         animation.setInterpolator(new LinearInterpolator());         animation.setDuration(100);         animation.setFillAfter(true);

 

        reverseAnimation = new RotateAnimation(-180, 0,                 RotateAnimation.RELATIVE_TO_SELF, 0.5f,                 RotateAnimation.RELATIVE_TO_SELF, 0.5f);         reverseAnimation.setInterpolator(new LinearInterpolator());         reverseAnimation.setDuration(100);         reverseAnimation.setFillAfter(true);

 

        inflater = LayoutInflater.from(context);         footer = inflater.inflate(R.layout.listview_footer, null);         footer.setTag("footer");         loadFull = (TextView) footer.findViewById(R.id.loadFull);         noData = (TextView) footer.findViewById(R.id.noData);         more = (TextView) footer.findViewById(R.id.more);         loading = (ProgressBar) footer.findViewById(R.id.loading);

 

        header = inflater.inflate(R.layout.pull_to_refresh_header, null);         header.setTag("header");         arrow = (ImageView) header.findViewById(R.id.arrow);         tip = (TextView) header.findViewById(R.id.tip);         lastUpdate = (TextView) header.findViewById(R.id.lastUpdate);         refreshing = (ProgressBar) header.findViewById(R.id.refreshing);

 

        // 为listview添加头部和尾部,并进行初始化         headerContentInitialHeight = header.getPaddingTop();         measureView(header);         headerContentHeight = header.getMeasuredHeight();//获取头布局的的高度         topPadding(-headerContentHeight);//设置头布局的位置         this.addHeaderView(header);         this.addFooterView(footer);         this.setOnScrollListener(this);     }

 

    public void onRefresh() {         if (onRefreshListener != null) {             onRefreshListener.onRefresh();         }     }

 

    public void onLoad() {         if (onLoadListener != null) {             onLoadListener.onLoad();         }     }

 

    public void onRefreshComplete(String updateTime) {         lastUpdate.setText(this.getContext().getString(R.string.lastUpdateTime,                 Utils.getCurrentTime()));         state = NONE;         refreshHeaderViewByState(); //改变头部的提示信息     }

 

    // 用于下拉刷新结束后的回调     public void onRefreshComplete() {         String currentTime = Utils.getCurrentTime();         onRefreshComplete(currentTime);     }

 

    // 用于加载更多结束后的回调     public void onLoadComplete() {         isLoading = false;     }

 

    @Override     public void onScroll(AbsListView view, int firstVisibleItem,                          int visibleItemCount, int totalItemCount) {         this.firstVisibleItem = firstVisibleItem;     }

 

    @Override     public void onScrollStateChanged(AbsListView view, int scrollState) {         this.scrollState = scrollState;         ifNeedLoad(view, scrollState);     }

 

    // 根据listview滑动的状态判断是否需要加载更多     private void ifNeedLoad(AbsListView view, int scrollState) {         if (!loadEnable) {             return;         }         try {             if (scrollState == OnScrollListener.SCROLL_STATE_IDLE                     && !isLoading                     && view.getLastVisiblePosition() == view                     .getPositionForView(footer) && !isLoadFull) {                 onLoad();                 isLoading = true;             }         } catch (Exception e) {         }     }

 

    /**      * 监听触摸事件,解读手势      */     @Override     public boolean onTouchEvent(MotionEvent ev) {         switch (ev.getAction()) {             case MotionEvent.ACTION_DOWN:                 if (firstVisibleItem == 0) {                     isRecorded = true;                     startY = (int) ev.getY();                 }                 break;             case MotionEvent.ACTION_CANCEL:             case MotionEvent.ACTION_UP:                 if (state == PULL) {                     state = NONE;                     refreshHeaderViewByState();                 } else if (state == RELEASE) {                     state = REFRESHING;                     refreshHeaderViewByState();                     onRefresh();                 }                 isRecorded = false;                 break;             case MotionEvent.ACTION_MOVE:                 whenMove(ev);                 break;         }         return super.onTouchEvent(ev);     }

 

    // 解读手势,刷新header状态     private void whenMove(MotionEvent ev) {         if (!isRecorded) {             return;         }         int tmpY = (int) ev.getY();         int space = tmpY - startY;         int topPadding = space - headerContentHeight;         switch (state) {             case NONE:                 if (space > 0) {                     state = PULL;                     refreshHeaderViewByState();                 }                 break;             case PULL:                 topPadding(topPadding);                 if (scrollState == SCROLL_STATE_TOUCH_SCROLL                         && space > headerContentHeight + SPACE) {                     state = RELEASE;                     refreshHeaderViewByState();                 }                 break;             case RELEASE:                 topPadding(topPadding);                 if (space > 0 && space

 

    }

 

    // 调整header的大小。其实调整的只是距离顶部的高度。     private void topPadding(int topPadding) {         header.setPadding(header.getPaddingLeft(), topPadding,                 header.getPaddingRight(), header.getPaddingBottom());         header.invalidate();     }

 

    /**      * 这个方法是根据结果的大小来决定footer显示的。      *

     * 这里假定每次请求的条数为10。如果请求到了10条。则认为还有数据。如过结果不足10条,则认为数据已经全部加载,这时footer显示已经全部加载      *

     *      * @param resultSize      */     public void setResultSize(int resultSize,String isover) {         if (resultSize == 0) {             isLoadFull = true;             loadFull.setVisibility(View.GONE);             loading.setVisibility(View.GONE);             more.setVisibility(View.GONE);             noData.setVisibility(View.VISIBLE);         } else if (isover.equals("1")) {             isLoadFull = true;             loadFull.setVisibility(View.VISIBLE);             loading.setVisibility(View.GONE);             more.setVisibility(View.GONE);             noData.setVisibility(View.GONE);         } else if (isover.equals("0")) {             isLoadFull = false;             loadFull.setVisibility(View.GONE);             loading.setVisibility(View.VISIBLE);             more.setVisibility(View.VISIBLE);             noData.setVisibility(View.GONE);         }     }

 

    // 根据当前状态,调整header     private void refreshHeaderViewByState() {         switch (state) {             case NONE:                 topPadding(-headerContentHeight);                 tip.setText(R.string.pull_to_refresh);                 refreshing.setVisibility(View.GONE);                 arrow.clearAnimation();                 arrow.setImageResource(R.mipmap.pull_to_refresh_arrow);                 break;             case PULL:                 arrow.setVisibility(View.VISIBLE);                 tip.setVisibility(View.VISIBLE);                 lastUpdate.setVisibility(View.VISIBLE);                 refreshing.setVisibility(View.GONE);                 tip.setText(R.string.pull_to_refresh);                 arrow.clearAnimation();                 arrow.setAnimation(reverseAnimation);                 break;             case RELEASE:                 arrow.setVisibility(View.VISIBLE);                 tip.setVisibility(View.VISIBLE);                 lastUpdate.setVisibility(View.VISIBLE);                 refreshing.setVisibility(View.GONE);                 tip.setText(R.string.pull_to_refresh);                 tip.setText(R.string.release_to_refresh);                 arrow.clearAnimation();                 arrow.setAnimation(animation);                 break;             case REFRESHING:                 topPadding(headerContentInitialHeight);                 refreshing.setVisibility(View.VISIBLE);                 arrow.clearAnimation();                 arrow.setVisibility(View.GONE);                 tip.setVisibility(View.GONE);                 lastUpdate.setVisibility(View.GONE);                 break;         }     }

 

    // 用来计算header大小的。比较隐晦。因为header的初始高度就是0,貌似可以不用。     private void measureView(View child) {         ViewGroup.LayoutParams p = child.getLayoutParams();         if (p == null) {             p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,                     ViewGroup.LayoutParams.WRAP_CONTENT);         }         int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);         int lpHeight = p.height;         int childHeightSpec;         if (lpHeight > 0) {             childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,                     MeasureSpec.EXACTLY);         } else {             childHeightSpec = MeasureSpec.makeMeasureSpec(0,                     MeasureSpec.UNSPECIFIED);         }         child.measure(childWidthSpec, childHeightSpec);     }

 

    /*      * 定义下拉刷新接口      */     public interface OnRefreshListener {         public void onRefresh();     }

 

    /*      * 定义加载更多接口      */     public interface OnLoadListener {         public void onLoad();     }     public boolean isFooter(View view)     {         Object tag=view.getTag();         if(tag!=null) {             if (view.getTag().equals(footer.getTag())) {                 return true;             } else {                 return false;             }         }         else         {             return false;         }     }     public boolean isHeader(View view)     {         Object tag=view.getTag();         if(tag!=null) {             if (view.getTag().equals(header.getTag())) {                 return true;             } else {                 return false;             }         }         else         {             return false;         }     }

 

}

 

对WebView接口的实现

标签:upd   添加   bottom   service   itemid   interface   can   near   hand   

原文地址:http://www.cnblogs.com/zonghao/p/7067486.html


评论


亲,登录后才可以留言!