Android中listview如何刷新数据。

一个demo中,可以将sqlite中数据适配到listview中,但当插入新的数据点击查看,之前listview旧数据又出现了一遍,如何避免这个。

8个回答

第一种可以加入之前先clear一下在addall查出来的数据 然后notify一下
第二种就是分页加载了

你通过List集合绑定到Adapter中,你下次只需要调用list.add方法新增数据,然后notifyDataChanged方法即可。不需要清空list集合

插入数据后,更新list集合,在adapter中写一个更新list的方法,在该方法中接受传递过来的list集合,并notifyDataChanged()..
在activity中调用在adapter中定义的方法,传递过去更新后的list集合

我开发中列表的刷新就只使用:adapter的setdatanotify()方法,出现问题来,找找逻辑。可能是你逻辑出现了问题。

adapter.notifyDataChanged()

adapter要add而不是set

notifyDataChanged()

notifyDataChanged()

通知适配器改变

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
如何刷新android widget中listview的数据
如何刷新android widget中listview的数据,就是初始化的时候加载了数据,后来我收到一个广播,需要更新 里面的数据,怎么办?
关于listview数据刷新
安卓中broadcast接收到了短信存入数据库中后,如何立即刷新listview的数据
Android中,刷新ListView中的item导致ListView闪烁的解决方法
如题,因为下载列表使用ListView实现的,所以必须实时更新ListView中的数据。 我采用的是Service+BroadcastReceiver的搭配。更新数据 在Activity里面再用notifySetDataChange()的方法对ListView进行动态刷新 但是发现一个很严重的问题。刷新的时候ListView有明显的闪烁。 求解决方法
Android Listview adapter数据更新
listview绑定适配器后,数据更新不是需要调用notifyDataSetChanged刷新数据吗,为什么我现在不用掉也能刷新,平台是4.2和4.4,低的平台没测。代码如下 adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1); listview = (ListView)findViewById(R.id.listview); listview.setAdapter(adapter); btn = (Button)findViewById(R.id.button); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { adapter.add("item"); } });
android listview 删除之后怎么刷新 listview
这个是TitleAdapter package com.example.ming.myapplication; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.net.MalformedURLException; import java.net.URL; import java.util.List; public class TitleAdapter extends BaseAdapter { Context context; List<Article> postlist2; String id2; String id=""; int ii=0; public TitleAdapter(Context context, List<Article> postlist) { this.context = context; this.postlist2 = postlist; } @Override public int getCount() { return postlist2.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { convertView = LayoutInflater.from(context).inflate(R.layout.activity_article, null); Object obj = convertView.getTag(); ii=position; ViewHolder holder;//实现缓存 高效加载数据 //如果为空 if (obj == null) { holder = new ViewHolder(convertView); convertView.setTag(holder); } else { //緩存 通過viewholder存儲 holder = (ViewHolder) obj; } Article posit = postlist2.get(position); holder.tv_tltleid.setText(posit.getWid() + ""); holder.tv_tltlecontent.setText(posit.getTitle() + ""); return convertView; } public class ViewHolder { public View lv_title; public TextView tv_tltleid; public TextView tv_tltlecontent; public Button btn_neirong; public Button btn_delete; public ViewHolder(View rootView) { this.lv_title = rootView; this.tv_tltleid = (TextView) rootView.findViewById(R.id.tv_tltleid); this.tv_tltlecontent = (TextView) rootView.findViewById(R.id.tv_tltlecontent); this.btn_neirong=(Button)rootView.findViewById(R.id.btn_neirong); btn_neirong.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent2 = new Intent(context, ContentActivity.class); String id2=tv_tltleid.getText().toString(); Log.i("aaa",id2); intent2.putExtra("wid",id2); context.startActivity(intent2); } }); this.btn_delete = (Button) rootView.findViewById(R.id.btn_delete); btn_delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String id = tv_tltleid.getText().toString(); Log.i("1111", id); Log.i("11112", id); String url = "http://192.168.43.124:8080/test1/LoginServlet?jsp=delete&wid=" + id; new LoginTask().execute(url); } }); } class LoginTask extends AsyncTask<String, Integer, String> { @Override protected String doInBackground(String... params) { String par = params[0]; URL url = null; try { url = new URL(par); } catch (MalformedURLException e) { e.printStackTrace(); } String result = HttpUtil.doPost(url); return result; } //第四步 @Override protected void onPostExecute(String result) { super.onPostExecute(result); //保存数据 if (result.equals("1")) { Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show(); return; } else { if (result.equals("-1")) { Toast.makeText(context, "删除失败", Toast.LENGTH_SHORT).show(); return; } } } } } } 这个是TitleActivity package com.example.ming.myapplication; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.Button; import android.widget.ListView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.json.JSONArray; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * Created by Ming on 2019/6/16. */ public class TitleActivity extends AppCompatActivity { private ListView listView; Article article; JSONArray jsonArray; ListView lv_title; Context context; Button button; String id2="used"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_title); Intent intent=getIntent(); id2=intent.getStringExtra("id2"); context = this; String url = "http://192.168.43.124:8080/test1/LoginServlet?jsp=titleck&id2="+id2; new LoginTask().execute(url); } class LoginTask extends AsyncTask<String, Integer, String> { @Override protected String doInBackground(String... params) { String par = params[0]; URL url = null; try { url = new URL(par); } catch (MalformedURLException e) { e.printStackTrace(); } String result = HttpUtil.doPost(url); return result; } //第四步 @Override protected void onPostExecute(String result) { super.onPostExecute(result); final List<Article> list = new ArrayList<Article>(); Gson gson1 = new Gson(); final List<Article> list2 = gson1.fromJson(result, new TypeToken<List<Article>>() { }.getType()); for (Article person1 : list) { System.out.println(person1.toString()); } lv_title=(ListView)findViewById(R.id.lv_title); lv_title.setAdapter(new TitleAdapter(context,list2)); } } } 1.
android ListView一直添加数据导致OOM怎么办?
给listView设置了下拉刷新,但是发现如果我一直刷新,一直添加数据的话,内存使用会越来越大,最后导致OOM?怎么解决啊?
android listview 数据显示bug,帮忙看一下?
应用情景是这样的,点击底部选项卡,每个选项卡都会刷新listview,如果慢的点击一般不会出现异常,如果快速点击就会报异常,不知道什么原因,有的时候还会报这个异常:java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1343) at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1354) 还有这个异常: java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread.​ 还有这个异常: java.lang.IndexOutOfBoundsException: Invalid index 2, size is 1 at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251) at java.util.ArrayList.get(ArrayList.java:304) at android.widget.HeaderViewListAdapter.getView(HeaderViewListAdapter.java:225) at android.widget.AbsListView.obtainView(AbsListView.java:2260) at android.widget.ListView.makeAndAddView(ListView.java:1769) at android.widget.ListView.fillDown(ListView.java:672) at android.widget.ListView.fillSpecific(ListView.java:1330) at android.widget.ListView.layoutChildren(ListView.java:1600) at android.widget.AbsListView.onLayout(AbsListView.java:2111) at android.view.View.layout(View.java:13775) at android.view.ViewGroup.layout(ViewGroup.java:4364) at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1649) at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1507) at android.widget.LinearLayout.onLayout(LinearLayout.java:1420) at android.view.View.layout(View.java:13775) at android.view.ViewGroup.layout(ViewGroup.java:4364) at android.widget.FrameLayout.onLayout(FrameLayout.java:448) at android.view.View.layout(View.java:13775) at android.view.ViewGroup.layout(ViewGroup.java:4364) at android.widget.FrameLayout.onLayout(FrameLayout.java:448) at android.view.View.layout(View.java:13775) at android.view.ViewGroup.layout(ViewGroup.java:4364) at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1649) at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1507) at android.widget.LinearLayout.onLayout(LinearLayout.java:1420) at android.view.View.layout(View.java:13775) at android.view.ViewGroup.layout(ViewGroup.java:4364) at android.widget.FrameLayout.onLayout(FrameLayout.java:448) at android.view.View.layout(View.java:13775)
android ListView 做下拉刷新 下拉跳到第一项怎么解决
listView.setonRefreshListener(new OnRefreshListener() { @Override public void onRefresh() { Log.e(TAG, "---下拉刷新---"); new AsyncTask<Void, Void, Void>() { protected Void doInBackground(Void... params) { try { mylineslistlist.clear(); mylinesorderlist.clear(); list.clear(); getMylines(0); } catch (Exception e) { e.printStackTrace(); } return null; } protected void onPostExecute(Void result) { adapter.notifyDataSetChanged(); listView.onRefreshComplete(); } }.execute(); } }); listView.setOnScrollListener(new OnScrollListener() { @Override public void onScrollStateChanged(final AbsListView view, int scrollState) { listView.onScrollStateChanged(view, scrollState); // 数据为空--不用继续下面代码了 if (list.size() == 0) return; // 判断是否滚动到底部 boolean scrollEnd = false; try { if (view.getPositionForView(loadingLayout) == view .getLastVisiblePosition()) scrollEnd = true; } catch (Exception e) { scrollEnd = false; } if (scrollEnd) { // 如果是自动加载,可以在这里放置异步加载数据的代码 Log.e("LOADMORE", "loading..."); if (currentPage < pageNum) { // Log.e(TAG, "---currentPage is " + currentPage); currentPage++; // Log.e(TAG, "---currentPage is " + currentPage); handler.postDelayed(new Runnable() { @Override public void run() { // Log.d(TAG, "---loadData page is" + // currentPage); getMylines(currentPage); // listView.setSelection(view // .getLastVisiblePosition() - 1); // 设置选中项 // setLoadView("加载更多"); //恢复按钮文字 } }, 1000); } else { listView.removeFooterView(loadingLayout); } } }
android 怎么优化ListView
怎么优化listView,普通的优化我知道(convertView+ViewHolder),我主要是想知道关于数据方面怎么优化, 比如说,我的adpater中有一个ArrayList用来保存从服务端获取的数据集合。ArrayList中存放的是Person这个类, Person类中定义的都是String类型的数据,不过有一个有点占内存,就是图片的16进制字符串。 那么当我初始化这个ListView的时候,服务端向我发过来10条Person数据,那么10条数据就会添加到ArrayList中, 当我上拉刷新,又向服务端请求,服务端又返回了10条数据,那么就会又向ArrayList里面添加10条数据。那么假如一直上拉刷新?程序不就OOM了吗? 在网上查找了一些资料,还是没有完全弄明白到底要怎么解决。求帮助 (๑>m<๑)
android listview怎么实现单个item的某个数据刷新
用android的notifyDataSetChanged()方法会进行getView,导致每次所有都刷新;效率太低,我要怎样使某个item数据改变时只刷新那个item? 我的代码如下,请大神帮我改下!谢谢 ``` public class OfflineDownloadedAdapter extends BaseAdapter { private List<OfflineMapCity> cities = new ArrayList<OfflineMapCity>(); private Context mContext; private OfflineChild currentOfflineChild; public OfflineDownloadedAdapter(Context context) { this.mContext = context; initCityList(); } /** * 重新初始化数据加载数据 */ public void notifyDataChange() { initCityList(); } private void initCityList() { if (cities != null) { for (Iterator it = cities.iterator(); it.hasNext();) { OfflineMapCity i = (OfflineMapCity) it.next(); it.remove(); } } cities.addAll(ByteOfflineMapManager.getInstance(mContext).getDownloadOfficeMapCityList()); cities.addAll(ByteOfflineMapManager.getInstance(mContext).getDownloadingCityList()); notifyDataSetChanged(); } @Override public int getCount() { return cities.size(); } @Override public Object getItem(int index) { return cities.get(index); } @Override public long getItemId(int position) { return position; } @Override public int getItemViewType(int position) { return 0; } public final class ViewHolder { public OfflineChild mOfflineChild; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (convertView != null) { viewHolder = (ViewHolder) convertView.getTag(); } else { viewHolder = new ViewHolder(); currentOfflineChild = new OfflineChild(mContext); convertView = currentOfflineChild.getOffLineChildView(); viewHolder.mOfflineChild = currentOfflineChild; convertView.setTag(viewHolder); } OfflineMapCity offlineMapCity = (OfflineMapCity) getItem(position); viewHolder.mOfflineChild.setOffLineCity(offlineMapCity); return convertView; } } ```
Android 中SimpleAdapter刷新数据问题
代码是这样的,想在点击button的时候获取Edittext的值并写到listview的最下行,结果运行的时候获取的是一堆包名和哈希值 ``` public class TestActivity extends Activity { List<String> data = new ArrayList<String>(); ListView listView; EditText et; Button btn; protected void onCreate(android.os.Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.test); data.add("AAA"); data.add("BBB"); data.add("CCC"); et = (EditText) findViewById(R.id.editText1); btn = (Button) findViewById(R.id.button1); listView = (ListView) findViewById(R.id.listView1); final ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, android.R.id.text1, data); listView.setAdapter(adapter); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String context = et.getContext() + ""; System.out.println("================" + context + "==================="); data.add(context); //通知adapter内容更新 adapter.notifyDataSetChanged(); } }); } } ``` 获取的et的数据: ================com.zmj.baseadapter.TestActivity@dafe4e===================
android listview闪退问题
listview有时候会闪退,有时候不会,而且滚动刷新数据的时候有时候会闪退有时候不会,adapter.notifyDataSetChanged()有加.
ListView自动刷新多个Item
![图片说明](https://img-ask.csdn.net/upload/201601/04/1451909397_404376.png)ListView自定刷新Item中有改变的数据,并将此项 item背景闪烁一下。 ``` package master.modle.masterfinance.adapter; import android.graphics.Color; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.LinearInterpolator; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import java.security.MessageDigest; import java.util.ArrayList; import java.util.List; import java.util.Objects; import master.modle.masterfinance.R; import master.modle.masterfinance.model.biz.MarketList; import master.modle.masterfinance.utils.LogUtils; import master.modle.masterfinance.utils.UIUtils; import master.modle.masterfinance.utils.ViewHolderUtils; /** * * @action: * @author: YangShao * @date: 2016/1/4 @time: 10:46 */ public class MarkItmeAapter extends BaseAdapter{ List<MarketList> listEntitys; ListView listView; public MarkItmeAapter(List<MarketList> listEntitys,ListView listView){ this.listEntitys=listEntitys; this.listView=listView; } @Override public int getCount() { return listEntitys.size(); } @Override public Object getItem(int i) { return listEntitys.get(i); } @Override public long getItemId(int i) { return i; } public static ViewHolder mviewHolder; @Override public View getView(int i, View view, ViewGroup viewGroup) { ViewHolder holder; if (view==null){ view = LayoutInflater.from(UIUtils.getContext()).inflate(R.layout.item_market, viewGroup, false); holder = new ViewHolder(); holder.tx_name = (TextView) view.findViewById(R.id.id_mr_name); holder.tx_new = (TextView) view.findViewById(R.id.id_mr_new); holder.tv_range = (TextView) view.findViewById(R.id.id_mr_range); view.setTag(holder); }else{ holder = (ViewHolder) view.getTag(); } setData(holder,i); return view; } private static class ViewHolder { private TextView tx_name; private TextView tx_new; private TextView tv_range; private MarketList market; } public List<MarketList> getListViewData(){ return listEntitys; } public void setListEntitys(List<MarketList> listEntitys) { this.listEntitys = listEntitys; } /** * 设置viewHolder的数据 * @param holder * @param itemIndex */ private void setData(ViewHolder holder, int itemIndex) { holder.tx_name.setText(listEntitys.get(itemIndex).getName()); holder.tx_new.setText(listEntitys.get(itemIndex).getLatestpri() + ""); holder.tv_range.setText(listEntitys.get(itemIndex).getMarkup() + ""); holder.market=listEntitys.get(itemIndex); //int markup=Integer.valueOf(String.valueOf(listEntitys.get(i).getMarkup())); // int markup = Integer.parseInt(new java.text.DecimalFormat("0").format(listEntitys.get(i).getMarkup())); int markup = (int)listEntitys.get(itemIndex).getMarkup(); if (markup>=0){ holder.tv_range.setTextColor(Color.RED); holder.tx_new.setTextColor(Color.RED); }else{ holder.tv_range.setTextColor(Color.GREEN); holder.tx_new.setTextColor(Color.GREEN); } } } ``` ``` package master.modle.masterfinance.frg; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import java.util.List; import java.util.Timer; import java.util.TimerTask; import butterknife.Bind; import butterknife.ButterKnife; import master.modle.masterfinance.R; import master.modle.masterfinance.adapter.MarkItmeAapter; import master.modle.masterfinance.adapter.PagerItmeAapter; import master.modle.masterfinance.base.BaseApplication; import master.modle.masterfinance.base.BaseFragment; import master.modle.masterfinance.model.biz.InformatTitle; import master.modle.masterfinance.model.biz.MarketList; import master.modle.masterfinance.mpresenter.IMarketListPresnter; import master.modle.masterfinance.mview.IMarketView; import master.modle.masterfinance.utils.LogUtils; import master.modle.masterfinance.utils.ToastUtils; /** * @action: * @author: YangShao VapagerFragment * @date: 2015/12/24 @time: 16:22 */ public class MarkItmeFrag extends BaseFragment implements IMarketView { @Bind(R.id.id_mr_list) ListView idMrList; private View rootView; InformatTitle categoryEntitie; //标签内容 IMarketListPresnter iMarketListPresnter = new IMarketListPresnter(this); private String actName; public static MarkItmeFrag informationItmeFrag; private PagerItmeAapter itmeFragAapter; Handler handler = new Handler(){ public void handleMessage(Message msg) { super.handleMessage(msg); if(msg.what == 1){ iMarketListPresnter.getMarkList(String.valueOf(categoryEntitie.getId())); } } }; private Timer timer = new Timer(true); //任务 private TimerTask task = new TimerTask() { public void run() { Message msg = new Message(); msg.what = 1; handler.sendMessage(msg); } }; public static MarkItmeFrag getFragment(InformatTitle categoryEntitie, String mactName) { LogUtils.e("InformationItmeFrag getFragment" + mactName); informationItmeFrag = new MarkItmeFrag(); informationItmeFrag.categoryEntitie = categoryEntitie; informationItmeFrag.actName = mactName; return informationItmeFrag; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = getRootView(); ButterKnife.bind(this, rootView); initView(); return rootView; } public void initView() { //启动定时器 timer.schedule(task, 0, 10 * 1000); // iMarketListPresnter.getMarkList(String.valueOf(categoryEntitie.getId())); } public View getRootView() { rootView = LayoutInflater.from(getActivity()).inflate( R.layout.frag_mark_home, null); return rootView; } /* 摧毁视图 */ @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); timer.cancel(); timer=null; } /* 摧毁该Fragment,一般是FragmentActivity 被摧毁的时候伴随着摧毁 */ @Override public void onDestroy() { super.onDestroy(); BaseApplication.requestQueue.cancelAll(this); if (timer!=null){ timer.cancel(); timer=null; } } @Override public void onResume() { super.onResume(); } @Override public void onPause() { super.onPause(); } MarkItmeAapter markItmeAapter; @Override public void setInfomatList(final List<MarketList> listEntitys) { if (listEntitys.size()==0){ return; }if (markItmeAapter==null){ markItmeAapter=new MarkItmeAapter(listEntitys,idMrList); idMrList.setAdapter(markItmeAapter); }else { setUpdateListView(listEntitys); } } public void setUpdateListView(List<MarketList> mlistEntitys){ //得到原有数据 List<MarketList> liste = markItmeAapter.getListViewData(); for (int i=0;i<liste.size();i++){ double markup1=liste.get(i).getLatestpri(); double markup2=mlistEntitys.get(i).getLatestpri(); if (!equal(markup1,markup2)){ ToastUtils.showToastReal(markup2 + ""); LogUtils.e("发生改变的数据id" + i); } } markItmeAapter.setListEntitys(mlistEntitys); markItmeAapter.notifyDataSetChanged(); } boolean equal(double num1,double num2) { if((num1-num2>-0.000001)&&(num1-num2)<0.000001) return true; else return false; } @Override public void noData() { } } ``` ``` package master.modle.masterfinance.model.biz; public class MarketList { private int id; private String name; private double latestpri; private double markup; public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } public void setLatestpri(double latestpri) { this.latestpri = latestpri; } public void setMarkup(double markup) { this.markup = markup; } public int getId() { return id; } public String getName() { return name; } public double getLatestpri() { return latestpri; } public double getMarkup() { return markup; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof MarketList)) return false; MarketList that = (MarketList) o; return getId() == that.getId(); } @Override public int hashCode() { return getId(); } } ```
listview下拉刷新时遇到的问题
listview在第一页时往下拉,没到底部就会刷新,而第二页会拉到底部才会刷新, 到第三页时又会出现没到底部就会刷新了 package com.phone1000.exam01.activity; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.phone1000.exam01.R; import com.phone1000.exam01.adapter.MyAdapter; import com.phone1000.exam01.async.DownDataListAsyncTask; import com.phone1000.exam01.bean.Data; import com.phone1000.exam01.constant.IMyUrl; import com.phone1000.exam01.interf.OnGetDownDataListListener; public class MainActivity extends Activity implements OnGetDownDataListListener { private ListView lvShow = null; private TextView noData = null; private int index = 1; private boolean isBottom = false; private MyAdapter adapter = null; // 全局的数据列表 private List<Data> list = new ArrayList<Data>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new DownDataListAsyncTask(MainActivity.this) .execute(IMyUrl.url + index); initView(); setListener(); } private void setListener() { lvShow.setOnScrollListener(new OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { /** * 如果isBottom为true并且手指离开屏幕, 开启新的异步任务, * 注意:开启异步任务以后要设置isBottom为false 否则,会一直每当 */ if (isBottom && scrollState == OnScrollListener.SCROLL_STATE_IDLE) { new DownDataListAsyncTask(MainActivity.this) .execute(IMyUrl.url + ++index); isBottom = false; } } // 判断如果first+visible=total则滑到了屏幕底部,则设置isBottom为true; @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (firstVisibleItem + visibleItemCount == totalItemCount) { // Toast.makeText( // MainActivity.this, // "first***" + firstVisibleItem + "visible***" // + visibleItemCount + "total***" // + totalItemCount, Toast.LENGTH_LONG).show(); isBottom = true; } } }); } private void initView() { lvShow = (ListView) findViewById(R.id.lvShow); noData = (TextView) findViewById(R.id.NoData); lvShow.setEmptyView(noData); adapter = new MyAdapter(this.list, MainActivity.this); /** * 在这里设置适配器是只设置了一个适配器,以后到底部刷新时是在此适配器里添加数据 * 如果在回调方法里设置适配器,相当于每次调用回调方法都会给listview重新设置适配器 * 所导致的结果就是每次刷新完,都显示第一页内容 */ lvShow.setAdapter(adapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public void onGetDownDataList(List<Data> list) { // 每次刷新后在全局的数据列表中添加新获取到的数据 this.list.addAll(list); // 每次刷新都更新适配器中的数据 adapter.notifyDataSetChanged(); // ***************** // Toast.makeText(MainActivity.this, lvShow.getCount(), Toast.LENGTH_LONG).show(); } } ``` ```
android 关于listview convertview的一些问题,求解!
![图片说明](https://img-ask.csdn.net/upload/201603/14/1457947694_116075.png) 做的是一个聊天界面,这是adapter代码。 运行时只能输入一次,输第二次时,参数convertview是第二次view的对象,不知道为什么啊。 ``` package com.example.chattest; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; public class ChatActivity extends Activity implements OnClickListener { private Button btnSend; private ListView lvChat; private EditText etSendContent; //聊天内容的适配器 private ChatMsgViewAdapter chatMsgAdapter; //聊天内容 private List<ChatMsgInfo> chatMsgDataArrays = new ArrayList<ChatMsgInfo>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //不显示标题栏 requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.chat); initView(); initData(); } //初始化视图 private void initView() { lvChat = (ListView) findViewById(R.id.chat_listview); btnSend = (Button) findViewById(R.id.btn_send); btnSend.setOnClickListener(this); etSendContent = (EditText) findViewById(R.id.et_sendmessage); } //聊天数据 //private final static int COUNT = 10 private String text = new String("第1种写法果然最慢,第二种写法由于用了StringBuffer,快了很多。奇怪的是" + "第4种写法竟然也很快,比用StringBuffer还快,怎么回事?其实慢,第二种写" + "法由于用了StringBuffer,快了很多。奇怪的是第4种写法竟然也很快,比用StringBuffer还快,怎" + "比用StringBuffer还快,怎么回事?其r还快,怎么回事?其回事?其如果你调试过字符串连接的执行过程就会知"); private String date = new String("2016-3-10 18:11"); //初始化数据 private void initData() { ChatMsgInfo msgExample = new ChatMsgInfo("XiaoMing", date, text, true); chatMsgDataArrays.add(msgExample); chatMsgAdapter = new ChatMsgViewAdapter(this, chatMsgDataArrays); //listview绑定adapter lvChat.setAdapter(chatMsgAdapter); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch(v.getId()) { case R.id.btn_send: send(); break; } } //发送按钮的响应函数 private void send() { //获取输入文本框内容 String sendContent = etSendContent.getText().toString(); if (sendContent.length() > 0) { ChatMsgInfo msg = new ChatMsgInfo("XiaoHong", getDate(), sendContent, false); chatMsgDataArrays.add(msg); //通过一个外部的方法控制如果适配器的内容改变时需要强制调用getView来刷新每个Item的内容。 Log.d("chattest", "after setchanged!"); chatMsgAdapter.notifyDataSetChanged(); etSendContent.setText(""); //定位到最后一行 Log.d("chattest", "after setSelection!"); lvChat.setSelection(lvChat.getCount() -1 ); } } //获取时间 private String getDate() { Calendar c = Calendar.getInstance(); String year = String.valueOf(c.get(Calendar.YEAR)); String month = String.valueOf(c.get(Calendar.MONTH)); String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH) + 1); String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY)); String mins = String.valueOf(c.get(Calendar.MINUTE)); StringBuffer buffer = new StringBuffer(); buffer.append(year + "-" + month + "-" + day + " " + hour + ":" + mins); return buffer.toString(); } } ``` ``` package com.example.chattest; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; public class ChatMsgViewAdapter extends BaseAdapter { private static final int TYPE_COM_MSG = 0; private static final int TYPE_TO_MSG = 1; //private static final int TAG_KEY_ITEM_TYPE = 0; //private static final int TAG_KEY_VIEWHOLDER = 1; private List<ChatMsgInfo> data;//数据list private LayoutInflater myInflater;//layout convert view对象 private Context context;//环境 //构造 public ChatMsgViewAdapter(Context context, List<ChatMsgInfo> data) { this.context = context; this.data = data; myInflater = LayoutInflater.from(context); } @Override public int getItemViewType(int position) { // TODO Auto-generated method stub ChatMsgInfo msg = data.get(position); if (msg.getMsgType()) { return TYPE_COM_MSG; } else { return TYPE_TO_MSG; } } @Override public int getViewTypeCount() { // TODO Auto-generated method stub return 2; } //获取ListView的个数 @Override public int getCount() { return data.size(); } //获取项 @Override public Object getItem(int position) { return data.get(position); } //获取项的id @Override public long getItemId(int position) { return position; } //获取view @Override public View getView(int position, View convertView, ViewGroup parent) { ChatMsgInfo chatMsg = data.get(position);//聊天数据 boolean isComMsg = chatMsg.getMsgType();//数据类型(发送、接收) LeftItemViewHolder leftViewHolder = null; RightItemViewHolder rightViewHolder = null; int viewType = getItemViewType(position); System.out.println(position + " " + convertView); if (convertView == null || ((Integer)convertView.getTag(R.id.tag_item_viewtype)) != viewType) { //区分消息类别,展示不同的界面 if (viewType == TYPE_COM_MSG) { convertView = myInflater.inflate(R.layout.chat_msg_text_left_item, null); leftViewHolder = new LeftItemViewHolder(); leftViewHolder.tvSendTime = (TextView) convertView.findViewById(R.id.tv_sendtime); leftViewHolder.tvUserName = (TextView) convertView.findViewById(R.id.tv_username); leftViewHolder.tvContent = (TextView) convertView.findViewById(R.id.tv_chatcontent); leftViewHolder.isComMsg = isComMsg; convertView.setTag(R.id.tag_item_viewholder, leftViewHolder); } else { convertView = myInflater.inflate(R.layout.chat_msg_text_right_item, null); rightViewHolder = new RightItemViewHolder(); rightViewHolder.tvSendTime = (TextView) convertView.findViewById(R.id.tv_sendtime); rightViewHolder.tvContent = (TextView) convertView.findViewById(R.id.tv_chatcontent); rightViewHolder.isComMsg = isComMsg; convertView.setTag(R.id.tag_item_viewtype, rightViewHolder); } convertView.setTag(R.id.tag_item_viewtype, viewType); } else { if (viewType == TYPE_COM_MSG) { leftViewHolder = (LeftItemViewHolder) convertView.getTag(R.id.tag_item_viewholder); } else { rightViewHolder = (RightItemViewHolder) convertView.getTag(R.id.tag_item_viewholder); } } if (viewType == TYPE_COM_MSG) { leftViewHolder.tvUserName.setText(chatMsg.getName()); leftViewHolder.tvSendTime.setText(chatMsg.getDate()); leftViewHolder.tvContent.setText(chatMsg.getText()); } else { rightViewHolder.tvSendTime.setText(chatMsg.getDate()); rightViewHolder.tvContent.setText(chatMsg.getText()); } System.out.println(position + " " + convertView); return convertView; } //保存项,显示项的内容 static class LeftItemViewHolder { public TextView tvSendTime; public TextView tvUserName; public TextView tvContent; public boolean isComMsg = true; } static class RightItemViewHolder { public TextView tvSendTime; public TextView tvContent; public boolean isComMsg = true; } } ```
listView的局部刷新丶单条数据刷新
![图片说明](https://img-ask.csdn.net/upload/201701/19/1484790285_764769.jpg) 如图所示,我扫描一个单号并进行操作,实现卸货,如果总数量和卸货数量相等则移除给条数据,否则就将卸货数量加一?这要怎么实现卸货数量加一呢?
关于ListView 刷新的问题
package com.box.page; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.android.volley.RequestQueue; import com.android.volley.Request.Method; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.box.datamodel.CartGood; import com.box.sjfood_v_1_0.MainActivity; import com.box.sjfood_v_1_0.R; import com.box.tools.UrlString; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.LinearGradient; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; public class ShoppingCart extends Fragment{ private boolean hasitem = false;//进入界面时,接受服务器数据,表示购物车内是否有物品 private Button goForBuybutton;//去逛逛 private Button calculate;//结算按钮 private RequestQueue mQueue = null; private boolean isLogin;//是否已经登陆 private String phoneString;//用户手机号 private SharedPreferences sp; private Handler mHandler; private ArrayList<CartGood> cartGoods; private RelativeLayout shopping_somethingLayout; private LinearLayout shopping_nothingLayout; private ListView listView;//购物车listview private Button allSelectImageView;//全选图标 private TextView totalPriceTextView;//总价 private ShoppingCartAdapter myAdapter; private float totalPrice = 0;//记录总价 private ArrayList<Boolean> isselected = new ArrayList<Boolean>(); public View onCreateView( final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable Bundle savedInstanceState) { // TODO Auto-generated method stub //获取用户信息 getUserInfo(); View view = inflater.inflate(R.layout.shoppingcart, container,false); //获取页面 initView(view); //获取用户的订单信息 mQueue = Volley.newRequestQueue(getActivity()); GetOrderList(); mHandler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub if(msg.obj.toString().equals("-1")) { isLogin = false; hasitem = false; Log.i("isLogin1", String.valueOf(isLogin)); Log.i("hasitem1", String.valueOf(hasitem)); setAllGone(); shopping_nothingLayout.setVisibility(View.VISIBLE); } else { JSONObject jsonObject= new JSONObject(); jsonObject = (JSONObject) msg.obj; cartGoods = (ArrayList<CartGood>) JSONArray.parseArray(jsonObject.getJSONArray("orderList").toString(), CartGood.class); isLogin = true; hasitem = true; Log.i("isLogin1", String.valueOf(isLogin)); Log.i("hasitem1", String.valueOf(hasitem)); setAllGone(); shopping_somethingLayout.setVisibility(View.VISIBLE); dataToListView(); } } /* * 把cartgoods中的数据传到适配器中 */ private void dataToListView() { // TODO Auto-generated method stub for(int i = 0;i<cartGoods.size();i++) { Log.i("cartGoods",cartGoods.get(i).getName()+ i); isselected.add(false); } myAdapter = new ShoppingCartAdapter(getActivity(), cartGoods,isselected); listView.setAdapter(myAdapter); myAdapter.notifyDataSetChanged(); } private void setAllGone() { // TODO Auto-generated method stub shopping_somethingLayout.setVisibility(View.GONE); shopping_nothingLayout.setVisibility(View.GONE); } }; return view; } private void initView(View view) { // TODO Auto-generated method stub shopping_nothingLayout = (LinearLayout) view.findViewById(R.id.shoppingcart_nothing_layout); shopping_somethingLayout = (RelativeLayout) view.findViewById(R.id.shoppingcart_something_layout); initNothingView(view); initSomethingView(view); } //初始化有item时的界面 private void initSomethingView(View view) { // TODO Auto-generated method stub calculate = (Button) view.findViewById (R.id.shoppingcart_something_calcu);//结算按钮 allSelectImageView = (Button) view.findViewById (R.id.shoppingcart_allselect);//全选 totalPriceTextView = (TextView)view.findViewById (R.id.shoppingcart_totalprice);//总价 listView = (ListView)view.findViewById(R.id.shoppingcart_listview); allSelectImageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub isselected.add(true); if (allSelectImageView.isSelected()) { for(int i = 0;i<isselected.size();i++) { isselected.set(i, false); } allSelectImageView.setSelected(false); } else { for(int i = 0;i<isselected.size();i++) { isselected.set(i, true); } allSelectImageView.setSelected(true); } CalculatePrice(); myAdapter.notifyDataSetChanged(); } }); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub final int mposition = position; final CartGood cartGood = cartGoods.get(position); final Button button = (Button) view.findViewById(R.id.shoppingcart_item_select); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (isselected.get(mposition)) { allSelectImageView.setSelected(false); } isselected.set(mposition, !isselected.get(mposition)); Log.i("isselected", String.valueOf(isselected.get(mposition))); //Log.i("isselectedadapter",String.valueOf(myAdapter.getList().get(mposition))); myAdapter.notifyDataSetChanged(); CalculatePrice(); } }); } }); } /* * 获取用户存储在手机上的ID * 若未登录则Id置为-1,另外处理 */ private void CalculatePrice() { // TODO Auto-generated method stub totalPrice = 0; for(int i = 0;i<isselected.size();i++) { if(isselected.get(i)) { if(cartGoods.get(i).getIsDiscount() == 1) totalPrice = totalPrice+cartGoods.get(i).getDiscountPrice(); else { totalPrice = totalPrice + cartGoods.get(i).getPrice(); } } } totalPriceTextView.setText("¥ "+String.valueOf(totalPrice)); } private void getUserInfo() { // TODO Auto-generated method stub sp = getActivity().getSharedPreferences("login", 0); isLogin = sp.getBoolean("Login", false); phoneString = sp.getString("phone", "-1"); if(!isLogin) { hasitem = false; phoneString = "-1"; } } /* * 获取用户订单信息 */ private void GetOrderList() { // TODO Auto-generated method stub StringRequest stringRequest = new StringRequest(Method.POST, UrlString.GetOrderString, new Response.Listener<String>() { @Override public void onResponse(String response) { // TODO Auto-generated method stub Log.i("用户订单信息", response); JSONObject jsonObject =JSONObject.parseObject(response); String statusString = jsonObject.getString("status"); if(statusString.equals("success")) { Message message = mHandler.obtainMessage(); if(!jsonObject.getString("message").equals("获取购物车订单成功")) { message.obj = -1; } else { message.obj = jsonObject; } mHandler.sendMessage(message); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // TODO Auto-generated method stub } }) { protected Map<String, String> getParams(){ Map<String, String> params = new HashMap<String, String>(); params.put("phoneId", phoneString); return params; } }; mQueue.add(stringRequest); } private void initNothingView(View view) { // TODO Auto-generated method stub goForBuybutton = (Button)view.findViewById(R.id.shoppingcart_goforbuy); goForBuybutton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(getActivity(),MainActivity.class); startActivity(intent); getActivity().finish(); } }); } } ``` ``` 为什么listview不会自动刷新? 是不是只要adapter绑定的数据源发生变化了,调用notifydatasetonchanged就会刷新? notifydatasetonchanged()调用有什么条件?
android listview拉到底部的方法
目前做了个项目,是带有解析表情的聊天功能,在listview显示数据时,每次带有表情的item,就不能通过notify刷新出来,只能手动去拉,所以我想问问大神们,除了setseletion这个方法外,还有其他方法吗? 谢谢大神们指点!!!
新手请教ListView 刷新问题
这是显示ListView的界面 package com.security.phonepolice.view; import java.util.ArrayList; import java.util.List; import org.apache.http.Header; import org.json.JSONException; import org.json.JSONObject; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.security.phonepolice.ContantValues; import com.security.phonepolice.R; import com.security.phonepolice.entity.Msgbean; import com.security.phonepolice.http.MyHttpclient; import com.security.phonepolice.util.SharedPreferenceUtil; import com.security.phonepolice.view.MessageManager.NotificationAdapter; import com.security.phonepolice.view.OAFileFragment.FileViewHolder; import com.security.phonepolice.view.widget.MyListView; import com.security.phonepolice.view.widget.MyListView.RefreshListener; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class OANotifyFragment extends Fragment implements OnClickListener, OnItemClickListener{ private View view; private ImageView mPreIv; private MyListView mNotifyLv; private LayoutInflater mInflater; private NotifyAdapter adapter = null; private TextView notifyUpload; private List<Msgbean> mList; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.oa_notify_ui, container, false); mInflater = inflater; init(); initEvent(); return view; } private void init() { mNotifyLv = (MyListView) view.findViewById(R.id.oa_notify_lv); } private void initEvent() { mList = new ArrayList<Msgbean>(); adapter = new NotifyAdapter(mList); mNotifyLv.setOnItemClickListener(this); mNotifyLv.setAdapter(adapter); mNotifyLv.setOnRefreshListener(new RefreshListener() { @Override public Object refreshing() { RequestParams params = new RequestParams(); params.put("action", "Message"); String serverAdd = SharedPreferenceUtil.getServerStringSP(getActivity(), "config", "serverAdd"); MyHttpclient.post(serverAdd+ContantValues.IDCARD_URL, params, new AsyncHttpResponseHandler(){ @Override public void onSuccess( int statusCode, Header[] headers, String content) { super.onSuccess(statusCode, headers, content); if (!content.equals("failed")) { Msgbean msgBean = new Msgbean(); try { JSONObject jsonObject=new JSONObject(content); msgBean.setTitle(jsonObject.getString("TITLE")); msgBean.setContent(jsonObject.getString("CONTENT")); Log.i("-----------", jsonObject.getString("TITLE")); List<Msgbean> list = new ArrayList<Msgbean>(); list.add(msgBean); mList = list; adapter.notifyDataSetChanged(); } catch (JSONException e) { e.printStackTrace(); } }else { Toast.makeText(getActivity(), "刷新失败", Toast.LENGTH_LONG).show(); } } @Override public void onFailure( Throwable error, String content) { Toast.makeText(getActivity(), "连接失败", Toast.LENGTH_LONG).show(); super.onFailure(error, content); } } ); return null; } @Override public void refreshed(Object obj) { Toast.makeText(getActivity(), "刷新完毕", Toast.LENGTH_LONG).show(); } @Override public void more() { Toast.makeText(getActivity(), "正在加载", Toast.LENGTH_LONG).show(); } }); } class NotifyAdapter extends BaseAdapter{ private List<Msgbean> list; public NotifyAdapter(List<Msgbean> list) { this.list = list; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { NotifyViewHolder viewHolder = null; if (convertView == null) { convertView = mInflater.inflate(R.layout.oa_item, null); viewHolder = new NotifyViewHolder(); viewHolder.itemIv = (ImageView) convertView.findViewById(R.id.oa_item_iv); viewHolder.itemTitle = (TextView) convertView.findViewById(R.id.oa_item_title); viewHolder.itemContent = (TextView) convertView.findViewById(R.id.oa_item_content); convertView.setTag(viewHolder); }else { viewHolder = (NotifyViewHolder) convertView.getTag(); } viewHolder.itemIv.setImageResource(R.drawable.notification_small); viewHolder.itemTitle.setText(list.get(position).getTitle()); viewHolder.itemContent.setText(list.get(position).getContent()); return convertView; } } public static class NotifyViewHolder{ public ImageView itemIv; public TextView itemTitle; public TextView itemContent; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = null; if (position > 0) { //去服务器拉取警情的详细信息 intent = new Intent(); intent.putExtra("InfoTag", "OANotify"); intent.setClass(getActivity(), MessageDetail.class); startActivity(intent); } } } 这是在网上找到的自定义的ListView package com.security.phonepolice.view.widget; import java.text.SimpleDateFormat; import java.util.Date; import com.security.phonepolice.R; import android.content.Context; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; /** * 下拉刷新,底部更多 * */ public class MyListView extends ListView implements OnScrollListener{ private float mDownY; private float mMoveY; private int mHeaderHeight; private int mCurrentScrollState; private final static int NONE_PULL_REFRESH = 0; //正常状态 private final static int ENTER_PULL_REFRESH = 1; //进入下拉刷新状态 private final static int OVER_PULL_REFRESH = 2; //进入松手刷新状态 private final static int EXIT_PULL_REFRESH = 3; //松手后反弹和加载状态 private int mPullRefreshState = 0; //记录刷新状态 private final static int REFRESH_BACKING = 0; //反弹中 private final static int REFRESH_BACED = 1; //达到刷新界限,反弹结束后 private final static int REFRESH_RETURN = 2; //没有达到刷新界限,返回 private final static int REFRESH_DONE = 3; //加载数据结束 private LinearLayout mHeaderLinearLayout = null; private LinearLayout mFooterLinearLayout = null; private TextView mHeaderTextView = null; private TextView mHeaderUpdateText = null; private ImageView mHeaderPullDownImageView = null; private ImageView mHeaderReleaseDownImageView = null; private ProgressBar mHeaderProgressBar = null; private TextView mFooterTextView = null; private ProgressBar mFooterProgressBar = null; private SimpleDateFormat mSimpleDateFormat; private Object mRefreshObject = null; private RefreshListener mRefreshListener = null; public void setOnRefreshListener(RefreshListener refreshListener) { this.mRefreshListener = refreshListener; } public MyListView(Context context) { this(context, null); } public MyListView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } void init(final Context context) { mHeaderLinearLayout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.refresh_list_header, null); addHeaderView(mHeaderLinearLayout); mHeaderTextView = (TextView) findViewById(R.id.refresh_list_header_text); mHeaderUpdateText = (TextView) findViewById(R.id.refresh_list_header_last_update); mHeaderPullDownImageView = (ImageView) findViewById(R.id.refresh_list_header_pull_down); mHeaderReleaseDownImageView = (ImageView) findViewById(R.id.refresh_list_header_release_up); mHeaderProgressBar = (ProgressBar) findViewById(R.id.refresh_list_header_progressbar); mFooterLinearLayout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.refresh_list_footer, null); addFooterView(mFooterLinearLayout); mFooterProgressBar = (ProgressBar) findViewById(R.id.refresh_list_footer_progressbar); mFooterTextView = (TextView) mFooterLinearLayout.findViewById(R.id.refresh_list_footer_text); mFooterLinearLayout.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if ("加载更多".equals(mFooterTextView.getText())) { mFooterTextView.setText("正在加载"); mFooterProgressBar.setVisibility(View.VISIBLE); if (mRefreshListener != null) { mRefreshListener.more(); } } } }); setSelection(1); setOnScrollListener(this); measureView(mHeaderLinearLayout); mHeaderHeight = mHeaderLinearLayout.getMeasuredHeight(); mSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm"); mHeaderUpdateText.setText("下拉刷新"+ mSimpleDateFormat.format(new Date())); } @Override public boolean onTouchEvent(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: mDownY = ev.getY(); break; case MotionEvent.ACTION_MOVE: mMoveY = ev.getY(); if (mPullRefreshState == OVER_PULL_REFRESH) { mHeaderLinearLayout.setPadding(mHeaderLinearLayout.getPaddingLeft(), (int)((mMoveY - mDownY)/3), mHeaderLinearLayout.getPaddingRight(), mHeaderLinearLayout.getPaddingBottom()); } break; case MotionEvent.ACTION_UP: //when you action up, it will do these: //1. roll back util header topPadding is 0 //2. hide the header by setSelection(1) if (mPullRefreshState == OVER_PULL_REFRESH || mPullRefreshState == ENTER_PULL_REFRESH) { new Thread() { public void run() { Message msg; while(mHeaderLinearLayout.getPaddingTop() > 1) { msg = mHandler.obtainMessage(); msg.what = REFRESH_BACKING; mHandler.sendMessage(msg); try { sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } } msg = mHandler.obtainMessage(); if (mPullRefreshState == OVER_PULL_REFRESH) { msg.what = REFRESH_BACED; } else { msg.what = REFRESH_RETURN; } mHandler.sendMessage(msg); }; }.start(); } break; } return super.onTouchEvent(ev); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (mCurrentScrollState == SCROLL_STATE_TOUCH_SCROLL && firstVisibleItem == 0 && (mHeaderLinearLayout.getBottom() >= 0 && mHeaderLinearLayout.getBottom() < mHeaderHeight)) { //进入且仅进入下拉刷新状态 if (mPullRefreshState == NONE_PULL_REFRESH) { mPullRefreshState = ENTER_PULL_REFRESH; } } else if (mCurrentScrollState == SCROLL_STATE_TOUCH_SCROLL && firstVisibleItem == 0 && (mHeaderLinearLayout.getBottom() >= mHeaderHeight)) { //下拉达到界限,进入松手刷新状态 if (mPullRefreshState == ENTER_PULL_REFRESH || mPullRefreshState == NONE_PULL_REFRESH) { mPullRefreshState = OVER_PULL_REFRESH; mDownY = mMoveY; //为下拉1/3折扣效果记录开始位置 mHeaderTextView.setText("松手刷新");//显示松手刷新 mHeaderPullDownImageView.setVisibility(View.GONE);//隐藏"下拉刷新" mHeaderReleaseDownImageView.setVisibility(View.VISIBLE);//显示向上的箭头 } } else if (mCurrentScrollState == SCROLL_STATE_TOUCH_SCROLL && firstVisibleItem != 0) { //不刷新了 if (mPullRefreshState == ENTER_PULL_REFRESH) { mPullRefreshState = NONE_PULL_REFRESH; } } else if (mCurrentScrollState == SCROLL_STATE_FLING && firstVisibleItem == 0) { //飞滑状态,不能显示出header,也不能影响正常的飞滑 //只在正常情况下才纠正位置 if (mPullRefreshState == NONE_PULL_REFRESH) { setSelection(1); } } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { mCurrentScrollState = scrollState; } @Override public void setAdapter(ListAdapter adapter) { super.setAdapter(adapter); setSelection(1); } private void measureView(View child) { ViewGroup.LayoutParams p = child.getLayoutParams(); if (p == null) { p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_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); } private Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case REFRESH_BACKING: mHeaderLinearLayout.setPadding(mHeaderLinearLayout.getPaddingLeft(), (int) (mHeaderLinearLayout.getPaddingTop()*0.75f), mHeaderLinearLayout.getPaddingRight(), mHeaderLinearLayout.getPaddingBottom()); break; case REFRESH_BACED: mHeaderTextView.setText("正在加载..."); mHeaderProgressBar.setVisibility(View.VISIBLE); mHeaderPullDownImageView.setVisibility(View.GONE); mHeaderReleaseDownImageView.setVisibility(View.GONE); mPullRefreshState = EXIT_PULL_REFRESH; new Thread() { public void run() { if (mRefreshListener != null) { mRefreshObject = mRefreshListener.refreshing(); } Message msg = mHandler.obtainMessage(); msg.what = REFRESH_DONE; mHandler.sendMessage(msg); }; }.start(); break; case REFRESH_RETURN: mHeaderTextView.setText("下拉刷新"); mHeaderProgressBar.setVisibility(View.INVISIBLE); mHeaderPullDownImageView.setVisibility(View.VISIBLE); mHeaderReleaseDownImageView.setVisibility(View.GONE); mHeaderLinearLayout.setPadding(mHeaderLinearLayout.getPaddingLeft(), 0, mHeaderLinearLayout.getPaddingRight(), mHeaderLinearLayout.getPaddingBottom()); mPullRefreshState = NONE_PULL_REFRESH; setSelection(1); break; case REFRESH_DONE: mHeaderTextView.setText("下拉刷新"); mHeaderProgressBar.setVisibility(View.INVISIBLE); mHeaderPullDownImageView.setVisibility(View.VISIBLE); mHeaderReleaseDownImageView.setVisibility(View.GONE); mHeaderUpdateText.setText("最新更新"+ mSimpleDateFormat.format(new Date())); mHeaderLinearLayout.setPadding(mHeaderLinearLayout.getPaddingLeft(), 0, mHeaderLinearLayout.getPaddingRight(), mHeaderLinearLayout.getPaddingBottom()); mPullRefreshState = NONE_PULL_REFRESH; setSelection(1); if (mRefreshListener != null) { mRefreshListener.refreshed(mRefreshObject); } break; default: break; } } }; public interface RefreshListener { Object refreshing(); void refreshed(Object obj); void more(); } public void finishFootView() { mFooterProgressBar.setVisibility(View.GONE); mFooterTextView.setText("更多"); } public void addFootView() { if (getFooterViewsCount() == 0) { addFooterView(mFooterLinearLayout); } } public void removeFootView() { removeFooterView(mFooterLinearLayout); } } 这是实体类: package com.security.phonepolice.entity; public class Msgbean { private int id; private String title; private String content; private String relName; private String relTime; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getRelName() { return relName; } public void setRelName(String relName) { this.relName = relName; } public String getRelTime() { return relTime; } public void setRelTime(String relTime) { this.relTime = relTime; } } 走到这一步法mNotifyLv.setOnRefreshListener(new RefreshListener() 就停了 为什么刷新的时候就是不走接口中的refreshing()方法。求大神指教啊!
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它是一个过程,是一个不断累积、不断沉淀、不断总结、善于传达自己的个人见解以及乐于分享的过程。
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过...
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 free -m 其中:m表示兆,也可以用g,注意都要小写 Men:表示物理内存统计 total:表示物理内存总数(total=used+free) use...
比特币原理详解
一、什么是比特币 比特币是一种电子货币,是一种基于密码学的货币,在2008年11月1日由中本聪发表比特币白皮书,文中提出了一种去中心化的电子记账系统,我们平时的电子现金是银行来记账,因为银行的背后是国家信用。去中心化电子记账系统是参与者共同记账。比特币可以防止主权危机、信用风险。其好处不多做赘述,这一层面介绍的文章很多,本文主要从更深层的技术原理角度进行介绍。 二、问题引入 假设现有4个人...
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发...
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 演示地点演示 html代码如下` music 这个年纪 七月的风 音乐 ` 然后就是css`*{ margin: 0; padding: 0; text-decoration: none; list-...
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。
数据库优化 - SQL优化
以实际SQL入手,带你一步一步走上SQL优化之路!
通俗易懂地给女朋友讲:线程池的内部原理
餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”
经典算法(5)杨辉三角
杨辉三角 是经典算法,这篇博客对它的算法思想进行了讲解,并有完整的代码实现。
使用 Docker 部署 Spring Boot 项目
Docker 技术发展为微服务落地提供了更加便利的环境,使用 Docker 部署 Spring Boot 其实非常简单,这篇文章我们就来简单学习下。首先构建一个简单的 S...
英特尔不为人知的 B 面
从 PC 时代至今,众人只知在 CPU、GPU、XPU、制程、工艺等战场中,英特尔在与同行硬件芯片制造商们的竞争中杀出重围,且在不断的成长进化中,成为全球知名的半导体公司。殊不知,在「刚硬」的背后,英特尔「柔性」的软件早已经做到了全方位的支持与支撑,并持续发挥独特的生态价值,推动产业合作共赢。 而对于这一不知人知的 B 面,很多人将其称之为英特尔隐形的翅膀,虽低调,但是影响力却不容小觑。 那么,在...
面试官:你连RESTful都不知道我怎么敢要你?
干货,2019 RESTful最贱实践
刷了几千道算法题,这些我私藏的刷题网站都在这里了!
遥想当年,机缘巧合入了 ACM 的坑,周边巨擘林立,从此过上了"天天被虐似死狗"的生活… 然而我是谁,我可是死狗中的战斗鸡,智力不够那刷题来凑,开始了夜以继日哼哧哼哧刷题的日子,从此"读题与提交齐飞, AC 与 WA 一色 ",我惊喜的发现被题虐既刺激又有快感,那一刻我泪流满面。这么好的事儿作为一个正直的人绝不能自己独享,经过激烈的颅内斗争,我决定把我私藏的十几个 T 的,阿不,十几个刷题网...
白话阿里巴巴Java开发手册高级篇
不久前,阿里巴巴发布了《阿里巴巴Java开发手册》,总结了阿里巴巴内部实际项目开发过程中开发人员应该遵守的研发流程规范,这些流程规范在一定程度上能够保证最终的项目交付质量,通过在时间中总结模式,并推广给广大开发人员,来避免研发人员在实践中容易犯的错误,确保最终在大规模协作的项目中达成既定目标。 无独有偶,笔者去年在公司里负责升级和制定研发流程、设计模板、设计标准、代码标准等规范,并在实际工作中进行...
SQL-小白最佳入门sql查询一
不要偷偷的查询我的个人资料,即使你再喜欢我,也不要这样,真的不好;
redis分布式锁,面试官请随便问,我都会
文章有点长并且绕,先来个图片缓冲下! 前言 现在的业务场景越来越复杂,使用的架构也就越来越复杂,分布式、高并发已经是业务要求的常态。像腾讯系的不少服务,还有CDN优化、异地多备份等处理。 说到分布式,就必然涉及到分布式锁的概念,如何保证不同机器不同线程的分布式锁同步呢? 实现要点 互斥性,同一时刻,智能有一个客户端持有锁。 防止死锁发生,如果持有锁的客户端崩溃没有主动释放锁,也要保证锁可以正常释...
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // doshom...
Nginx 原理和架构
Nginx 是一个免费的,开源的,高性能的 HTTP 服务器和反向代理,以及 IMAP / POP3 代理服务器。Nginx 以其高性能,稳定性,丰富的功能,简单的配置和低资源消耗而闻名。 Nginx 的整体架构 Nginx 里有一个 master 进程和多个 worker 进程。master 进程并不处理网络请求,主要负责调度工作进程:加载配置、启动工作进程及非停升级。worker 进程负责处...
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,...
程序员:我终于知道post和get的区别
是一个老生常谈的话题,然而随着不断的学习,对于以前的认识有很多误区,所以还是需要不断地总结的,学而时习之,不亦说乎
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU...
加快推动区块链技术和产业创新发展,2019可信区块链峰会在京召开
11月8日,由中国信息通信研究院、中国通信标准化协会、中国互联网协会、可信区块链推进计划联合主办,科技行者协办的2019可信区块链峰会将在北京悠唐皇冠假日酒店开幕。   区块链技术被认为是继蒸汽机、电力、互联网之后,下一代颠覆性的核心技术。如果说蒸汽机释放了人类的生产力,电力解决了人类基本的生活需求,互联网彻底改变了信息传递的方式,区块链作为构造信任的技术有重要的价值。   1...
Java世界最常用的工具类库
Apache Commons Apache Commons有很多子项目 Google Guava 参考博客
程序员把地府后台管理系统做出来了,还有3.0版本!12月7号最新消息:已在开发中有github地址
第一幕:缘起 听说阎王爷要做个生死簿后台管理系统,我们派去了一个程序员…… 996程序员做的梦: 第一场:团队招募 为了应对地府管理危机,阎王打算找“人”开发一套地府后台管理系统,于是就在地府总经办群中发了项目需求。 话说还是中国电信的信号好,地府都是满格,哈哈!!! 经常会有外行朋友问:看某网站做的不错,功能也简单,你帮忙做一下? 而这次,面对这样的需求,这个程序员...
网易云6亿用户音乐推荐算法
网易云音乐是音乐爱好者的集聚地,云音乐推荐系统致力于通过 AI 算法的落地,实现用户千人千面的个性化推荐,为用户带来不一样的听歌体验。 本次分享重点介绍 AI 算法在音乐推荐中的应用实践,以及在算法落地过程中遇到的挑战和解决方案。 将从如下两个部分展开: AI算法在音乐推荐中的应用 音乐场景下的 AI 思考 从 2013 年 4 月正式上线至今,网易云音乐平台持续提供着:乐屏社区、UGC...
【技巧总结】位运算装逼指南
位算法的效率有多快我就不说,不信你可以去用 10 亿个数据模拟一下,今天给大家讲一讲位运算的一些经典例子。不过,最重要的不是看懂了这些例子就好,而是要在以后多去运用位运算这些技巧,当然,采用位运算,也是可以装逼的,不信,你往下看。我会从最简单的讲起,一道比一道难度递增,不过居然是讲技巧,那么也不会太难,相信你分分钟看懂。 判断奇偶数 判断一个数是基于还是偶数,相信很多人都做过,一般的做法的代码如下...
为什么要学数据结构?
一、前言 在可视化化程序设计的今天,借助于集成开发环境可以很快地生成程序,程序设计不再是计算机专业人员的专利。很多人认为,只要掌握几种开发工具就可以成为编程高手,其实,这是一种误解。要想成为一个专业的开发人员,至少需要以下三个条件: 1) 能够熟练地选择和设计各种数据结构和算法 2) 至少要能够熟练地掌握一门程序设计语言 3) 熟知所涉及的相关应用领域的知识 其中,后两个条件比较容易实现,而第一个...
Android 9.0 init 启动流程
阅读五分钟,每日十点,和您一起终身学习,这里是程序员Android本篇文章主要介绍Android开发中的部分知识点,通过阅读本篇文章,您将收获以下内容:一、启动流程概述一、 启动流程概述Android启动流程跟Linux启动类似,大致分为如下五个阶段。1.开机上电,加载固化的ROM。2.加载BootLoader,拉起Android OS。3.加载Uboot,初始外设,引导Kernel启动等。...
相关热词 c# 输入ip c# 乱码 报表 c#选择结构应用基本算法 c# 收到udp包后回包 c#oracle 头文件 c# 序列化对象 自定义 c# tcp 心跳 c# ice连接服务端 c# md5 解密 c# 文字导航控件
立即提问