`

listview 滑动分页 contextmenu菜单用法

阅读更多

这节将阐述一个listview 的滑动分页效果,和contextmenu用法,根据listview选项弹出一个contextmenu菜单,再根据所选择的菜单项执行查看详情或者编辑提交,效果如图:

自定义listview项:

 

contextmenu,长按选项唤出:

选择详情菜单:


选择编辑菜单:



 滑动分页,当大滚动到最好一项时,自动加载下一页:
 

 
 代码:

package com.gk.view;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.gk.R;
import com.gk.data.AnswerServiceHelper;
import com.gk.data.TaskByPageHelper;
import com.gk.data.UserDataServiceHelper;
import com.gk.model.Health;

public class taskView extends Activity implements OnCreateContextMenuListener,
  OnScrollListener {

 private View view;
 private ListView listview;
 private TextView cardid;
 private TextView recorder;
 private TextView consultationtype;
 private TextView consultationexpert;
 private TextView consultationcontent;
 private TextView answer;
 private TextView answer1;
 private TextView clientname;
 private AlertDialog selfdialog;
 private Health health;

 private ProgressBar progressBar;
 private ProgressDialog progressdialog;
 private int lastItem = 0;
 private SimpleAdapter adapter;
 private int page = 1;
 private int allpage = 1;
 private List<Health> heallist = new ArrayList<Health>();
 private List<Map<String, Object>> httpResult = new ArrayList<Map<String, Object>>();

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  // LayoutInflater inflater = (LayoutInflater)
  // getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
  // view = inflater.inflate(R.layout.taskview, null);
  adapter = new SimpleAdapter(this, httpResult, R.layout.taskview,
    new String[] { "title", "info", "img" }, new int[] {
      R.id.title, R.id.info, R.id.img });
  listview = new ListView(this);
  listview.setAdapter(adapter);
  listview.setOnCreateContextMenuListener(this);
  listview.setOnScrollListener(this);
  setContentView(listview);
  dealData();
 }

 @Override
 public void onCreateContextMenu(ContextMenu menu, View v,
   ContextMenuInfo menuInfo) {
  menu.setHeaderTitle("详情菜单");
  menu.add(0, 0, 1, "查看详情");
  menu.add(0, 1, 2, "编辑解答");
  menu.add(0, 2, 3, "取消查看");
 }

 @Override
 public boolean onContextItemSelected(MenuItem item) {
  AdapterContextMenuInfo menuinfo = (AdapterContextMenuInfo) item
    .getMenuInfo();
  health = heallist.get(menuinfo.position);
  List<NameValuePair> params = new ArrayList<NameValuePair>();
  params.add(new BasicNameValuePair("iid", health.getIid().toString()));
  String host = UserDataServiceHelper.getHost();
  String uri = host + "/task.do?task=getHealthById";
  Bundle bundle = UserDataServiceHelper.getObjectByid(uri, params);

  if (item.getItemId() == 0) {
   if (bundle != null) {
    health = (Health) bundle.get("health");

    // 创建对话框
    LayoutInflater inflater = (LayoutInflater) getApplicationContext()
      .getSystemService(LAYOUT_INFLATER_SERVICE);
    view = inflater.inflate(R.layout.detail, null);
    // 设置
    cardid = (TextView) view.findViewById(R.id.cardid);
    recorder = (TextView) view.findViewById(R.id.recorder);
    consultationtype = (TextView) view
      .findViewById(R.id.consultationtype);
    consultationexpert = (TextView) view
      .findViewById(R.id.consultationexpert);
    consultationcontent = (TextView) view
      .findViewById(R.id.consultationcontent);
    answer = (TextView) view.findViewById(R.id.answer);
    clientname = (TextView) view.findViewById(R.id.clientname);

    cardid.setText(health.getCardid());
    recorder.setText(health.getRecorder());
    consultationtype.setText(health.getConsultationtype());
    consultationexpert.setText(health.getConsultationexpert());
    consultationcontent.setText(health.getConsultationcontent());
    answer.setText(health.getAnswer());
    clientname.setText(health.getName());

    AlertDialog.Builder ad = new AlertDialog.Builder(taskView.this);
    ad.setView(view);
    ad.setTitle("详情").create().show();
    Toast.makeText(this, page + "/" + allpage + "页",
      Toast.LENGTH_LONG).show();
   }

  }

  if (item.getItemId() == 1) {
   if (bundle != null) {
    health = (Health) bundle.get("health");

    // 创建对话框
    LayoutInflater inflater = (LayoutInflater) getApplicationContext()
      .getSystemService(LAYOUT_INFLATER_SERVICE);
    view = inflater.inflate(R.layout.detail, null);
    // 设置
    cardid = (TextView) view.findViewById(R.id.cardid);
    recorder = (TextView) view.findViewById(R.id.recorder);
    consultationtype = (TextView) view
      .findViewById(R.id.consultationtype);
    consultationexpert = (TextView) view
      .findViewById(R.id.consultationexpert);
    consultationcontent = (TextView) view
      .findViewById(R.id.consultationcontent);
    answer = (TextView) view.findViewById(R.id.answer);
    answer.setVisibility(View.INVISIBLE);// 设置不可见
    answer1 = (TextView) view.findViewById(R.id.answer1);
    answer1.setVisibility(View.VISIBLE);// 设置可见
    clientname = (TextView) view.findViewById(R.id.clientname);

    cardid.setText(health.getCardid());
    recorder.setText(health.getRecorder());
    consultationtype.setText(health.getConsultationtype());
    consultationexpert.setText(health.getConsultationexpert());
    consultationcontent.setText(health.getConsultationcontent());
    answer1.setText(health.getAnswer());
    clientname.setText(health.getName());

    AlertDialog.Builder ad = new AlertDialog.Builder(taskView.this);
    ad.setView(view);
    ad.setTitle("解答");
    selfdialog = ad.create();

    selfdialog.setButton("提交", new OnClickListener() {
     @Override
     public void onClick(DialogInterface dialog, int which) {
      String host = UserDataServiceHelper.getHost();
      String uri = host + "/task.do?task=updateAnswer";
      String answer = answer1.getText().toString();
      String iid = health.getIid().toString();
      List<NameValuePair> params = new ArrayList<NameValuePair>();
      params.add((new BasicNameValuePair("answer", answer)));
      params.add((new BasicNameValuePair("iid", iid)));

      String state = AnswerServiceHelper.updateAnswer(uri,
        params);

      Toast.makeText(taskView.this, "提示:" + state,
        Toast.LENGTH_LONG).show();
     }
    });
    selfdialog.setButton2("取消", new OnClickListener() {

     @Override
     public void onClick(DialogInterface dialog, int which) {
      selfdialog.cancel();
     }
    });
    selfdialog.show();
   }

  }
  return super.onContextItemSelected(item);
 }

 private static Bundle bundle;

 public Bundle getBundle() {
  bundle = getIntent().getExtras();
  return bundle;
 }

 private List<Map<String, Object>> getMapData(List<Health> httpResult) {
  List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
  for (Iterator<Health> it = httpResult.iterator(); it.hasNext();) {
   Map<String, Object> map = new HashMap<String, Object>();
   Health health = (Health) it.next();
   map.put("title", health.getName());
   map.put("info", health.getConsultationexpert());
   map.put("img", R.drawable.ic_launcher);
   list.add(map);
  }
  return list;
 }

 public List<Health> getData(int page) {
  String overflag = getIntent().getStringExtra("overflag");
  String consultationexpert = getIntent().getStringExtra(
    "consultationexpert");
  List<NameValuePair> params = new ArrayList<NameValuePair>();
  params.add(new BasicNameValuePair("overflag", overflag));
  params.add(new BasicNameValuePair("consultationexpert",
    consultationexpert));
  params.add(new BasicNameValuePair("page", String.valueOf(page)));
  TaskByPageHelper task = new TaskByPageHelper();
  String host = UserDataServiceHelper.getHost();
  String uri = host + "/task.do?task=getTask";
  Bundle bundle = task.getTask(uri, params);
  page = Integer.valueOf(bundle.getString("page"));
  allpage = Integer.valueOf(bundle.getString("allpage"));
  List<Health> healist = (List<Health>) bundle.get("list");
  return healist;
 }

 private void dealData() {
  List<Health> data = getData(this.page);
  // heallist =data;
  List<Map<String, Object>> a = getMapData(data);
  for (int i = 0, size = a.size(); i < size; i++) {
   httpResult.add(a.get(i));
   heallist.add(data.get(i));
  }
  adapter.notifyDataSetChanged();
 }

 @Override
 public void onScrollStateChanged(AbsListView view, int scrollState) {
  if (lastItem == adapter.getCount()
    && scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
   if (page == allpage || page > allpage) {
    Toast.makeText(this, "尾页", Toast.LENGTH_LONG).show();
   } else {
    page = page + 1;
    progressdialog =ProgressDialog.show(taskView.this, "请等待...", "正在加载...");
    refreshHandler.sleep(100);
    Toast.makeText(this, page + "/" + allpage + "页",
      Toast.LENGTH_LONG).show();
   }
  }
 }

 @Override
 public void onScroll(AbsListView view, int firstVisibleItem,
   int visibleItemCount, int totalItemCount) {
  lastItem = firstVisibleItem + visibleItemCount;
 }
 
 //加载
 private RefreshHandler refreshHandler =new RefreshHandler();
 
 //处理器
 class RefreshHandler extends Handler{

  @Override
  public void handleMessage(Message msg) {
   try{
    dealData();
   }catch(Exception e){
    e.printStackTrace();
   }finally{
    progressdialog.dismiss();//解除进度条
   }
  }
  
  public void sleep(long delayMillis){
   this.removeMessages(0);
   sendMessageDelayed(obtainMessage(0), delayMillis);
  }
 }
}

 

taskview.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="horizontal" android:layout_width="fill_parent"
 android:layout_height="fill_parent" >


 <ImageView android:id="@+id/img" 
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" 
  android:layout_margin="5px"/>

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

  <TextView android:id="@+id/title" 
   android:layout_width="wrap_content"
   android:layout_height="wrap_content" 
   android:textColor="#FFFFFFFF"
   android:textSize="15px" />
  <TextView android:id="@+id/info" 
   android:layout_width="wrap_content"
   android:layout_height="wrap_content" 
   android:textColor="#FFFFFFFF"
   android:textSize="15px" />

 </LinearLayout>
<!--  <ListView
     android:id="@id/android:list"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:drawSelectorOnTop="false"
     android:scrollbars="vertical"/> -->

</LinearLayout>

  

后台逻辑:

package com.gk.data;

import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.SparseArray;

import com.gk.model.Agent;
import com.gk.model.Health;
import com.gk.util.BundleUtil;
public class TaskByPageHelper {


 private static HttpResponse httpresponse =null;
 
 public static Bundle getTask(String uri,List<NameValuePair> params){
  HttpPost httqRequest =new HttpPost(uri);
  try{
   httqRequest.setEntity(new  UrlEncodedFormEntity(params,HTTP.UTF_8));
   httpresponse = new DefaultHttpClient().execute(httqRequest);
   if(httpresponse.getStatusLine().getStatusCode() == 200){
    //取出应答字符串
   String strResult = EntityUtils.toString(httpresponse.getEntity());
   JSONObject json =new JSONObject(strResult);
   String pageSize =json.getString("pageSize");
   String allcount = json.getString("allcount");
   String allpage = json.getString("allpage");
   String page = json.getString("page");
   
   JSONArray jsonarray = json.getJSONArray("list");
   List<Health> healthlist =new ArrayList<Health>();
   for(int i=0; i<jsonarray.length(); i++){
    JSONObject object =(JSONObject)jsonarray.get(i);
    Health health =new Health();
    health.setIid(object.getInt("iid"));
    health.setConsultationexpert(object.getString("consultationexpert"));
    health.setName(object.getString("name"));
    healthlist.add(health);
   }
   
   Bundle bundle =new Bundle();
   bundle.putString("pageSize", pageSize);
   bundle.putString("allcount", allcount);
   bundle.putString("allpage",allpage);
   bundle.putString("page", page);
   bundle.putSerializable("list", (Serializable) healthlist);
   
   System.out.println(json.toString());
   return bundle;
  }else{
   return null;
  }
  }catch(ClientProtocolException e){
   e.printStackTrace();
  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;
 }
 
}

 

  • 描述: 自定义listview
  • 大小: 39.2 KB
  • 描述: contextmenu效果
  • 大小: 45.1 KB
  • 描述: 详情
  • 大小: 52.3 KB
  • 描述: 编辑
  • 大小: 61.5 KB
  • 描述: 滑动分页
  • 大小: 44.4 KB
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics