Reputation: 2563
My code is as follow. I just don't wanna set an id to my EditText and findViewById. Because I'm building dynamic ui. So static id is useless for me. I'm now trying to get the EditText from the linearLayout but it didn't work yet. Any idea ?
LinearLayout linearLayout = new LinearLayout(this);
LayoutParams cbLayoutParams = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
locationLayout.setLayoutParams(cbLayoutParams);
locationLayout.setOrientation(LinearLayout.VERTICAL);
EditText edtText = new EditText(this);
edtText.setEnable(false);
edtText.setLayoutParams(new LayoutParams(150,50));
linearLayout.addView(edtText);
Button button = new Button(this);
button.setText("say hello");
button.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
EditText edt = null;
for(int i=0; i<linearLayout.getChildCount();i++){
Class<?> c = (Class<?>) linearLayout.getChildAt(i).getClass();
if(c.getName().equals("android.widget.EditText")){
edt = (EditText) linearLayout.getChildAt(i);
}
}
edt.setText("hello");
}
});
Upvotes: 0
Views: 31
Reputation: 10715
You need to make your EditText
final.
final EditText edtText = new EditText(this);
And then you can use your final edtText
reference inside button's onClick
:
LinearLayout linearLayout = new LinearLayout(this);
LayoutParams cbLayoutParams = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
locationLayout.setLayoutParams(cbLayoutParams);
locationLayout.setOrientation(LinearLayout.VERTICAL);
final EditText edtText = new EditText(this);
edtText.setEnabled(false);
edtText.setLayoutParams(new LayoutParams(150,50));
linearLayout.addView(edtText);
Button button = new Button(this);
button.setText("say hello");
button.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
edtText.setText("hello");
}
});
Upvotes: 1