-1
Hello, I am developing a custom view and would like to know how it would be possible to add an Edittext via Java (without using xml, and without referencing the R class because it would be via java code, if possible). Thanks in advance.
-1
Hello, I am developing a custom view and would like to know how it would be possible to add an Edittext via Java (without using xml, and without referencing the R class because it would be via java code, if possible). Thanks in advance.
2
Good morning, Michael!
You can create Views
programmatically (using Java). For example
EditText etUserName = new EditText(getContext());
How are you creating a View
custom, pass the context to the View
by means of the method getContext()
. If you created your View
in own Activity
, just passing the context itself
EditText etUserName = new EditText(this);
Don’t forget that you will need to create a layout
father and then add his EditText
LinearLayout mLayout = /* Obtenha o layout */;
EditText etUserName = new EditText(context)
etUserName.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
myLayout.addView(etUserName);
Or in the case of a View
personalized, give a extends
in a View
of layout
and create the EditText
as stated above
public class CustomView extends LinearLayout {
public CustomView(Context context, AttributeSet attrs){
super(context, attrs);
setOrientation(LinearLayout.VERTICAL);
setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
EditText etUserName = new EditText(context)
addView(etUserName);
}
}
However, I would advise creating your UI
by way of a declaration xml
, because you will have less work. I hope this helps!
Browser other questions tagged java android
You are not signed in. Login or sign up in order to post.