gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 12:22:17 25 4
gpt4 key购买 nike

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

但是这不起作用。我认为这是因为 notificationOnDataChange 使按钮可见性再次可见。

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() 实现始终会膨胀并返回 customview。由于您始终返回新扩展的 View ,因此扩展后未手动设置的 View 的所有属性都将设置为布局 xml 中的值(或默认值,如果未在此处设置)。

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

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

PS:一般来说,每次调用 getView() 时都膨胀一个新 View 是一个坏主意。您应该利用 convertView 参数和“viewholder”模式。这将提高您的应用程序的性能。搜索 Google 和此网站应该会给您一些关于此的想法。

关于java - 更改自定义适配器中按钮的可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45681524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com