Android開發---ListView實現區域性重新整理及刪除
阿新 • • 發佈:2019-01-29
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 public 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;
// 進行資料對比獲取對應資料在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()方法進行移除當前行的操作. |
介面卡內呼叫的刪除介面 彈出(是否刪除?)的對話方塊 引數1:實體類id 引數2:要刪除的listview的position |
@Override
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) {
}
});
}