我有一个项目列表,在点击项目之后,应该设置ProgressBar我想要设置的进度值。我已经这样做了,但它不起作用(它没有显示设置的进度值)。
HashMap<Integer,Boolean> states = new HashMap<Integer, Boolean>();
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.my_list_item, parent, false);
}
progressBar = ((ProgressBar) view.findViewById(R.id.progress_bar));
playButton = ((ImageButton) view.findViewById(R.id.play_pause));
playButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if(states.containsKey(position))
{
states.put(position, !states.get(position));
playButton = ((ImageButton) view.findViewById(R.id.play_pause));
playButton.setImageResource(states.get(position) ? R.drawable.button_pause : R.drawable.button_play);
// Here i set the tag that the row of listview is clicked
progressBar.setTag(position);
}
else
{
states.put(position, true);
playButton = ((ImageButton) view.findViewById(R.id.play_pause));
playButton.setImageResource(R.drawable.button_pause);
// Here i set the tag that the row of listview is clicked
progressBar.setTag(position);
}
// Here i want to get the clicked progressBar using the tag we set above
progressBar.setProgress(100); // Does not work.... no effect on progressBar
}
}
return view;
}
我试过这些,但没有锁定。我认为,问题是,如果我使用视图,我得到空指针异常。也许是因为,我试图访问playButton的onClick(View视图)中的视图。我不知道如何解决它,任何帮助都将不胜感激。
progressBar = ((ProgressBar) view.getTag());
progressBar = ((ProgressBar) convertView.getTag());
答案 0 :(得分:1)
你的方法的问题是OnClickListener是一个回调函数,它不是作为getView方法的一部分执行的,而是在一个封闭类的属性中保存对ProgressBar的引用,实际上每个属性都被覆盖列表中的行,实际上只保留引用的最后一个ProgressBar。因此,每次单击任何行时,实际上都会更新最后渲染的ProgressBar。
解决方案是将最后一个变量中的进度条引用作为封闭的getView方法上下文的一部分。
HashMap<Integer,Boolean> states = new HashMap<Integer, Boolean>();
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.my_list_item, parent, false);
}
final ProgressBar progressBar = ((ProgressBar) view.findViewById(R.id.progress_bar));
final ImageButton playButton = ((ImageButton) view.findViewById(R.id.play_pause));
playButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if(states.containsKey(position))
{
states.put(position, !states.get(position));
playButton.setImageResource(states.get(position) ? R.drawable.button_pause : R.drawable.button_play);
// Here i set the tag that the row of listview is clicked
progressBar.setTag(position);
}
else
{
states.put(position, true);
playButton.setImageResource(R.drawable.button_pause);
// Here i set the tag that the row of listview is clicked
progressBar.setTag(position);
}
// Here i want to get the clicked progressBar using the tag we set above
progressBar.setProgress(100); // Does not work.... no effect on progressBar
}
}
return view;
}