Getting The Value Of Edittext Which Created Programmatically
In my project ,there is a button which creates Edittex programmatically using foor loop depending on a number that user add,and I don't know how to get the value for each of them.m
Solution 1:
I guess you want to get the values of the dynamically created EditTexts. You currently replace the instance of the EditText which each creation. Try the below code:
List<EditText> editTextList = new ArrayList<>();
private void setChoices() {
layout = (LinearLayout) findViewById(R.id.linearLayout);
params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
int marginPixel = 1;
int marginPixell = 5;
float densityy =getResources().getDisplayMetrics().density;
int marginDp = (int)(marginPixel * densityy);
int margin = (int)(marginPixell * densityy);
params.setMargins(marginDp, margin, marginDp, margin);
int num= Integer.parseInt(choicesNumberEDT.getText().toString());
for (int i = 0; i < num; i++) {
EditText explanationED= new EditText(this);
explanationED.setLayoutParams(params);
editTextList.add(explanationED); //<-------new line here
layout.addView(explanationED);
explanationED.setGravity(Gravity.TOP);
explanationED.setHint("أكتب هنا.....");
explanationED.setTextSize(14);
explanationED.setId(i);
float density = getResources().getDisplayMetrics().density;
int paddingDp = (int) (Const.paddingPixel * density);
explanationED.setBackgroundColor(Color.parseColor("#B2E3CC"));
explanationED.setPadding(paddingDp, paddingDp, paddingDp, paddingDp);
}
}
private EditText getText(int position) {
return editTextList.get(position).getText().toString();
}
OR if you don't want to keep a list of the EditTexts, you can set a tag for each EditText you create using:
editText.setTag("tag");
and later retrieve it using:
layout.findViewWithTag("tag");
Solution 2:
Each time in loop when you create a new object, you are assigning that to the same EditText
object explanationED
. This is why whenever you want to getText()
from explanationED
object you will always get the text of the last EditText
.
For this scenario,
Let's consider a List
of EditText
of length N
, then give id
to each of the list item - EditText
. Now from these ID's
you can get the value of any EditText
object.
//e.g
list.get(i).getText().toString(); //getting value via index
//you may search for a specific Id.
for(EditText text: list) {
if(text.getId() === MY_ID) {
// do something..
}
}
Post a Comment for "Getting The Value Of Edittext Which Created Programmatically"