Обновление Listview в Android - PullRequest
       20

Обновление Listview в Android

0 голосов
/ 11 декабря 2018

Я пытаюсь создать мероприятие, в котором пользователь может создать рецепт и ввести ингредиенты.каждый раз, когда пользователь вводит ингредиент, он должен быть добавлен в список.Проблема, с которой я столкнулся, заключается в том, что первый вход является единственным, который добавляется в просмотр списка, а не остальные.

Вот скрипт макета:

<?xml version="1.0" encoding="utf-8"?><ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Activities.AddActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">


    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="226dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="8dp"
        android:orientation="vertical">

        <EditText
            android:id="@+id/Name_ET"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="@string/recipe_name" />

        <EditText
            android:id="@+id/ServingsNbr_ET"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="@string/number_of_servings" />

        <EditText
            android:id="@+id/PrepTime_Et"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="@string/preparation_time" />

        <EditText
            android:id="@+id/Calories_ET"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="@string/calories" />
    </LinearLayout>

    <LinearLayout
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="36dp"
            android:text="@string/ingredients"
            android:textSize="26sp"
            android:textAlignment="center"
            android:textStyle="bold"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <EditText
                android:id="@+id/new_ing"
                android:layout_width="0dp"
                android:layout_weight="9"
                android:layout_height="36dp" />
            <ImageView
                android:id="@+id/add_ingredient_btn"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="36dp"
                android:src="@drawable/round_add_circle_outline_black_36dp"/>
        </LinearLayout>

        <ListView
            android:id="@+id/ingredient_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"></ListView>
    </LinearLayout>

</LinearLayout>

И логика, стоящая за этим:

public class AddActivity extends AppCompatActivity {
private ListView added_ing;
private IngredientAdapter adapter;
private ArrayList<String> ingredients = new ArrayList<String>();
private EditText new_ing;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add);

    adapter = new IngredientAdapter(AddActivity.this,ingredients);
    added_ing = findViewById(R.id.ingredient_list);
    added_ing.setAdapter(adapter);

    new_ing = findViewById(R.id.new_ing);


    ImageView add_ingredien = findViewById(R.id.add_ingredient_btn);
    add_ingredien.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ingredients.add(new_ing.getText().toString());
            Toast.makeText(AddActivity.this, new_ing.getText().toString(), Toast.LENGTH_SHORT).show();
            adapter.notifyDataSetChanged();
        }
    });
}

public class IngredientAdapter extends ArrayAdapter<String> {

    ArrayList<String> mNewIngredients;
    public IngredientAdapter(Context context, ArrayList<String> objects) {
        super(context, 0, objects);
        mNewIngredients = objects;
    }
    public String getItem(int position) {
        return mNewIngredients.get(position).toString();
    }

    public View getView(int position, View convertView, ViewGroup parent) {

        String item = getItem(position);

        if(convertView==null)
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.ingredient,parent,false);

        TextView recipeName= convertView.findViewById(R.id.new_added_ingredient);
        recipeName.setText(item);
        return convertView;
    }

}

}

Ответы [ 3 ]

0 голосов
/ 11 декабря 2018

Попробуйте прокрутить вниз представление списка, возможно, в макете вашего элемента вы установили layout_height = match_parent, чтобы не видеть другие входные данные.

0 голосов
/ 11 декабря 2018

Вам необходимо добавить android:fillViewport="true" к вашему ScrollView

Также измените всю дочернюю высоту LinearLayout на wrap_content вместо match_parent

Попробуйте это

<?xml version="1.0" encoding="utf-8"?><ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
  android:fillViewport="true"
    android:layout_height="match_parent"
   >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">


        <ImageView
            android:id="@+id/imageView"
            android:layout_width="match_parent"
            android:layout_height="226dp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:orientation="vertical">

            <EditText
                android:id="@+id/Name_ET"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="@string/app_name" />

            <EditText
                android:id="@+id/ServingsNbr_ET"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="@string/app_name" />

            <EditText
                android:id="@+id/PrepTime_Et"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="@string/app_name" />

            <EditText
                android:id="@+id/Calories_ET"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="@string/app_name" />
        </LinearLayout>

        <LinearLayout
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/textView"
                android:layout_width="match_parent"
                android:layout_height="36dp"
                android:text="@string/app_name"
                android:textSize="26sp"
                android:textAlignment="center"
                android:textStyle="bold"/>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
                <EditText
                    android:id="@+id/new_ing"
                    android:layout_width="0dp"
                    android:layout_weight="9"
                    android:layout_height="36dp" />
                <ImageView
                    android:id="@+id/add_ingredient_btn"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:layout_height="36dp"
                    android:src="@drawable/ic_launcher_background"/>
            </LinearLayout>

            <ListView
                android:id="@+id/ingredient_list"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"></ListView>
        </LinearLayout>

    </LinearLayout>
</ScrollView>
0 голосов
/ 11 декабря 2018

В вашей реализации IngredientAdapter вы используете свой собственный ArrayList mNewIngredients для данных вместо сбора в ArrayAdapter.Когда вы добавляете новые данные в ingredients, они не добавляются в адаптер.

Для простоты использовать коллекцию, реализованную в ArrayAdapter.Ниже приведен пример с держателем вида, позволяющим использовать его повторно.

public class IngredientAdapter extends ArrayAdapter<String> {

    public IngredientAdapter(Context context, ArrayList<String> objects) {
        super(context, 0, objects);
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;

        if(convertView==null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.ingredient, parent, false);

            holder = new ViewHolder();
            holder.recipeName = convertView.findViewById(R.id.new_added_ingredient);

            convertView.Tag = holder;
        } else {
            holder = (ViewHolder)convertView.Tag;
        }

        String item = getItem(position);
        holder.recipeName.setText(item);
        return convertView;
    }
}

public class ViewHolder {
    public TextView recipeName;
}

Данные в адаптере теперь поддерживаются внутренней коллекцией.А в упражнении вы должны добавить новые данные непосредственно в адаптер.

public class AddActivity extends AppCompatActivity {
    private ListView added_ing;
    private IngredientAdapter adapter;
    // keep this if you need it for something else
    // private ArrayList<String> ingredients = new ArrayList<String>();
    private EditText new_ing;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);

        adapter = new IngredientAdapter(AddActivity.this,ingredients);
        added_ing = findViewById(R.id.ingredient_list);
        added_ing.setAdapter(adapter);

        new_ing = findViewById(R.id.new_ing);

        ImageView add_ingredien = findViewById(R.id.add_ingredient_btn);
        add_ingredien.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // keep this if you need it for something else
                // ingredients.add(new_ing.getText().toString());

                // to add adata into the adapter
                adapter.Add(new_ing.getText().toString());

                Toast.makeText(AddActivity.this, new_ing.getText().toString(), Toast.LENGTH_SHORT).show();
                adapter.notifyDataSetChanged();
            }
        });
    }
}
...