更改自定义适配器中按钮的可见性
我有一个listview和自定义适配器的问题。我试图把一个按钮的可见性当我点击它时消失了,为列表创建一个新的元素来编辑和更改。更改自定义适配器中按钮的可见性
但它不起作用。我认为这是因为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;
}
应该让新元素添加到列表中,并删除按钮来添加更多的elemenets,在第一个(加号按钮)。让用户列出配料清单。
你基本上是正确的;调用notifyDataSetChanged()
将使您的按钮重新出现。但为什么?
当您拨打notifyDataSetChanged()
时,您的ListView将完全重新绘制自己,并返回适配器以获取所需信息。这包括为列表中的所有当前可见项目调用getView()
。
您对getView()
的实施总是膨胀并返回customview
。由于你总是返回一个新增的视图,所以在通货膨胀之后你不需要手动设置的视图的所有属性都将被设置为布局xml中的值(或者如果它们没有在这里设置,则设置为默认值)。
可见性的默认值是VISIBLE
,所以当您膨胀customview
时,您的plusButton
将始终可见,除非您手动将其更改为GONE
。
您必须存储某种指示,指示给定的position
上的按钮是否应该可见或不见,然后在您膨胀customview
后在getView()
内应用此指示。 PS:一般来说,每调用一次getView()
就夸大一个新视图是一个不好的主意。您应该使用convertView
参数和“视图持有者”模式。这会改善你的应用程序的性能。搜索谷歌和这个网站应该给你一些关于这个的想法。
谢谢!我从行中删除了按钮,并将其放在我的主视图上,现在可以正常工作。此外,我在谷歌搜索查看持有人,我修改了我的代码,与视图持有人和文本观察员的Recycler视图工作,这对我的应用程序一般工作更好。 –
评论notifyDataSetChange()行并再次检查。 –