在Android中,如何在listview中为某些项目设置按钮?
我正在为android创建一个社交网络应用程序,我有一个显示帖子的列表视图,我想做的是让用户能够删除自己的帖子,我不知道如何在一些帖子中删除按钮,而不是所有帖子。我希望你理解我的问题,任何帮助都将不胜感激。 多谢各位 这是提要的适配器:在Android中,如何在listview中为某些项目设置按钮?,android,listview,Android,Listview,我正在为android创建一个社交网络应用程序,我有一个显示帖子的列表视图,我想做的是让用户能够删除自己的帖子,我不知道如何在一些帖子中删除按钮,而不是所有帖子。我希望你理解我的问题,任何帮助都将不胜感激。 多谢各位 这是提要的适配器: public class FeedListAdapter extends BaseAdapter { private static final String TAG = FeedListAdapter.class.getSimpleName(); PopupW
public class FeedListAdapter extends BaseAdapter {
private static final String TAG = FeedListAdapter.class.getSimpleName();
PopupWindow popWindow = null;
private Activity activity;
private LayoutInflater inflater;
private List<FeedItem> feedItems;
private String URL = "http://192.168.1.10/social/like.php";
private String user_id;
ViewHolder holder;
private int[] mHighlightedPositions = new int[6];
private String test;
private CommentsListAdapter listAdapter;
private List<CommentsListItem> commentsitems;
private LikesListAdapter listAdapter1;
private List<FriendsListItem> likesitems;
private String URL1 = "http://192.168.1.10/social/comments.php";
private String URL2 = "http://192.168.1.10/social/comment.php";
private String URL3 = "http://192.168.1.10/social/likes.php";
private static final String TAG_SUCCESS = "success";
FeedItem item;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public FeedListAdapter(Activity activity, List<FeedItem> feedItems, String user_id) {
this.activity = activity;
this.feedItems = feedItems;
this.user_id = user_id;
}
@Override
public int getCount() {
return feedItems.size();
}
@Override
public Object getItem(int location) {
return feedItems.get(location);
}
@Override
public long getItemId(int position) {
return position;
}
public void refresh(List<FeedItem> newlist) {
feedItems.addAll(newlist);
this.notifyDataSetChanged();
}
public List<FeedItem> getData() {
return feedItems;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final View vi = convertView;
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
if (inflater == null)
inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null){
convertView = inflater.inflate(R.layout.posts_row, null);
holder = new ViewHolder();
holder.name = (Button)convertView .findViewById(R.id.name);
holder.timestamp = (TextView) convertView
.findViewById(R.id.time);
holder.statusMsg = (TextView) convertView
.findViewById(R.id.status);
holder. url = (TextView) convertView.findViewById(R.id.url);
holder.profilePic = (CircleImageView) convertView
.findViewById(R.id.profile_img);
holder.feedImageView = (FeedImageView) convertView
.findViewById(R.id.image);
holder.nbr_likes = (Button) convertView.findViewById(R.id.nbr_likes);
holder.nbr_comments = (Button)convertView.findViewById(R.id.nbr_comments);
holder.like =(Button)convertView.findViewById(R.id.like);
holder.comment =(Button)convertView.findViewById(R.id.comment);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
Log.d(TAG, "Button row pos click: " + getCount());
holder.like.setTag(position);
SharedPreferences prefs = activity.getSharedPreferences("mHighlightedPositions2", activity.MODE_PRIVATE);
String savedString = prefs.getString("string", "");
StringTokenizer st = new StringTokenizer(savedString, ",");
int[] savedList = new int[6];
for (int i = 0; i < 6; i++) {
while(st.hasMoreTokens())
mHighlightedPositions[i] = Integer.parseInt(st.nextToken());
}
if(mHighlightedPositions[position] == 1) {
holder.like.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like2, 0, 0, 0);
holder.like.setTextColor(Color.parseColor("#FF5722"));
notifyDataSetChanged();
}else {
holder.like.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like1, 0, 0, 0);
holder.like.setTextColor(Color.parseColor("#8B8B8F"));
notifyDataSetChanged();
}
holder.nbr_likes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
item = feedItems.get(position);
LayoutInflater layoutInflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View inflatedView = null;
PopupWindow popWindow = null;
// inflate the custom popup layout
inflatedView = layoutInflater.inflate(R.layout.likes, null, false);
// find the ListView in the popup layout
ListView listView = (ListView) inflatedView.findViewById(R.id.likesListView);
TextView emptyList = (TextView)inflatedView.findViewById(R.id.empty);
listView.setEmptyView(emptyList);
// get device size
Display display = activity.getWindowManager().getDefaultDisplay();
final Point size = new Point();
display.getSize(size);
int mDeviceHeight = size.y;
// fill the data to the list items
setLikesList(listView);
// set height depends on the device size
if(inflatedView!=null)
popWindow = new PopupWindow(inflatedView, size.x - 50, size.y - 400, true);
// set a background drawable with rounders corners
popWindow.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.fb_popup_bg));
// make it focusable to show the keyboard to enter in `EditText`
popWindow.setFocusable(true);
// make it outside touchable to dismiss the popup window
popWindow.setOutsideTouchable(true);
// show the popup at bottom of the screen and set some margin at bottom ie,
if(popWindow!=null)
popWindow.showAtLocation(inflatedView, Gravity.BOTTOM, 0, 100);
}
});
holder.like.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
item = feedItems.get(position);
int position = (Integer) v.getTag();
Log.d(TAG, "Button row pos click: " + getCount());
LinearLayout layout = (LinearLayout) v.getParent();
Button button = (Button) layout.getChildAt(0);
if (mHighlightedPositions[position] == 1) {
test ="delete";
item.setNbrLikes(item.getNbrLikes()-1);
button.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like1, 0, 0, 0);
button.setTextColor(Color.parseColor("#8B8B8F"));
mHighlightedPositions[position] = 0;
notifyDataSetChanged();
} else {
test ="add";
item.setNbrLikes(item.getNbrLikes()+1);
button.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like2, 0, 0, 0);
button.setTextColor(Color.parseColor("#FF5722"));
mHighlightedPositions[position] = 1;
notifyDataSetChanged();
}
Map<String, String> params = new HashMap<String, String>();
params.put("post_id", item.getId());
params.put("user_id", user_id);
params.put("test", test);
Toast.makeText(activity, item.getId(), Toast.LENGTH_SHORT).show();
Toast.makeText(activity, user_id, Toast.LENGTH_SHORT).show();
// making fresh volley request and getting json
CustomRequest jsonReq = new CustomRequest(Request.Method.POST,
URL, params, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
});
holder.comment.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
item = feedItems.get(position);
LayoutInflater layoutInflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View inflatedView = null;
// inflate the custom popup layout
inflatedView = layoutInflater.inflate(R.layout.comment, null, false);
// find the ListView in the popup layout
ListView listView = (ListView) inflatedView.findViewById(R.id.commentsListView);
TextView nbr_likes_pop = (TextView) inflatedView.findViewById(R.id.nbr_likes_pop);
TextView emptyList = (TextView)inflatedView.findViewById(R.id.empty);
listView.setEmptyView(emptyList);
nbr_likes_pop.setText(item.getNbrLikes()+" Persons Like this");
if (item.getNbrLikes() == 0) nbr_likes_pop.setText("No Like For This Post Yet");
ImageButton send = (ImageButton) inflatedView.findViewById(R.id.send);
final EditText writeComment =(EditText)inflatedView.findViewById(R.id.writeComment);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
item = feedItems.get(position);
if (writeComment.getText().toString() == "") {
} else {
item.setNbrComments(item.getNbrComments() + 1);
String comment = writeComment.getText().toString();
Long ts = System.currentTimeMillis();
String time = ts.toString();
String post_id = item.getId();
Map<String, String> params = new HashMap<String, String>();
params.put("post_id", post_id);
params.put("comment", comment);
params.put("time", time);
params.put("user_id", user_id);
CustomRequest jsonReq = new CustomRequest(Request.Method.POST,
URL2, params, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if (response != null) {
parseJsonComment(response);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
popWindow.dismiss();
}
}
});
// get device size
Display display = activity.getWindowManager().getDefaultDisplay();
final Point size = new Point();
display.getSize(size);
int mDeviceHeight = size.y;
// fill the data to the list items
setCommentList(listView);
// set height depends on the device size
if(inflatedView!=null)
popWindow = new PopupWindow(inflatedView, size.x - 50, size.y - 400, true);
// set a background drawable with rounders corners
popWindow.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.fb_popup_bg));
// make it focusable to show the keyboard to enter in `EditText`
popWindow.setFocusable(true);
// make it outside touchable to dismiss the popup window
popWindow.setOutsideTouchable(true);
// show the popup at bottom of the screen and set some margin at bottom ie,
if(popWindow!=null)
popWindow.showAtLocation(inflatedView, Gravity.BOTTOM, 0, 100);
}
});
holder.nbr_comments.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
item = feedItems.get(position);
LayoutInflater layoutInflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View inflatedView = null;
PopupWindow popWindow = null;
// inflate the custom popup layout
inflatedView = layoutInflater.inflate(R.layout.comments, null, false);
// find the ListView in the popup layout
ListView listView = (ListView) inflatedView.findViewById(R.id.commentsListView);
TextView nbr_likes_pop = (TextView) inflatedView.findViewById(R.id.nbr_likes_pop);
TextView emptyList = (TextView)inflatedView.findViewById(R.id.empty);
listView.setEmptyView(emptyList);
nbr_likes_pop.setText(item.getNbrLikes()+" Persons Like this");
if (item.getNbrLikes() == 0) nbr_likes_pop.setText("No Like For This Post Yet");
// get device size
Display display = activity.getWindowManager().getDefaultDisplay();
final Point size = new Point();
display.getSize(size);
int mDeviceHeight = size.y;
// fill the data to the list items
setCommentList(listView);
// set height depends on the device size
if(inflatedView!=null)
popWindow = new PopupWindow(inflatedView, size.x - 50, size.y - 400, true);
// set a background drawable with rounders corners
popWindow.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.fb_popup_bg));
// make it focusable to show the keyboard to enter in `EditText`
popWindow.setFocusable(true);
// make it outside touchable to dismiss the popup window
popWindow.setOutsideTouchable(true);
// show the popup at bottom of the screen and set some margin at bottom ie,
if(popWindow!=null)
popWindow.showAtLocation(inflatedView, Gravity.BOTTOM, 0, 100);
}
});
item = feedItems.get(position);
holder.name.setText(item.getName());
holder.nbr_likes.setText(item.getNbrLikes() + " Likes - ");
holder.nbr_comments.setText(item.getNbrComments() + " Comments");
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
Long.parseLong(item.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
holder.timestamp.setText(timeAgo);
// Chcek for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
holder.statusMsg.setText(item.getStatus());
holder.statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
holder.statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
holder.url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
holder.url.setMovementMethod(LinkMovementMethod.getInstance());
holder.url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
holder.url.setVisibility(View.GONE);
}
// user profile pic
holder.profilePic.setImageUrl(item.getProfilePic(), imageLoader);
// Feed image
if (item.getImge() != null) {
holder.feedImageView.setImageUrl(item.getImge(), imageLoader);
holder.feedImageView.setVisibility(View.VISIBLE);
holder.feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
@Override
public void onError() {
}
@Override
public void onSuccess() {
}
});
} else {
holder.feedImageView.setVisibility(View.GONE);
}
SharedPreferences.Editor editor = activity.getSharedPreferences("mHighlightedPositions2", activity.MODE_PRIVATE).edit();
StringBuilder str = new StringBuilder();
for (int i = 0; i < mHighlightedPositions.length; i++) {
str.append(mHighlightedPositions[i]).append(",");
}
editor.putString("string", str.toString());
return convertView;
}
void setCommentList(ListView listView){
commentsitems = new ArrayList<CommentsListItem>();
listAdapter = new CommentsListAdapter(activity, commentsitems);
listView.setAdapter(listAdapter);
Map<String, String> params = new HashMap<String, String>();
params.put("post_id", item.getId());
// making fresh volley request and getting json
CustomRequest jsonReq = new CustomRequest(Request.Method.POST,
URL1,params , new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if (response != null) {
parseJsonComments(response);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
void setLikesList(ListView listView){
likesitems = new ArrayList<FriendsListItem>();
listAdapter1 = new LikesListAdapter(activity, likesitems);
listView.setAdapter(listAdapter1);
Map<String, String> params = new HashMap<String, String>();
params.put("post_id", item.getId());
// making fresh volley request and getting json
CustomRequest jsonReq = new CustomRequest(Request.Method.POST,
URL3,params , new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if (response != null) {
parseJsonLikes(response);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
static class ViewHolder {
Button name;
TextView timestamp;
TextView statusMsg;
TextView url;
CircleImageView profilePic;
FeedImageView feedImageView;
Button nbr_likes;
Button nbr_comments;
Button like;
Button comment;
}
private void parseJsonFeed(JSONObject response) {
int success;
try {
success = response.getInt(TAG_SUCCESS);
if (success == 1) {
notifyDataSetChanged();
} else {
Toast.makeText(activity, "erreur", Toast.LENGTH_SHORT).show();
}
//listAdapter.addAll(feedItems);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void parseJsonComments(JSONObject response) {
int success;
try {
success = response.getInt(TAG_SUCCESS);
if (success == 1) {
JSONArray feedArray = response.getJSONArray("comments");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
CommentsListItem item = new CommentsListItem();
item.setId(feedObj.getString("comment_id"));
item.setName(feedObj.getString("name"));
item.setComment(feedObj.getString("comment"));
item.setProfile_img(feedObj.getString("profile_img"));
item.setTime(feedObj.getString("time"));
commentsitems.add(item);
// Toast.makeText(getContext(),feedObj.getString("text"), Toast.LENGTH_LONG).show();
}
// update data in our adapter
listAdapter.notifyDataSetChanged();
// notify data changes to list adapater
} else {
}
//listAdapter.addAll(feedItems);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void parseJsonLikes(JSONObject response) {
int success;
try {
success = response.getInt(TAG_SUCCESS);
if (success == 1) {
JSONArray feedArray = response.getJSONArray("likes");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FriendsListItem item = new FriendsListItem();
item.setName(feedObj.getString("name"));
item.setProfImage(feedObj.getString("profile_img"));
likesitems.add(item);
// Toast.makeText(getContext(),feedObj.getString("text"), Toast.LENGTH_LONG).show();
}
// update data in our adapter
listAdapter1.notifyDataSetChanged();
// notify data changes to list adapater
} else {
}
//listAdapter.addAll(feedItems);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void parseJsonComment(JSONObject response) {
int success;
try {
success = response.getInt(TAG_SUCCESS);
if (success == 1) {
notifyDataSetChanged();
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
公共类FeedListAdapter扩展了BaseAdapter{
私有静态最终字符串标记=FeedListAdapter.class.getSimpleName();
PopupWindow-popWindow=null;
私人活动;
私人充气机;
私人物品清单;
专用字符串URL=”http://192.168.1.10/social/like.php";
私有字符串用户标识;
视窗座;
私有int[]mHighlightedPositions=新int[6];
私有字符串测试;
私有注释listAdapter listAdapter;
私人网站列表;
私有类列表适配器列表适配器1;
私有列表类项目;
专用字符串URL1=”http://192.168.1.10/social/comments.php";
专用字符串URL2=”http://192.168.1.10/social/comment.php";
专用字符串URL3=”http://192.168.1.10/social/likes.php";
私有静态最终字符串标记_SUCCESS=“SUCCESS”;
饲料项目;
ImageLoader ImageLoader=AppController.getInstance().getImageLoader();
公共FeedListAdapter(活动、列表feedItems、字符串用户id){
这个。活动=活动;
此项。feedItems=feedItems;
this.user\u id=user\u id;
}
@凌驾
public int getCount(){
返回feedItems.size();
}
@凌驾
公共对象getItem(int位置){
返回feedItems.get(位置);
}
@凌驾
公共长getItemId(int位置){
返回位置;
}
公共无效刷新(列表新建列表){
feedItems.addAll(新列表);
this.notifyDataSetChanged();
}
公共列表getData(){
返回饲料项目;
}
@凌驾
公共视图getView(最终整数位置、视图转换视图、视图组父视图){
最终视图vi=转换视图;
如果(imageLoader==null)
imageLoader=AppController.getInstance().getImageLoader();
如果(充气器==null)
充气器=(LayoutFlater)父.getContext().getSystemService(Context.LAYOUT\u充气器\u服务);
if(convertView==null){
convertView=充气机。充气(R.layout.posts\u行,空);
holder=新的ViewHolder();
holder.name=(按钮)convertView.findViewById(R.id.name);
holder.timestamp=(TextView)convertView
.findviewbyd(R.id.time);
holder.statusMsg=(TextView)convertView
.findViewById(R.id.status);
holder.url=(TextView)convertView.findViewById(R.id.url);
holder.profilePic=(CircleImageView)convertView
.findviewbyd(R.id.profile\u img);
holder.feedImageView=(feedImageView)convertView
.findviewbyd(R.id.image);
holder.nbr\u likes=(按钮)convertView.findViewById(R.id.nbr\u likes);
holder.nbr\u comments=(按钮)convertView.findViewById(R.id.nbr\u comments);
holder.like=(Button)convertView.findViewById(R.id.like);
holder.comment=(按钮)convertView.findViewById(R.id.comment);
convertView.setTag(支架);
}否则{
holder=(ViewHolder)convertView.getTag();
}
Log.d(标签,“按钮行位置点击:”+getCount());
支架类固定标签(位置);
SharedReferences prefs=activity.GetSharedReferences(“mHighlightedPositions2”,activity.MODE\u PRIVATE);
String savedString=prefs.getString(“String”,”);
StringTokenizer st=新的StringTokenizer(savedString,“,”);
int[]savedList=新int[6];
对于(int i=0;i<6;i++){
而(st.hasMoreTokens())
mHighlightedPositions[i]=Integer.parseInt(st.nextToken());
}
如果(mHighlightedPositions[位置]==1){
holder.like.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like2,0,0,0);
holder.like.setTextColor(Color.parseColor(“#FF5722”));
notifyDataSetChanged();
}否则{
holder.like.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like1,0,0,0);
holder.like.setTextColor(Color.parseColor(#8b8f));
notifyDataSetChanged();
}
holder.nbr\u likes.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
项目=饲料项目。获取(位置);
LayoutInflater LayoutInflater=(LayoutInflater)activity.getSystemService(Context.LAYOUT\u INFLATER\u SERVICE);
视图充气视图=空;
PopupWindow-popWindow=null;
//对自定义弹出窗口布局进行充气
充气视图=LayoutFlater.充气(R.layout.likes,null,false);
//在弹出式布局中查找ListView
ListView ListView=(ListView)充气视图.findViewById(R.id.likesListView);
TextView emptyList=(TextView)inflatedView.findViewById(R.id.empty);
setEmptyView(emptyList);
//获取设备大小
Display Display=activity.getWindowManager().getDefaultDisplay();
最终点大小=新点();
display.getSize(size);
int-mDeviceHeight=size.y;
//将数据填入列表项
setLikesList(listView);
//设置高度取决于设备大小
如果(充气视图!=null)
popWindow=新的PopupWindow(充气视图,尺寸为.x-50,尺寸为.y-400,真);
//设置具有圆角的可绘制背景
setBackgroundDrawable(activity.getResources().getDrawable(R.draawable.fb_popup_bg));
//使其可聚焦显示键盘以输入“编辑文本”`
popWindow.setFocusable(真);
//使其在外部可触摸,以关闭弹出窗口
popWindow.setOutsideTouchable(真);
//在屏幕底部显示弹出窗口,并在底部设置一些边距,
if(popWindow!=null)