2017-08-14 126 views
0

我有一個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; 
} 

Image of the app

應該讓新元素添加到列表中,並刪除按鈕來添加更多的elemenets,在第一個(加號按鈕)。讓用戶列出配料清單。

+0

評論notifyDataSetChange()行並再次檢查。 –

回答

1

你基本上是正確的;調用notifyDataSetChanged()將使您的按鈕重新出現。但爲什麼?

當您撥打notifyDataSetChanged()時,您的ListView將完全重新繪製自己,並返回適配器以獲取所需信息。這包括爲列表中的所有當前可見項目調用getView()

您對getView()的實施總是膨脹並返回customview。由於你總是返回一個新增的視圖,所以在通貨膨脹之後你不需要手動設置的視圖的所有屬性都將被設置爲佈局xml中的值(或者如果它們沒有在這裏設置,則設置爲默認值)。

可見性的默認值是VISIBLE,所以當您膨脹customview時,您的plusButton將始終可見,除非您手動將其更改爲GONE

您必須存儲某種指示,指示給定的position上的按鈕是否應該可見或不見,然後在您膨脹customview後在getView()內應用此指示。 PS:一般來說,每調用一次getView()就誇大一個新視圖是一個不好的主意。您應該使用convertView參數和「視圖持有者」模式。這會改善你的應用程序的性能。搜索谷歌和這個網站應該給你一些關於這個的想法。

+0

謝謝!我從行中刪除了按鈕,並將其放在我的主視圖上,現在可以正常工作。此外,我在谷歌搜索查看持有人,我修改了我的代碼,與視圖持有人和文本觀察員的Recycler視圖工作,這對我的應用程序一般工作更好。 –

相關問題