`

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
分享到:
评论

相关推荐

    Android ListView 滑动分页

    本篇文章将详细讲解如何实现Android ListView的滑动分页功能。 首先,理解滑动分页的基本原理。滑动分页基于“按需加载”的概念,即仅在用户滚动到列表底部时才请求服务器获取新的数据。这样避免了一次性加载所有...

    android listview左右滑动分页

    http://blog.csdn.net/icqapp/article/details/24978057 详看效果图...android listview左右滑动分页(viewpager嵌套listview进行分页),焦点图带圆焦点 先敬告学者:如在此项目上运行不了的直接找到本人QQ:508181017,

    ListView水平滑动分页

    然而,通常ListView默认是垂直滚动的,而“ListView水平滑动分页”则是将ListView的功能扩展到支持水平滑动,以此来实现类似ViewPager的效果。这个特性使得开发者可以在有限的屏幕空间内展示更多的信息,增强用户...

    android ListView滑动分页加载和点击分页加载,以及复用convertView综合案例

    1. **监听滑动事件**:使用AbsListView的OnScrollListener监听ListView的滑动状态。当滚动到底部时,`onScrollStateChanged()`方法会被调用,通过判断滚动状态和最后一个可见项的位置来确定是否需要加载更多数据。 ...

    android实现仿qq中listview滑动菜单

    "仿QQ中listview滑动菜单"是一个常见的设计模式,它允许用户通过滑动列表项来展示隐藏的菜单,比如删除或打开按钮。这种功能可以提升应用的互动性和易用性。接下来,我们将深入探讨如何在Android中实现这样的滑动...

    android Listview下拉刷新 上拉(滑动分页)加载更多

    总之,下拉刷新和上拉加载更多是提升Android应用用户体验的关键特性,通过合理使用开源库和自定义事件监听,可以轻松地在ListView中实现这些功能。开发者可以根据项目需求选择合适的库,或者自定义实现,以满足各种...

    android ListView下拉分页

    提供下拉分页刷新列表 case MotionEvent.ACTION_UP: if (!isVerticalScrollBarEnabled()) { setVerticalScrollBarEnabled(true); } if (getFirstVisiblePosition() == 0 && mRefreshState != REFRESHING) { /...

    android listview左右滑动出菜单

    在Adapter的`getView()`方法中,你需要为每个ListView项创建并设置滑动菜单。滑动菜单由`SwipeMenu`对象表示,可以通过`SwipeMenuCreator`来创建和定制。 3. **菜单项设置**: 使用`SwipeMenuItem`类来创建菜单项...

    ListView 滑动删除 item

    `SwipeMenuListView`则专门提供了创建滑动菜单的功能,包括滑动删除。这些库通常会提供一些预定义的动画效果和回调函数,方便开发者处理滑动过程和结果。 在使用`SwipeMenuListView`时,我们需要为每个ListView的...

    VB ListView 数据分页处理

    总之,VB ListView的数据分页处理需要自定义逻辑来实现,这涉及到数据源的操作、分页计算、ListView控件的动态更新以及用户界面的交互设计。掌握这些技巧,不仅可以提高你的VB编程能力,还能让你在处理大量数据时...

    ListView滑动控件(一)(修正版)

    实现这一功能需要监听滑动事件,使用手势检测库如GestureDetector或者直接在onTouchEvent()方法中处理。一旦检测到滑动,可以改变子视图的透明度和位置,创建删除按钮的视觉效果。同时,还需要处理点击事件,完成...

    ScrollView嵌套ListView滑动冲突的解决方法

    当需要在一个界面中同时展示大量数据和一些额外内容时,可能会将ListView嵌套在ScrollView中,但这种做法往往会导致滑动冲突的问题,即用户难以确定是想滚动整个ScrollView还是单独滑动ListView。本文将深入探讨这个...

    ListView滑动删除item

    3. 第三方库:如果需要更复杂的功能,如多方向滑动、自定义滑动菜单等,可以考虑使用如SwipeRefreshLayout、SwipeMenuListView等第三方库。它们已经封装了滑动删除的逻辑,可以直接集成使用。 总结,ListView的滑动...

    listView滑动显示首字母

    这可以通过ListView的getChildAt方法和getFirstVisiblePosition方法实现。然后,我们可以使用TextView或者其他视图来显示这个首字母,通过设置其背景颜色或文字样式使其突出。 此外,我们还需要考虑首字母指示器的...

    使用listview分页显示数据

    总的来说,这个实例涵盖了Android开发中的关键知识点:ListView的使用、Adapter的实现、分页加载策略以及与数据库的交互。通过研究这个案例,开发者能够深入理解如何在实际项目中有效地管理和展示大量数据,提升应用...

    ListView可滑动出菜单的Demo

    在Android中,实现ListView的滑动菜单通常有两种主要方法:一是自定义Adapter,二是使用第三方库。这个Demo可能采用了第三方库的方式,因为文件名“AndroidSwipeLayout”暗示了它可能依赖于一个名为“SwipeLayout”...

    listview分页加载

    ListView的数据分页加载功能是提高用户体验和优化应用性能的关键技术。本篇文章将深入探讨如何在Android中实现ListView的分页加载。 首先,理解分页加载的概念至关重要。分页加载是指在用户滚动列表到底部时,应用...

    listView 滑动置顶漂浮

    可以将头部视图设置为ListView的头部,或者使用一个父布局包含ListView和头部视图,然后在代码中处理它们的相对位置。 6. **动画效果**:为了提供更好的用户体验,可以在头部视图从普通状态转换为置顶状态时添加...

    Listview 滑动 贴合效果

    1. **OnScrollListener**: ListView提供了一个OnScrollListener接口,通过重写其`onScrollStateChanged()`和`onScroll()`方法,我们可以获取到ListView的滚动状态和当前位置,这是实现滑动贴合效果的基础。...

Global site tag (gtag.js) - Google Analytics