从ListView,自定义适配器更新特定的行布局

时间:2017-04-16 19:19:47

标签: android listview button android-arrayadapter onclicklistener

当我点击属于该行的“接受”按钮时,我想更新一个特定的行,但不知怎的,它正在更新错误的行,我想获得一些如何解决这个问题的指导。

我在第一行按“接受”,但第二行更新了。

这是我的代码:

public class UserAdapter extends ArrayAdapter<User> {

    private View listRow;
    private String mOrderId;
    private LinearLayout userNotChosenLayout, userChosenLayout;

    public UserAdapter(Context context, List<User> users, String orderId) {
        super(context, 0, users);
        mOrderId = orderId;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        listRow = convertView;

        if (listRow == null) {
            listRow = LayoutInflater.from(getContext()).inflate(R.layout.row_my_order_users, parent, false);
        }
        User currentUser = getItem(position);
        TextView userName = (TextView) listRow.findViewById(R.id.textview_user_name);
        userName.setText(currentUser.getName());
        setListeners(position);
        return listRow;
    }

    private void setListeners(final int position) {
        Button acceptBtn = (Button) listRow.findViewById(R.id.button_accept_user);
        acceptBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(), "UserID: " + getItem(position).getId(), Toast.LENGTH_SHORT).show();
                new AcceptUser().execute(mOrderId, getItem(position).getId());

                View view = getView(position, listRow, null);

                userChosenLayout = (LinearLayout) view.findViewById(R.id.user_chosen_layout);
                userNotChosenLayout = (LinearLayout) view.findViewById(R.id.user_not_chosen_layout);

                userChosenLayout.setVisibility(View.VISIBLE);
                userNotChosenLayout.setVisibility(View.GONE);
            }
        });
    }

enter image description here

1 个答案:

答案 0 :(得分:1)

如果它总是更新下面的行那么它应该 - 然后只是从位置删除1。

首先,不推荐使用ListView,只使用RecyclerView,它更轻松,更容易使用(如果你仍然遇到问题 - 然后发布)

Google的RecyclerView示例:https://developer.android.com/training/material/lists-cards.html

可搜索和可扩展的recycerview示例(在对话框容器中,这个想法是相同的):https://github.com/WithoutCaps/DialogsCheatSheet