我使用List.get(position)
来获取ListView
的位置。
但是这会从当前滚动边界的顶部返回位置。
我的ListView有50个项目,但你一次只能看到10个。
因此,当您完全向下滚动并调用List.get(位置)时,您将获得10个列表项而不是50.如果单击ListView
正好中间的项目,则得到5而不是25等。
如何从ListView
的实际顶部获取ListView
的排名。至少是最简单的方法。
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.addtowatchlist, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.label);
viewHolder.addbutton = (Button) view.findViewById(R.id.button);
viewHolder.addbutton
.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View buttonview) {
//I need the correct ACTUAL position here, not the VISABLE position
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(list.get(position).getUrl()));
context.startActivity(browserIntent);
list.get(position).getUrl();
Model element = (Model) viewHolder.addbutton
.getTag();
element.setSelected(true);
}
});
view.setTag(viewHolder);
viewHolder.addbutton.setTag(list.get(position));
} else {
view = convertView;
((ViewHolder) view.getTag()).addbutton.setTag(list.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(list.get(position).getName());
return view;
}
编辑:我认为它与使用错误的viewHolder调用onClickListener有关,但我无法弄明白...
答案 0 :(得分:1)
变量position
已经是ListView中条目的位置
我不知道你的名单里面有什么。
以下是BaseAdapter如何工作以及如何构建getView的教程:http://thinkandroid.wordpress.com/2010/01/13/custom-baseadapters/
答案 1 :(得分:0)
convertView
参数的作用......
我将onClickListener
移到if (convertView == null)
块之外,并在getView返回其视图之前将其放置。这样,所采取的位置不是可回收的可见位置,而是从顶部一直到ACTUAL位置。
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = null;
final AiringModel am = list.get(position);
am.setRealPosition(position, list.get(position).getUrl());
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.addtowatchlist, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.label);
if (convertView == null) {
view.setTag(viewHolder);
} else {
view = convertView;
((ViewHolder)view.getTag()).addbutton.setTag(list.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(list.get(position).getName());
viewHolder.addbutton = (Button) view.findViewById(R.id.check);
viewHolder.addbutton.setTag((Integer)position);
viewHolder.addbutton
.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View buttonview) {
// TODO Auto-generated method stub
int realPosition = am.getRealPosition();
String realName = am.getRealName();
Log.d("Pair created!", "Clicked button with position: "+ realPosition + " For item name: " + realName);
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(list.get(realPosition).getUrl()));
context.startActivity(browserIntent);
}
});
return view;
}