Answer the question
In order to leave comments, you need to log in
How to get programmatically generated UI elements using findViewById()?
I have an Activity , which has an embedded LinearLayout , which has one default editText element, but the user can add more editText elements with a button. How is it done? That's how:
private void addNewEditText(){
if(getEditTextId() >= EDIT_TEXT_ID_LIMIT){
//Часть кода пропущу, тут просто Toast который появляется, когда у нас слишком много
//editText элементов
}else {
setEditTextId(getEditTextId()+1);
EditText editText = new EditText(AddWordActivity.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
editText.setLayoutParams(params);
editText.setSingleLine(true);
editText.setId(getEditTextId());
editViewsLayout.addView(editText);
}
}
private void submitAllWords(){
EditText et = (EditText)findViewById(R.id.editText_0);
String word = et.getText().toString();
Log.w("word to add: ", word + " from " + et.getId());
insertNewWord(word, db);
//TODO: Add here parsing words from the generated editTexts
for(int i = 1; i <= EDIT_TEXT_ID_LIMIT; i++){
et = (EditText)findViewById(i);
}
}
Expected resource type idand
Constant and resource type mismatching
Answer the question
In order to leave comments, you need to log in
Firstly, I would advise you not to generate the EditText programmatically, but to implement it from the layout file. This will not solve the c id problem, but it will save you from trash in the code, a headache with changing orientation and bring many other nice goodies)
as for the solution with IdRes, it is good, but in some cases and specifically in this one (when we have a container ) I would be lazy to use it ─ add a dozen more EditTexts, or maybe add two dozen buttons and a couple of pictures mixed together so that it’s not boring ) to figure out where whose id in this case is not difficult, but lazy)
for (int i=0; i < editViewsLayout.getChildCount(); i++){
EditText et = (EditText) editViewsLayout.getChildAt(i);
// делаем что то с et
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question