Отредактированный текст, который будет сохранен в Integer Arraylist

#android #arraylist #android-edittext

#Android #список массивов #android-edittext

Вопрос:

Я пытаюсь получить числовой пользовательский ввод в EditText, и я хочу, чтобы он был сохранен в Integer Arraylist. Здесь у меня есть код, в котором числа программно добавляются в arraylist с именем number. Я также добавил Textviews для отображения всего массива и первого элемента массива, чтобы посмотреть, подходит ли он.

С чем мне нужна помощь, так это с синтаксисом для сохранения пользовательского ввода в EditText в тот же Arraylist. Я искал этот сайт и не нашел ничего подходящего. Я также хотел бы увидеть результат в Textview, чтобы убедиться, что он работает.

 enter code hereI am trying to get numeric user input on an EditText and I want it to be saved to an Integer Arraylist. I have code here that has numbers added programatically to an arraylist called number. I have also added Textviews to display the entire array and the first element of the array to see if it is good.
  

С чем мне нужна помощь, так это с синтаксисом для сохранения пользовательского ввода в EditText в тот же Arraylist.
Я также хотел бы увидеть результат в Textview, чтобы убедиться, что он работает.

 enter code here  @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ArrayList<Integer> number = new ArrayList<Integer>();

    look = (TextView)findViewById(R.id.tv1);
    look2 = (TextView)findViewById(R.id.tv2);

    setUIViews();

    one.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            display1.setText("1");
        }
    });

    two.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            display1.setText("2");
        }
    });

    three.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            display1.setText("3");
        }
    });

    number.add(1);
    number.add(22);
    number.add(45);
    number.add(17);
    number.add(0,7);

    for (int i=0; i < number.size(); i  ){
        look2.setText(look2.getText()  " "   number.get(i)   " , ");
        look.setText("First element is: " number.get(0));
    }

}

private void setUIViews (){

    one = (Button)findViewById(R.id.btn1);
    display1 = (EditText)findViewById(R.id.et1);

    two = (Button)findViewById(R.id.btn2);
    display1 = (EditText)findViewById(R.id.et1);

    three = (Button)findViewById(R.id.btn3);
    display1 = (EditText)findViewById(R.id.et1);


}
  

}
введите код здесь

 enter code here<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<EditText
    android:id="@ id/et1"
    android:layout_width="323dp"
    android:layout_height="58dp"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:ems="10"
    android:inputType="number"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.503"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.017" />

<Button
    android:id="@ id/btn1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="244dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="244dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:inputType="number"
    android:text="1"
    android:visibility="visible"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.522"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.212" />

<Button
    android:id="@ id/btn2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:inputType="number"
    android:text="2"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.212" />

<Button
    android:id="@ id/btn3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:inputType="number"
    android:text="3"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.921"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.212" />

<TextView
    android:id="@ id/tv1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.355" />

<TextView
    android:id="@ id/tv2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.416" />

<Button
    android:id="@ id/btnview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:text="View Arraylist"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.798" />
enter code here
  

Комментарии:

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

2. Как вы хотите, чтобы значение из EditText сохранялось в списке? Есть ли какая-либо кнопка, на которую пользователь должен нажать, чтобы сделать это?

3. Просто нажмите 1, или 2, или 3

Ответ №1:

С чем мне нужна помощь, так это с синтаксисом для сохранения пользовательского ввода в EditText в тот же Arraylist.

Я думаю, вы имеете в виду это:

 number.add(Integer.parseInt(display1.getText().toString()));
  

Комментарии:

1. @N.Macdonald какое сообщение он выдает?

Ответ №2:

Вы можете обработать EditText.AddonTextChangeListner и преобразовать каждый ‘char’ в Int и добавить его в array и удалить в случае удаления, я думаю, это будет эффективно

Комментарии:

1. Было бы неплохо, чтобы цифровые кнопки отправляли соответствующие им числа в массив. Предпочтительно напрямую, если нет, то косвенно. Если onclick не будет добавляться в arraylist, то TextChangeListener может получить символ EditText при нажатии моей кнопки в том виде, в каком он уже установлен.