2017-08-14 1 views
0

リストビューとカスタムアダプターに問題があります。私がそれをクリックすると消えていくボタンの可視性を入れようとしている私は、リストの編集と変更のための新しい要素を作成します。カスタムアダプターのボタンの表示の変更

しかし、動作しません。私はそれが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

これは、リストに新しい要素を追加してみましょう、と最初の1(プラスボタン)で、より多くのelemenetsを追加するためのボタンを削除する必要があります。ユーザーが成分のリストを作ることを可能にする。

+0

コメントnotifyDataSetChange()行をチェックしてもう一度チェックします。 –

答えて

1

本質的に正しいです。 notifyDataSetChanged()を呼び出すと、ボタンが再び表示されます。しかし、なぜ?

notifyDataSetChanged()を呼び出すと、ListViewが完全に再描画され、必要な情報をアダプタに戻します。これには、リスト内で現在表示されているすべての項目に対してgetView()を呼び出します。

お客様の実装では、getView()は常に膨張し、customviewを返します。新しくインフレしたビューを返すので、インフレーション後に手動で設定しないビューのすべての属性は、レイアウトxmlの値(またはここで設定されていない場合はデフォルト)に設定されます。

可視性のデフォルト値はVISIBLEあるので、あなたはcustomviewを膨らませるときは、手動GONEにそれを変更しない限り、あなたのplusButtonは常に表示されます。

positionのボタンを表示するかどうかの表示を保存しておき、customviewを膨張させた後にgetView()の内部に適用する必要があります。

PS:一般的には、getView()が呼び出されるたびに新しいビューを展開するのは悪い考えです。 convertView引数と「ビューホルダー」パターンを活用する必要があります。これにより、アプリのパフォーマンスが向上します。 Googleとこのサイトを検索すると、これに関するいくつかのアイデアが得られます。

+0

ありがとうございます!私は行からボタンを削除し、私はそれを私のメインビューに入れ、今は正常に動作します。また、私は、ビューの所有者についてはGoogleで検索し、私は一般的に私のアプリのためにはるかに良い作品、ビューホルダーとテキストウォッチャーとRecyclerビューで動作するように私のコードを改良した。 –

関連する問題