Donovan Tan
Donovan Tan

Reputation: 326

Android: Display same text output to multiple EditText

Let's say I have a single text output, for example "This is an EditText"(textToUse).

I want to display this same text output into not 1, but multiple EditText fields.

If I have 3 EditText ids: edit1, edit2 and edit3

Instead of using just:

private EditText mEditText;
private String textToUse;

mEditText = (EditText)findViewById(R.id.edit1);
mEditText.setText(textToUse);

which will only display the text output to EditText "edit1", how can I change the codes to make it display on "edit2" and "edit3" as well?

I have tried:

mEditText = (EditText)findViewById(R.id.edit1);
mEditText = (EditText)findViewById(R.id.edit2);
mEditText = (EditText)findViewById(R.id.edit3);

and

mEditText = (EditText)findViewById(R.id.edit1, R.id.edit2, R.id.edit3);

and

mEditText = (EditText)findViewById(R.id.edit1, edit2, edit3);

but none of them works. I apologise if this is a stupid question, I have just started Android Development. Thanks~

Upvotes: 1

Views: 332

Answers (2)

Huy
Huy

Reputation: 3363

If you have many of EditText, you can try to create an array of EditText, ID array of every EditText.

ex:

EditText []et;
int []idEt = {R.id.et1, R.id.et2, R.id.et3.....};

Then use a loop statement to do anything.. ex:

for(int i=0; i<numberOfEditText; i++){
   et[i] = (EditText)findViewById(idEt[i]);
}

....

for(int i=0; i<numberOfEditText; i++){
   et[i].setText("abcdefghi");
}

You can save many lines of code. Hope this help!

Upvotes: 1

FrozenFire
FrozenFire

Reputation: 670

You need to declare three different EditText on your code, non-array object can hold only one(1) values. So:

mEditText = (EditText)findViewById(R.id.edit1);
mEditText = (EditText)findViewById(R.id.edit2);
mEditText = (EditText)findViewById(R.id.edit3);

will simply overrides its values. (In above code mEditText only holds the R.id.edit3)

Try

mEditText1 = (EditText)findViewById(R.id.edit1);
mEditText2 = (EditText)findViewById(R.id.edit2);
mEditText3 = (EditText)findViewById(R.id.edit3);
mEditText1.setText(textToUse);
mEditText2.setText(textToUse);
mEditText3.setText(textToUse);

Or use an array for your EditText as @Huy Nguyen did in his answer.

Upvotes: 1

Related Questions