简体   繁体   English

更新ListView上次单击的项目

[英]Update ListView previous clicked item

I have ListView which is customized to have a EditText box and a Button in it. 我有ListView,它被自定义为具有一个EditText框和一个Button。 The ListView displays text boxes as visible but the button as invisible . ListView将文本框显示为visible但按钮显示为invisible When the user clicks on an item in the ListView, the Button's made visible. 当用户单击ListView中的项目时,按钮变为可见。 I have written the following code for the ListView: 我为ListView编写了以下代码:

public void onItemClick(AdapterView<?> list, View view, int position, long id) {    
    view.findViewById(R.id.button).setVisibility(View.VISIBLE);
}

The above code functions in the case when the first item's Button and the second item's Button are visible. 上面的代码在第一项的按钮和第二项的按钮可见的情况下起作用。

My problem: 我的问题:
When the next item in the ListView is clicked, the Button from the previous item should become invisible as the current item's Button becomes visible. 单击ListView中的下一个项目时,前一个项目中的Button应该变为不可见,因为当前项目的Button变为可见。 So how do I update the view of the previous item? 那么,如何更新上一个项目的视图?

Store the previous row in a class variable: 将上一行存储在类变量中:

View previous;
...

public void onItemClick(AdapterView<?> list, View view, int position, long id) {    
    if(previous != null)
        previous.setVisibility(View.INVISIBLE);

    // Set the current button to visible while saving it for the next click 
    previous = view.findViewById(R.id.button);
    previous.setVisibility(View.VISIBLE);
}

Addition from comments 从评论中添加

You're right. 你是对的。 The adapter's view recycling is affecting the other rows so let's extend whatever adapter you are using and override its getView() method: 适配器的视图回收会影响其他行,因此让我们扩展您使用的任何适配器并覆盖其getView()方法:

public int selectedRow = -1;
...

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = super.getView(position, convertView, parent);

    // Here, either use findViewById() (slower) or the ViewHolder method (faster) to load the button:
    // Button button = ...

    if(position == selectedRow) 
        button.setVisibility(View.VISIBLE);
    else
        button.setVisibility(View.GONE);

    return view;
}

And in your onItemClick() method add a line like this: 然后在您的onItemClick()方法中添加如下一行:

adapter.selectedRow = position;

Attach a listener on the button instead of the listview itself. 在按钮上而不是列表视图本身上附加一个侦听器。 You could do it in the getview() method. 您可以在getview()方法中完成此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM