简体   繁体   English

Android 如何将edittext中的字符串保存到数组中?

[英]Android How to save a String from edittext into an array?

package com.example.addarray;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    Button button;
    EditText editText;
    int mCounter = 0;
    TextView textView;
    TextView textView2;
    TextView textView3;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.button);
        button.setOnClickListener(view -> {
            mCounter++;
            textView = findViewById(R.id.textView1);
            textView.setText(Integer.toString(mCounter));
            textView2 = findViewById(R.id.textView2);
            editText = findViewById(R.id.editText);

            String [] string = new String[mCounter];
            for(int i =mCounter-1; i>mCounter; i++){
                string[i] = editText.getText().toString();
            }

            textView2.setText(Arrays.toString(string));
        
            textView3 = findViewById(R.id.textView3);
            textView3.setText(editText.getText().toString());
        });
    }
}

I would like to add the input from the edit text into an array upon each click of the button, however, the element of the array only displayed null as shown in the picture.我想在每次单击按钮时将编辑文本中的输入添加到数组中,但是,数组的元素仅显示为 null,如图所示。 Is there any way to fix it?有什么办法可以解决吗? Thank you.谢谢你。

程序的输出

You create a new array with each click.每次单击都会创建一个新数组。 No need to create a new array on every click.无需在每次点击时创建一个新数组。 It is possible to save new values in ArrayList.可以在 ArrayList 中保存新值。

public class MainActivity extends AppCompatActivity {
    private ArrayList<String> list = new ArrayList<String>();
    // *******
    button.setOnClickListener(view -> {
        // *******
        list.add(editText.getText().toString());
        // ******
    }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM