更改自定义适配器中按钮的可见性

Changing visibility on button in custom adapter

我对列表视图和自定义适配器有疑问。我试图在单击按钮时让按钮的可见性消失,并为列表创建一个新元素以进行编辑和更改。

但是没用。我认为这是因为 notifyOnDataChange 使按钮可见性再次可见。

public class CustomAdapterIngredientsUser extends ArrayAdapter<Recipe.Ingredients.Ingredient>

List<Recipe.Ingredients.Ingredient> ingredientList;
Context context;
EditText textQuantity;
EditText textName;
Button xButton;
Button plusButton;
public CustomAdapterIngredientsUser(Context context, List<Recipe.Ingredients.Ingredient> resource) {
    super(context,R.layout.ingredient_new_recipe,resource);
    this.context = context;
    this.ingredientList = resource;
}

@NonNull
@Override
public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {

    LayoutInflater layoutInflater = LayoutInflater.from(getContext());
    final View customview = layoutInflater.inflate(R.layout.ingredient_new_recipe,parent,false);
    textQuantity = (EditText) customview.findViewById(R.id.quantityText);
    textName = (EditText) customview.findViewById(R.id.ingredientName);

    plusButton= (Button) customview.findViewById(R.id.newIngredientButton);
    xButton = (Button) customview.findViewById(R.id.Xbutton);
    xButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ingredientList.remove(position);
            notifyDataSetChanged();

        }
    });
    plusButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            plusButton.setVisibility(customview.GONE);

            String name = textName.getText().toString();
            String qnt = textQuantity.getText().toString();
            Recipe.Ingredients.Ingredient ing2 = new Recipe.Ingredients.Ingredient("Quantity","Name","Photo");
            ingredientList.add(ing2);

            notifyDataSetChanged();

        }
    });

    return customview;
}

Image of the app

应该允许向列表中添加新元素,并在第一个(加号按钮)中删除添加更多元素的按钮。让用户列出配料表。

你基本上是正确的;调用 notifyDataSetChanged() 将使您的按钮重新出现。但是为什么?

当您调用 notifyDataSetChanged() 时,您的 ListView 将完全重绘自身,返回到您的适配器以获得它需要的信息。这涉及为列表中所有当前可见的项目调用 getView()

您对 getView() 的实施总是膨胀并且 returns customview。由于您总是返回一个新膨胀的视图,因此您在 inflation 之后未手动设置的所有视图属性都将设置为布局中的值 xml (或默认值,如果它们是此处未设置)。

可见性的默认值为 VISIBLE,因此当您膨胀 customview 时,您的 plusButton 将始终可见,除非您手动将其更改为 GONE

您必须存储某种指示,指示给定 position 处的按钮是否可见或消失,然后在膨胀 customview 后在 getView() 中应用它.

PS:通常,每次调用 getView() 时都膨胀一个新视图是个坏主意。您应该利用 convertView 参数和 "view holder" 模式。这将提高您的应用程序的性能。搜索 Google 和这个网站应该会给你一些想法。