我有一个带有Textview,ImageView和Button的列表视图,我想要的是在点击按钮时更改按钮的背景,我希望你能解决我的问题。
这是适配器。
package com.example.mahdi.chat;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.method.LinkMovementMethod;
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 com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import circleview.CircleImageView;
public class FeedListAdapter extends BaseAdapter {
private static final String TAG = FeedListAdapter.class.getSimpleName();
private Activity activity;
private LayoutInflater inflater;
private List<FeedItem> feedItems;
JSONParser jsonParser = new JSONParser();
private String URL = "http://10.0.3.2/social/like.php";
private String user_id;
private Button like,comment;
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) {
if (inflater == null)
inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.posts_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
final TextView name = (TextView) convertView.findViewById(R.id.name);
TextView timestamp = (TextView) convertView
.findViewById(R.id.time);
TextView statusMsg = (TextView) convertView
.findViewById(R.id.status);
TextView url = (TextView) convertView.findViewById(R.id.url);
CircleImageView profilePic = (CircleImageView) convertView
.findViewById(R.id.profile_img);
FeedImageView feedImageView = (FeedImageView) convertView
.findViewById(R.id.image);
TextView nbr_likes = (TextView)convertView.findViewById(R.id.nbr_likes);
TextView nbr_comments = (TextView)convertView.findViewById(R.id.nbr_comments);
item = feedItems.get(position);
like =(Button)convertView.findViewById(R.id.like);
comment =(Button)convertView.findViewById(R.id.comment);
like.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
item = feedItems.get(position);
Map<String, String> params = new HashMap<String, String>();
params.put("post_id", item.getId());
params.put("user_id", user_id);
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);
}
});
comment.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
}
});
name.setText(item.getName());
nbr_likes.setText(item.getNbrLikes()+ " Likes");
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);
timestamp.setText(timeAgo);
// Chcek for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
statusMsg.setText(item.getStatus());
statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
url.setMovementMethod(LinkMovementMethod.getInstance());
url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
url.setVisibility(View.GONE);
}
// user profile pic
profilePic.setImageUrl(item.getProfilePic(), imageLoader);
// Feed image
if (item.getImge() != null) {
feedImageView.setImageUrl(item.getImge(), imageLoader);
feedImageView.setVisibility(View.VISIBLE);
feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
@Override
public void onError() {
}
@Override
public void onSuccess() {
}
});
} else {
feedImageView.setVisibility(View.GONE);
}
return convertView;
}
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();
}
}
}
FeedItem类
package com.example.mahdi.chat;
public class FeedItem {
private String id,name, status, image, profile_img, time, url,nbr_likes,nbr_comments;
public FeedItem() {
}
public FeedItem(String id, String name, String image, String status,
String profilePic, String timeStamp, String url,String nbr_likes,String nbr_comments) {
super();
this.id = id;
this.name = name;
this.image = image;
this.status = status;
this.profile_img = profilePic;
this.time = timeStamp;
this.url = url;
this.nbr_likes = nbr_likes;
this.nbr_comments = nbr_comments;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImge() {
return image;
}
public void setImge(String image) {
this.image = image;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getProfilePic() {
return profile_img;
}
public void setProfilePic(String profilePic) {
this.profile_img = profilePic;
}
public String getTimeStamp() {
return time;
}
public void setTimeStamp(String timeStamp) {
this.time = timeStamp;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getNbrLikes() {
return nbr_likes;
}
public void setNbrLikes(String nbr_likes) {
this.nbr_likes = nbr_likes;
}
public String getNbrComments() {
return nbr_comments;
}
public void setNbrComments(String nbr_comments) {
this.nbr_comments = nbr_comments;
}
}
问题是按钮赞,我想在点击时更改按钮的可绘制。谢谢。
编辑:
package com.example.mahdi.chat;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.method.LinkMovementMethod;
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 com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import circleview.CircleImageView;
public class FeedListAdapter extends BaseAdapter {
private static final String TAG = FeedListAdapter.class.getSimpleName();
private Activity activity;
private LayoutInflater inflater;
private List<FeedItem> feedItems;
JSONParser jsonParser = new JSONParser();
private String URL = "http://10.0.3.2/social/like.php";
private String user_id;
private Button like,comment;
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) {
if (inflater == null)
inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.posts_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
final TextView name = (TextView) convertView.findViewById(R.id.name);
TextView timestamp = (TextView) convertView
.findViewById(R.id.time);
TextView statusMsg = (TextView) convertView
.findViewById(R.id.status);
TextView url = (TextView) convertView.findViewById(R.id.url);
CircleImageView profilePic = (CircleImageView) convertView
.findViewById(R.id.profile_img);
FeedImageView feedImageView = (FeedImageView) convertView
.findViewById(R.id.image);
TextView nbr_likes = (TextView)convertView.findViewById(R.id.nbr_likes);
TextView nbr_comments = (TextView)convertView.findViewById(R.id.nbr_comments);
item = feedItems.get(position);
like =(Button)convertView.findViewById(R.id.like);
comment =(Button)convertView.findViewById(R.id.comment);
like.setTag(position);
like.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
int position = (Integer) v.getTag();
like.setBackgroundColor(Color.BLACK);
item = feedItems.get(position);
Map<String, String> params = new HashMap<String, String>();
params.put("post_id", item.getId());
params.put("user_id", user_id);
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);
}
});
comment.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
item = feedItems.get(position);
Intent i = new Intent(activity, Comment.class);
i.putExtra("user_id",item.getId());
i.putExtra("name",item.getName());
i.putExtra("image",item.getImge());
i.putExtra("status",item.getStatus());
i.putExtra("profile_img",item.getProfilePic());
i.putExtra("time",item.getTimeStamp());
i.putExtra("url",item.getUrl());
i.putExtra("nbr_likes",item.getNbrLikes());
i.putExtra("nbr_comments",item.getNbrComments());
activity.startActivity(i);
}
});
name.setText(item.getName());
nbr_likes.setText(item.getNbrLikes()+ " Likes");
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);
timestamp.setText(timeAgo);
// Chcek for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
statusMsg.setText(item.getStatus());
statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
url.setMovementMethod(LinkMovementMethod.getInstance());
url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
url.setVisibility(View.GONE);
}
// user profile pic
profilePic.setImageUrl(item.getProfilePic(), imageLoader);
// Feed image
if (item.getImge() != null) {
feedImageView.setImageUrl(item.getImge(), imageLoader);
feedImageView.setVisibility(View.VISIBLE);
feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
@Override
public void onError() {
}
@Override
public void onSuccess() {
}
});
} else {
feedImageView.setVisibility(View.GONE);
}
return convertView;
}
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();
}
}
}
答案 0 :(得分:3)
假设按钮在列表视图中。 首先在适配器的getView函数中的按钮上定义一个单击侦听器:
likebutton.setOnClickListener(likeButtonClickListener);
然后定义onclick监听器:
private OnClickListener likeButtonClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
View parentRow = (View) v.getParent();
ListView listView = (ListView) parentRow.getParent();
final int position = listView.getPositionForView(parentRow);
}
};
通过在getView函数中设置标记还有另一种方法:
likebutton.setTag(position);
likebutton.setOnClickListener(likeButtonClickListener);
在按钮单击监听器中,我们将获取标签并找到位置值。
private OnClickListener likeButtonClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
int position = (Integer) v.getTag();
}
};
编辑,解释我在评论中提到的链接的解决方案。 他声明了一个最终的布尔变量 mHighlightedPositions ,如果选择了列表视图中突出显示的位置,它将提供信息。 如果此变量返回 true ,则会选择列表视图中的行,因此您可以执行的操作。
将变量“NUM_OF_ITEMS”声明为整数,将“mHighlightedPositions”声明为适配器中的布尔值:
private int NUM_OF_ITEMS;
private final boolean[] mHighlightedPositions = new boolean[NUM_OF_ITEMS];
使用此功能,您可以定义是否选择了列表视图中的项目,并将背景/颜色应用于按钮,如下所示:
...
if(mHighlightedPositions[position]) {
holder.likebutton.setBackgroundResource(R.drawable.icon_yellow_star_large);
}else {
holder.likebutton.setBackgroundResource(0);
}
...
如果你想跟随他的例子,你还需要声明一个ViewHolder。
holder = new ViewHolder();
项目的位置将由位置变量返回:
int position = (Integer)view.getTag();
请参阅以下链接中的示例:
@Override
public void onClick(View view) {
int position = (Integer)view.getTag(); // gets current position
Log.d(TAG, "Button row pos click: " + position);
...
...
if(mHighlightedPositions[position]) { // current position is given
button.setBackgroundResource(0);
mHighlightedPositions[position] = false;
}else {
button.setBackgroundResource(R.drawable.icon_yellow_star_large);
mHighlightedPositions[position] = true;
}
}