Android开发---ListView实现局部刷新及删除
2016-06-28 18:24
471 查看
1.行布局,及简单的点击控件刷新
Activity代码
public class MainActivity extends Activityimplements IControl {private ArrayList<MyListEntity> list = null;
private ListView lv;
private MyListAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
initView();
initEvent();
}
/**
* 初始化数据
*/
private void initData() {
list = new ArrayList<MyListEntity>();
for (int i = 0; i < 20; i++) {
MyListEntity entityItem = new MyListEntity();
entityItem.setData("item " + i);
entityItem.setPosition(i);
list.add(entityItem);
}
}
private void initView() {
//这里和普通适配器不一样,要把当前的listview也传入适配器
lv =(ListView) findViewById(R.id.lv);
adapter = new MyListAdapter(list, getApplicationContext());
//1.重写行布局点击事件,实现ListView局部刷新
//(1)拿到点击行的position , 并将其作为实体类集合下标.
//(2)通过下标,找到实体类集合中对应的对象.
//(3)更新该对象的某一条属性.
//(4)将更新属性后的实体类对象,传入适配器更新数据的方法.
adapter.setListView(lv);
adapter.setiControl(this);
lv.setAdapter(adapter);
}
private void initEvent() {
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
p
4000
ublic void onItemClick(AdapterView<?> parent, View view, intposition, long id) {
// 获取listview中点击item的数据
MyListEntity item =(MyListEntity) parent.getItemAtPosition(position);
//Log.i("eee",item.getData() + " == " + item.getPosition());
// 更新数据
item.setData("update item" + position);//data:实体类属性,类似username
// 更新界面
adapter.updateItemData(item);
//2.update()行布局点击按钮事件,实现ListView局部刷新
//(1)当前按钮所在行的实体类对象,和位置已经通过接口参数传来
//(2)根据需求,更新该对象的某一条属性.
//(3)将更新属性后的实体类对象,传入适配器更新数据的方法.
}
});
}
@Override
public void update(MyListEntity myListEntity, int position) {
// 获取listview中点击item的数据
MyListEntity item = myListEntity;
// 更新数据
item.setData("update item " + position);
// 更新界面
adapter.updateItemData(item);
}
}Adapter代码public class MyListAdapter extendsBaseAdapter {
/**
* listview中的数据集
*/
private ArrayList<MyListEntity> mDataList;
private Context mContext;
private ListView mListView;
private IControl iControl;
public MyListAdapter(ArrayList<MyListEntity> list, Context cont) {
this.mDataList = list;
this.mContext = cont;
}
public void setiControl(IControl iControl) {
this.iControl = iControl;
}
/**
* 设置listview对象
*/
public void setListView(ListViewlisv) {
this.mListView = lisv;
}
/**
* update listview 单条数据
* @param entityItem 新数据对象
public void updateItemData(MyListEntityentityItem) { */
Message msg = Message.obtain();
int ids = -1;
// 进行数据对比获取对应数据在list中的位置
for (int i = 0; i < mDataList.size(); i++) {
if(mDataList.get(i).getPosition() == entityItem.getPosition()) {
ids = i;
}
}
msg.arg1 = ids;
// 更新mDataList对应位置的数据
mDataList.set(ids, entityItem);
// handle刷新界面
han.sendMessage(msg);
//另开线程更新UI
}
private Handler han = new Handler() { @SuppressLint("HandlerLeak")
public void handleMessage(android.os.Message msg) {
updateItem(msg.arg1);
} };
/**
* 刷新指定item
* @param index item在listview中的位置
*/
if (mListView == null) { privatevoid updateItem(intindex) {
return;
}
// 获取当前可以看到的item位置
int visiblePosition = mListView.getFirstVisiblePosition();
// 如添加headerview后 firstview就是hearderview
// 所有索引+1 取第一个view
// View view = listview.getChildAt(index - visiblePosition + 1);
// 获取点击的view
View view = mListView.getChildAt(index - visiblePosition);
TextView txt = (TextView) view.findViewById(R.id.txv_data);
// 获取mDataList.set(ids,item);更新的数据
MyListEntity data = (MyListEntity) getItem(index);
// 重新设置界面显示数据
txt.setText(data.getData());
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mDataList.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return mDataList.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroupparent) {
// TODO Auto-generated method stub
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.item_lv,null);
}
TextView txt = (TextView) convertView.findViewById(R.id.txv_data);
txt.setText(mDataList.get(position).getData());
Button btn_update = (Button) convertView.findViewById(R.id.btn_update);
btn_update.setOnClickListener(new View.OnClickListener() {
//两个参数
//1. 当前位置的实体类对象
//2. 当前位置int值
@Override
public void onClick(View v) {
iControl.update(mDataList.get(position),position);
}
});
return convertView;
}
}实体类代码
public class MyListEntity { /** * 数据id */ private int dataId; /** * 数据 */ private String data; public int getPosition() { return dataId; } public void setPosition(int position) { this.dataId = position; } public String getData() { return data; } public void setData(String data) { this.data = data; } }接口代码
public interface IControl { void update(MyListEntity myListEntity, int position); }
2.应用实例(获得editView输入值后局部刷新)
Activity代码public class ListCommentActivity extends Activity implements IControl_up,View.OnClickListener { Integer userid_becom = 0; String content_tch = ""; List<Comment> list; CommentAdapter adapter; ListView lv; Comment comment; Integer commentid_item = 0;//当前要更改的评论的id Comment citem;//全局实体类对象,专为局部刷新用 //老师发表评论 LinearLayout ll_write_comment; EditText edt_write_comment; Button btn_send_comment; @Override protected void onCreate(BundlesavedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_comment); initData(); initView(); initEvent(); } private void initData() { userid_becom =getIntent().getIntExtra("userid_becom", 0); list = new ArrayList<Comment>(); getComment(userid_becom, userid_becom); } private void initView() { lv = (ListView)findViewById(R.id.lv_comment); adapter = new CommentAdapter(this); adapter.setControl(this); lv.setAdapter(adapter); ll_write_comment = (LinearLayout)findViewById(R.id.ll_write_comment); edt_write_comment = (EditText)findViewById(R.id.edt_write_comment);//老师写评语 btn_send_comment = (Button)findViewById(R.id.btn_send_comment); edt_write_comment.addTextChangedListener(watcher); btn_send_comment.setEnabled(false); } private void initEvent() { btn_send_comment.setOnClickListener(this); } private TextWatcher watcher = newTextWatcher() { ...... @Override public void afterTextChanged(Editables) { //判断editText是否为空 if(!TextUtils.isEmpty(s.toString())) { //如果有文字 btn_send_comment.setEnabled(true); } else { //如果为空 btn_send_comment.setEnabled(false); } content_tch = s.toString(); } //获得输入的老师评语 }; /** * 获得评论列表 * 当前被评论的老师id * 发表评论的老师id */ public void getComment(Integeruserid_becom, Integer userid) { ...... //给实体类赋值 comment = new Comment(); //获得评论的实体类集合 comment.commentid =commentid; comment.avatar = avatar; comment.userid = userid; comment.userid_becom =userid_becom; comment.username = username; comment.title = title; comment.commentdate =commentdate; comment.content_stu =content_stu; comment.usertype = usertype; comment.content_tch =content_tch; //添加到用户List中 list.add(comment); //给适配器数据 adapter.setList(list); adapter.notifyDataSetChanged(); ...... } @Override public void recomment(Comment commentItem,int position) {//commentItem,position都是从adapter传来的值 //点击回复按钮,开始写评语 InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE); imm.toggleSoftInput(0, InputMethodManager.RESULT_SHOWN); if (ll_write_comment.getVisibility() == View.VISIBLE) { ll_write_comment.setVisibility(View.INVISIBLE); } else { ll_write_comment.setVisibility(View.VISIBLE); } //输入框获得焦点 edt_write_comment.setFocusable(true); edt_write_comment.setFocusableInTouchMode(true); edt_write_comment.requestFocus(); //通过从适配器传来的,当前行所在的实体类对象及position , 给全局变量 //(1) 局部刷新的实体类对象ctiem //(2) 局部刷新的评论编号commentid_item //分别赋值 edt_write_comment.requestFocusFromTouch(); //给要局部更新的实体类对象赋值 citem = commentItem; //给要局部刷新的 评论id赋值 commentid_item = commentItem.commentid; } @Override public void onClick(View v) { //点击确认发送评语按钮,更新老师评语 updateCommentTch(commentid_item,content_tch); } //点击确认发送按钮,发送评语,并局部刷新listview /** * 更新老师评语 */ private void updateCommentTch(Integercommentid, final String content_tch) { RequestParams params = newRequestParams(); params.addBodyParameter("commentid", commentid +""); params.addBodyParameter("content_tch", content_tch); newHttpUtils().send(HttpRequest.HttpMethod.POST, Constans_lekao.URL_UPDATE_COMMENT_TCH, params, newRequestCallBack<String>() { @Override public void onSuccess(ResponseInfo<String>info) { //请求成功 String result =info.result.trim(); result =result.substring(result.indexOf(Constans_lekao.BRACKET) + 1); if (result.equals(Constans_lekao.ZERO)){ Utils.showToast("评论失败!"); } else { // 刷新评论的文字 //局部刷新!!! //竟然不用调用 //adapter.updateItemData(item);这个方法,adapter里也不用写,很神奇. // 获取listview中点击item的数据 Comment item = citem; // 更新数据 item.setContent_tch(content_tch); // 更新界面 // adapter.updateItemData(item); } //关闭软键盘 InputMethodManager imm= (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); imm.toggleSoftInput(0,InputMethodManager.HIDE_NOT_ALWAYS); ll_write_comment.setVisibility(View.GONE); } @Override public voidonFailure(HttpException e, String s) { } }); } }Adapter代码public class CommentAdapter extendsBaseAdapter {
private LayoutInflater inflater;
private List<Comment> list;
private BitmapUtils bitmapUtils;
private IControl_up control;
private ListView lv;
public void setLv(ListView lv) {
this.lv = lv;
}
public CommentAdapter(Context context) {
this.inflater = LayoutInflater.from(context);
bitmapUtils = Utils.getInstance();
}
public void setList(List<Comment> list) {
this.list = list;
}
public void setControl(IControl_up control) {
this.control = control;
}
/**
* update listview 单条数据
* @param commentItem 新数据对象
*/
/*publicvoid updateItemData(Comment commentItem) {
Message msg = Message.obtain();
int ids = -1;
// 进行数据对比获
d04d
取对应数据在list中的位置
for (int i = 0; i < list.size(); i++) {
if (list.get(i).commentid == commentItem.commentid) {
ids = i;
}
}
msg.arg1 = ids;
// 更新mDataList对应位置的数据
list.set(ids, commentItem);
// handle刷新界面
handler.sendMessage(msg);
}*/
//都不用写,也可以局部刷新,很神奇,可能是因为用了xUtils,走了其他线程的原因.
/*@SuppressLint("HandlerLeak")
privateHandler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
updateItem(msg.arg1);
}};*/
/**
* 刷新指定item
* @param index item在listview中的位置
*/
/*private void updateItem(int index) {
if (lv == null) {
return;
}
// 获取当前可以看到的item位置
int visiblePosition = lv.getFirstVisiblePosition();
// 如添加headerview后 firstview就是hearderview
// 所有索引+1 取第一个view
// View view = listview.getChildAt(index - visiblePosition + 1);
// 获取点击的view
View view = lv.getChildAt(index - visiblePosition);
TextView txt = (TextView) view.findViewById(R.id.txv_content_tch);
// 获取mDataList.set(ids,item);更新的数据
Comment commentItem = (Comment) getItem(index);
// 重新设置界面显示数据
txt.setText("试验");
//txt.setText(commentItem.content_tch);
}*/
@Override
public int getCount() {
return (list == null) ? 0 : list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroupparent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_student_comment, null);
holder = new ViewHolder();
holder.avatar = (ImageView)convertView.findViewById(R.id.imgv_stu_avatar_comment);
holder.username = (TextView)convertView.findViewById(R.id.txv_username_stu);
holder.commentdate = (TextView)convertView.findViewById(R.id.txv_commentdate_stu);
holder.title = (TextView) convertView.findViewById(R.id.txv_title_stu);
holder.content_stu = (TextView)convertView.findViewById(R.id.txv_content_stu);
holder.content_tch = (TextView)convertView.findViewById(R.id.txv_content_tch);
holder.ll_recomment = (RelativeLayout)convertView.findViewById(R.id.rl_recomment);
holder.rl_stu_allcomment = (RelativeLayout) convertView.findViewById(R.id.rl_stu_allcomment);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final Comment commentItem = list.get(position);
bitmapUtils.display(holder.avatar, commentItem.avatar);
holder.username.setText(commentItem.username);
holder.commentdate.setText(commentItem.commentdate);
holder.title.setText(commentItem.title);
holder.content_stu.setText(commentItem.content_stu);
holder.content_tch.setText(commentItem.content_tch);
// 判断当前用户是否是老师,只能评论有关自己的评论
if ((Integer)MyApplication.aCache.getAsObject(Constans_lekao.ACACHE_USERTYPE) == 2
&& (Integer)MyApplication.aCache.getAsObject(Constans_lekao.ACACHE_USERID) ==commentItem.userid_becom) {
holder.ll_recomment.setVisibility(View.VISIBLE);//可见
} else {
holder.ll_recomment.setVisibility(View.GONE);// 不可见
}
//老师回复评论点击事件
holder.ll_recomment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//获得当前行的 commentid
control.recomment(commentItem,position);
}
});
//查看该学生全部评论的点击事件
holder.rl_stu_allcomment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 调用外部接口把当前行的userid传过去
control.showAllComment(commentItem.userid);
}
});
return convertView;
}
public static class ViewHolder {
ImageView avatar;// 头像
TextView username;// 用户名
TextView commentdate;// 日期
TextView title;// 标题
TextView content_stu;// 评论的内容
TextView content_tch;//老师的回复
RelativeLayout ll_recomment;// 老师回复按钮
RelativeLayout rl_stu_allcomment;// 查看全部评论的按钮
}
}
3.动态删除一行
(1)适配器内代码//1.如果直接调用,那么会立即删除 //2.如果想弹出对话框提示是否删除,确认后再删除,那么将当前的position作为接口参数传给外界的Activity,再Activity里调用remove()方法进行移除当前行的操作. |
holder.btn_delete_homework.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
control.delete(homeworkItem.homeworkid, position);
//remove(position);
}
});
return convertView;
}
public void remove(int index) {
list.remove(index);
notifyDataSetChanged();
}
适配器内调用的删除接口 弹出(是否删除?)的对话框 参数1:实体类id 参数2:要删除的listview的position |
publicvoid delete(final int homeworkid, final intposition) {
//判断当前Activity是否在前台,如果在前台(可见)才能显示对话框
LayoutInflater inflater =LayoutInflater.from(getActivity());
View myview =inflater.inflate(R.layout.dialog_delete_homework, null);
AlertDialog.Builder builder = newAlertDialog.Builder(getActivity());
builder.setView(myview);
//取消按钮
myview.findViewById(R.id.rl_cancel).setOnClickListener(newView.OnClickListener() {
@Override
public void onClick(View v) {
dg_delete_homework.dismiss();
//步骤2:Activity内在服务器上删除数据的方法
}
});
//删除
myview.findViewById(R.id.rl_ok).setOnClickListener(newView.OnClickListener() {
@Override
public void onClick(View v) {
//删除作业
deleteHomework(homeworkid,position);
dg_delete_homework.dismiss();
}
});
dg_delete_homework = builder.create();
dg_delete_homework.show();
}
/**
* 删除作业
* @param homeworkid
*/
privatevoid deleteHomework(int homeworkid, final int position) {
RequestParams params = newRequestParams();
params.addBodyParameter("homeworkid",homeworkid+"");
new HttpUtils().send(HttpRequest.HttpMethod.POST,
Constans_lekao.URL_DELETE_HOMEWORK,
params,
newRequestCallBack<String>() {
@Override
public voidonSuccess(ResponseInfo<String> info) {
Stringresult = info.result.trim();
result= result.substring(result.indexOf(Constans_lekao.BRACKET)+1);
if(result.equals(Constans_lekao.ZERO)){
Utils.showToast("删除失败!");
}else{
Utils.showToast("删除成功!");
adapter.remove(position);
adapter.notifyDataSetChanged();
//步骤3:在这里执行适配器内声明的remove()方法,移除当前行
}
}
@Override
public voidonFailure(HttpException e, String s) {
}
});
}
相关文章推荐
- Android 左右滑屏 方向判断 ViewPager
- AndroidManifest.xml中的minSdkVersion、targetSdkVersion、maxSdkVersion和project.properties中target API lev
- uboot流程分析--修改android启动模式按键
- Activity生命周期
- 解决Lightmap在PC上与ios和Android上表现不同的问题
- 解决TimePickerDialog中onTimeSet执行两次的问题
- Android设置多个type
- Android APK反编译就这么简单 详解(附图)
- Android Studio NDK 开发 问题记录
- 王学岗Android的三级缓存(待续)
- android studio 中使用gradle命令行
- mac android studio 编译时报Class JavaLaunchHelper is implemented in both
- Android 性能优化
- Mac下android_sdk配置环境变量
- android中的AlarmManager和邮件服务
- ToolBar、TabLayout加角标无从下手且看一看我的解决方法!
- 解决Android Studio添加依赖时出现“Manifest merger failed
- Android Template(模板) 编写
- SVN 管理 Android 项目
- onTouchListener中的onTouch函数