首页 文章

Android Studio - 自定义Listview EditText值不存储

提问于
浏览
0

因此,每当我在列表视图上向下滚动,并在editText上放置一个值时,editText的值在向下滚动时就会消失 . 我正在为listview使用自定义布局 .

我希望每当listview的行离开屏幕时阻止EditText值消失 .

add_food_intake.java

public class add_food_intake extends AppCompatActivity {
    SQLiteDatabase db, Foods;
    SQLiteOpenHelper helper1, helper;
    ArrayList<String> listItem;
    ArrayAdapter adapter;
    ListView foodview;
    SwipeRefreshLayout swiper;
    EditText editText1;

    int id;
    String str, str1, age1, foodname, foodtype, grams, kCal, carbohydrates;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_food_intake);
        helper = new FoodDB(this);
        editText1 = findViewById(R.id.editText1);
        db = helper.getReadableDatabase();
        helper1 = new FoodDB(this);
        Button aButton = (Button) findViewById(R.id.addButton);
        foodview = (ListView) findViewById(R.id.fooditems);
        listItem = new ArrayList<>();
        viewData();
        foodview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String text = foodview.getItemAtPosition(i).toString();
                Toast.makeText(add_food_intake.this, "" + text, Toast.LENGTH_SHORT).show();
            }
        });
        Button mShowDialog = (Button) findViewById(R.id.customButton);
        mShowDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                AlertDialog.Builder mBuilder = new AlertDialog.Builder(add_food_intake.this);
                final View mView = getLayoutInflater().inflate(R.layout.custom_food_intake_dialog, null);
                final EditText FoodName = (EditText) mView.findViewById(R.id.food_name);
                final EditText ServingSize = (EditText) mView.findViewById(R.id.serving_size);
                final EditText Fats = (EditText) mView.findViewById(R.id.total_fat);
                final EditText Calories = (EditText) mView.findViewById(R.id.calories);
                final EditText Carbohydrates = (EditText) mView.findViewById(R.id.carbohydrates);
                final EditText Protein = (EditText) mView.findViewById(R.id.protein);
                final RadioButton go1 = (RadioButton) mView.findViewById(R.id.go);
                final RadioButton grow1 = (RadioButton) mView.findViewById(R.id.grow);
                final RadioButton glow1 = (RadioButton) mView.findViewById(R.id.glow);
                final CheckBox breakfast = (CheckBox) mView.findViewById(R.id.breakfast_box);
                final CheckBox lunch = (CheckBox) mView.findViewById(R.id.lunch_box);
                final CheckBox dinner = (CheckBox) mView.findViewById(R.id.dinner_box);
                final Button button = (Button) mView.findViewById(R.id.addfromcustomfood);
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String name = FoodName.getText().toString();
                        String size = ServingSize.getText().toString();
                        String fats = Fats.getText().toString();
                        String calories = Calories.getText().toString();
                        String carbs = Carbohydrates.getText().toString();
                        String protein = Protein.getText().toString();
                        String type = "";
                        ArrayList<String> meal = new ArrayList<>();
                        String add = meal.toString();
                        if (go1.isChecked()) {
                            type = go1.getText().toString();
                        } else if (grow1.isChecked()) {
                            type = grow1.getText().toString();
                        } else if (glow1.isChecked()) {
                            type = glow1.getText().toString();
                        }
                        switch (mView.getId()) {
                            case R.id.breakfast_box:
                                if (breakfast.isChecked()) {
                                    meal.add("Breakfast");
                                } else {
                                    meal.remove("Breakfast");
                                }
                            case R.id.lunch_box:
                                if (lunch.isChecked()) {
                                    meal.add("Lunch");
                                } else {
                                    meal.remove("Lunch");
                                }
                            case R.id.dinner_box:
                                if (dinner.isChecked()) {
                                    meal.add("Dinner");
                                } else {
                                    meal.remove("Dinner");
                                }
                        }
                        if (!name.isEmpty() && !size.isEmpty() && !fats.isEmpty() && !calories.isEmpty() && !protein.isEmpty() && !carbs.isEmpty()
                                && (go1.isChecked() || grow1.isChecked() || glow1.isChecked())) {

                            insertData(type, name, size, fats, calories, carbs, protein, add);
                            Toast.makeText(add_food_intake.this, "Food has ben Added!", Toast.LENGTH_SHORT).show();
                            refreshData();

                        } else {
                            Toast.makeText(add_food_intake.this, "Fail", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

                mBuilder.setView(mView);
                AlertDialog dialog = mBuilder.create();
                dialog.show();
            }
        });


    }

    public void insertData(String type, String name, String size, String fats, String calories, String carbs, String protein, String add) {
        db = helper1.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("type", type);
        contentValues.put("name", name);
        contentValues.put("grams", size);
        contentValues.put("cal", calories);
        contentValues.put("fat", fats);
        contentValues.put("carbohydrates", carbs);
        contentValues.put("protein", protein);
        contentValues.put("meal_type", add);
        long id = db.insert("Food_Items", null, contentValues);
    }

    private void viewData() {
        Cursor cursor = db.rawQuery("SELECT * FROM Food_Items", null);

        if (cursor.getCount() == 0) {
            Toast.makeText(add_food_intake.this, "No data to show", Toast.LENGTH_SHORT).show();
        } else {
            while (cursor.moveToNext()) {
                listItem.add(cursor.getString(cursor.getColumnIndex("name")));
            }
            adapter = new MySimpleArrayAdapter(add_food_intake.this, listItem);
            foodview.setAdapter(adapter);
        }
        cursor.close();

    }

    public void refreshData() {
        listItem.clear();
        viewData();
        foodview.setAdapter(adapter);
    }

    /**
     * This adapter will create your list view row by row
     */
    public class MySimpleArrayAdapter extends ArrayAdapter<String> {

        private final Context context;
        private final ArrayList<String> values;

        public MySimpleArrayAdapter(Context context, ArrayList<String> values) {

            super(context, R.layout.add_food_intake_layout, values);

            this.context = context;
            this.values = values;

        }

        /**
         * Here we go and get our rowlayout.xml file and set the textview text.
         * This happens for every row in your listview.
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View rowView = inflater.inflate(R.layout.add_food_intake_layout, parent, false);

            TextView textView = (TextView) rowView.findViewById(R.id.textView1);
            EditText editText = (EditText) rowView.findViewById(R.id.editText1);

            // Setting the text to display
            textView.setText(values.get(position));

            return rowView;
        }
    }
}

add_food_intake_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:text="Name"
        android:textColor="@color/Black"
        android:textSize="16dp" />

    <RelativeLayout
        android:id="@+id/layout2"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/textView1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:text="Value"
            android:textColor="@color/MainGreen"
            android:textSize="18dp" />
    </RelativeLayout>

    <RelativeLayout
        android:background="@drawable/edittext_box"
        android:id="@+id/layout3"
        android:layout_width="100dp"
        android:layout_height="59dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:layout_marginEnd="20dp"
        android:orientation="vertical">

        <EditText
            android:id="@+id/editText1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_marginStart="0dp"
            android:layout_marginTop="0dp"
            android:inputType="number"
            android:singleLine="true"
            android:textAlignment="center"
            android:textColor="@color/Black"
            android:textSize="18dp" />
    </RelativeLayout>

</RelativeLayout>

1 回答

  • 0

    这是因为在 getView 方法中,每次适配器请求时都会创建一个新视图 . 您应该检查是否可以重新使用已经膨胀的视图 .

    该方法的文件 -

    /**
     * Get a View that displays the data at the specified position in the data set. You can either
     * create a View manually or inflate it from an XML layout file. When the View is inflated, the
     * parent View (GridView, ListView...) will apply default layout parameters unless you use
     * {@link android.view.LayoutInflater#inflate(int, android.view.ViewGroup, boolean)}
     * to specify a root view and to prevent attachment to the root.
     * 
     * @param position The position of the item within the adapter's data set of the item whose view
     *        we want.
     * @param convertView The old view to reuse, if possible. Note: You should check that this view
     *        is non-null and of an appropriate type before using. If it is not possible to convert
     *        this view to display the correct data, this method can create a new view.
     *        Heterogeneous lists can specify their number of view types, so that this View is
     *        always of the right type (see {@link #getViewTypeCount()} and
     *        {@link #getItemViewType(int)}).
     * @param parent The parent that this view will eventually be attached to
     * @return A View corresponding to the data at the specified position.
     */
     View getView(int position, View convertView, ViewGroup parent);
    

    基本上,如果 convertView 为null,则只应对新视图进行膨胀,否则重新使用它 .

    这将解决重置问题 . 但是,现在编辑文本可能会开始复制 . 为此,您必须实现ViewHolder模式并通过在edittexts上添加和删除textwatchers来保存输入的数据 -

    跟着这个 -

    使用ArrayAdapter - https://guides.codepath.com/android/Using-an-ArrayAdapter-with-ListView

    重复的edittexts - Android ListView with EditText values duplicating with TextWatcher

相关问题