我有带有自定义适配器的 ListView 。每行都包含可点击的按钮和文本。
目前 onClickListeners 已在主体中设置getView()
,这是一个非常疯狂的想法,因为这个方法被频繁调用。在每个 onClick 函数中,我需要访问私有数据以使用捆绑包调用新活动。
如何将 onClick 定义移到 getView() 例程之外?
当调用 onClick 时,我需要有关列表元素的位置(以访问私有数据)以及单击了哪个视图(以启动正确的活动)的信息。
public View getView(int position, View convertView, ViewGroup parent) {
if(convertview == null) {
convertView = ((Activity) getContext()).getLayoutInflater().inflate(R.layout.photo_tweet_row, null);
}
TextView userTweet = (TextView) v.findViewById(R.id.feed_user_tweet_body);
RepliesButton repliesBtn = (RepliesButton) v.findViewById(R.id.feed_replies_button);
Status twitterDataItem = getItem(position);
if (twitterDataItem != null) {
if (userTweet != null) {
userTweet.setText(twitterDataItem.getText());
}
if (repliesBtn != null) {
repliesBtn.setText(" replies");
}
userTweet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), ProfileActivity.class);
intent.putExtra(getContext().getString(R.string.serializable_user), twitterDataItem.getUser());
getContext().startActivity(intent);
}
});
repliesBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (!twitterDataItem.getComments().contentEquals("0")) {
Intent myIntent = new Intent(getContext(), RepliesToFeedActivity.class);
myIntent.putExtra("photoTweet", twitterDataItem);
getContext().startActivity(myIntent);
}
}
});
}
return convertView;
}
您的活动必须实现 OnClickListener,并将实现的方法移至活动级别。
基于view
您可以检测事件来自哪个 UI 对象(按钮、文本视图)的方法参数。
至于如何检测列表视图中的哪条记录/行。你必须设置一个自定义tag
在按钮和文本视图上getView
方法,您将通过以下方式在事件中阅读getTag
如果字符串不够,这个标签也可以是自定义对象。可能/推荐的方法是位于适配器中的位置。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)