Why is setWidth/Height not working on EditText? - android

In the code below setting width and height directly on nameEdit does not work, I have to use setLayoutParams. Why does not setWidth/Height work? This led to a lot of frustration for me before I found the solution.
EditText nameEdit = new EditText( theActivity );
nameEdit.setX(300);
nameEdit.setY(400);
// nameEdit.getLayoutParams().width = 100;
// nameEdit.getLayoutParams().height = 60;
//final EditText edittext = new EditText(this);
nameEdit.setLayoutParams(lparams);
//return edittext;
// nameEdit.setWidth(100);
// nameEdit.setHeight(60);
nameEdit.setBackgroundColor(Color.RED);
((ViewGroup) (theActivity).findViewById( android.R.id.content )).addView( nameEdit );

Why setHeight or setWidth did not work?
setHeight or setWidth has more to do with the line height of the text than the height of the view.
Why setLayoutParams works?
When we set the layout params of the editText, we are telling the parent layout rendering the editText, to set the specified height and width for the view. Therefore, it works fine.
Anyone please feel free to add more details or update my understanding ...
Thanks

Related

Android TextView: can I stop text that is partially displayed from appearing

In my app I display several text views containing text of various length that is loaded in at run time. I do not know the dimensions of the text view or the length of the text until run time. Sometimes, when the text is long and the textview small some of the text is partially visible, for example:
I want to remove the partially visible text as it looks a bit naff, but I can't find a way to do this. Any help would be appreciated!
Thanks,
Dave
You can hard code the TextView height in a way that the second row of text will not be visible.
Or use:
android:maxLines , Makes the TextView be at most this many lines tall.
as suggested above.
Put your textviews in a scrollview layout.And specify a specific width to your textview and make the height wrap content.So that your text doesn't get cut.
This is how I did it. I ran this code after the activity had loaded by posting the method CheckTextIsVisible to the parent relativelayout's handler queue, otherwise the height of the textviews will not be known:
m_eventsLayout.Post(new Action(CheckTextIsVisible));
Then the method CheckTextIsVisible finds each textview with text in it, calculates the height of the font, works out how many lines can fit in the textview, and sets the number of maximum lines accordingly:
private void CheckTextIsVisible()
{
View view;
TextView tView;
Android.Text.TextPaint tPaint;
float height;
int heightOfTextView;
int noLinesInTextView;
for (int i = 0; i < m_eventsLayout.ChildCount; i++)
{
view = m_eventsLayout.GetChildAt(i);
if (view is TextView)
{
tView = (TextView)view;
if (tView.Text != "")
{
//calculate font height
tPaint = tView.Paint;
height = CalculateTextHeight(tPaint.GetFontMetrics());
//calculate the no of lines that will fit in the text box based on this height
heightOfTextView = tView.Height;
noLinesInTextView = (int)(heightOfTextView / height);
//set max lines to this
tView.SetMaxLines(noLinesInTextView);
}
}
}
}
private float CalculateTextHeight(Android.Graphics.Paint.FontMetrics fm)
{
return fm.Bottom - fm.Top;
}
This results in no partially visible text!

Error with setWidth in android

My problem is that i want change width of my TEXTVIEW (INPUT TEXT).
In emulator that code work success but when i try to work with my app in mobile that crash it.
My answer is: Why my app crash when i try to change .setWidth? and how can i solve my problem?
A lot of thanks.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.binomial);
EditText TextVA, TextVB, TextVC, EtiquetaA, EtiquetaB, EtiquetaC;
TextVA = (EditText)findViewById(R.id.editTextP);
TextVB = (EditText)findViewById(R.id.editTextK);
TextVC = (EditText)findViewById(R.id.editText3);
ArrayList<TextView> listaTexto = new ArrayList<TextView>();
listaTexto.add(TextVA);
listaTexto.add(TextVB);
listaTexto.add(TextVC);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int y = size.y;
int x = size.x;
ResolucionPantalla respant = new ResolucionPantalla(y, x);
for (int i=0;i<listaTexto.size();i++)
//ResolInput METHOD return size in px according to the screen size
listaTexto.get(i).setWidth(respant.ResolInput());
Button BotonCalcular = (Button)findViewById(R.id.buttonCalcular);
BotonCalcular.setOnClickListener(this);
}
EDIT: TextView to EditText
I see several potential issues...
For starters:
TextVA = (TextView)findViewById(R.id.editTextP);
Is R.id.editTextP an EditText? You are casting it as a TextView
And also:
Calling setWidth here will have no effect. There is an onLayout method for each view that gets called after onCreate is finished. The width/height get set to whatever is specified in your XML layout during that call
You can either extend and create your own EditText and override the onLayout method, or you can figure out how to size your views correctly via XML.

How to align image in android

I am dynamically adding controls in my activity. simultaneously i'm adding a editbox and button, but facing some issue in image alignment.
Here is my code which ads the editText and Button and returns to the linear layout which is vertical in alignment.
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(0);
final EditText textView = new EditText(this);
textView.setLayoutParams(lparams);
textView.setSingleLine(true);
final LayoutParams lparams1 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final Button button = new Button(this);
textView.setLayoutParams(lparams1);
if(id == R.id.new_alternate_number_button)
{
if(contactNumber == "")
{
textView.setHint("Enter contact Number");
}
else
{
textView.setText(contactNumber);
}
textView.setInputType(InputType.TYPE_CLASS_PHONE); //to popup numpad
}
else
{
if(contactEmailID == "")
{
textView.setHint("Enter Email ID ");
}
else
{
textView.setText(contactEmailID);
}
}
button.setBackgroundResource(R.drawable.ic_delete);
button.setBackgroundResource(R.drawable.ic_delete);
button.setOnClickListener(deleteView);
layout.addView(textView);
layout.addView(button);
textView.post(new Runnable() {
public void run() {
textView.requestFocus();
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(textView, InputMethodManager.SHOW_IMPLICIT);
}
});
return layout;
In my XML file i have declared linear layout which is vertical in alignment i.e icon should be at the end of screen and EditText should be left aligned.. also i need a space between EditText and image..
Thanks in advance
Your LayoutParams is set to WRAP_CONTENT for Width instead of FILL_PARENT (or MATCH_PARENT).
A "pattern" that I use in similar cases is that even though I'm dynamically adding a new row/section, I still keep they layout in an xml file for that row, and then I dynamically inflate and find the elements by id, and bind to them. Sort of like how we deal with List Items except in this case, you are not using a list.
By keeping the layout in the XML file, it'll be easier to prototype what you want to see, add padding etc. And you can even use a RelativeLayout if you can't get the LinearLayout to work. Again, you can do all of this in code, but doing layout in the XML offers more flexibility (and is simpler to deal with in my mind)
This how you can go about adding space between the Button and EditText:
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(50, 0, 0, 0); // Adding margin to the left of your button
Button yourButton = new Button(this);
yourButton.setText("some text");
linearLayout.addView(yourButton, layoutParams);
The sequence of parameters in setMargins method:
android:layout_marginLeft
android:layout_marginTop
android:layout_marginRight
android:layout_marginBottom
Know more about setMargins method here.
Now that I realize your requirements properly (at least I guess so) I have another answer for you. Keep me updated about how it helps.
You will have to specify weight for the elements. Let's say total weightSum of your layout is 8, then if you specify weight of the EditText as 7, it will take 7/8th of the total space. And set wight of the Button as 1, so it will take 1/8th of the space. I am using 8 just as an example, you can change it to any number you want, do some trial and error see what weights are suiting your needs the best.
Also, the weights are in float, so don't forget the "f" after the number, like 1f and 7f:
(Again, I am not near my dev machine so there may be some errors. But this should work.)
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 7f);
// Last parameter 6f defines weight. So yourEditText will take 7/8th of the space
linearLayout.addView(yourEditText, layoutParams);
layoutParams = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f);
// Last parameter 6f defines weight. So yourEditText will take 1/8th of the space
linearLayout.addView(yourButton, layoutParams);
Let's see how this helps. :)

When is the width of an Android View set?

I have a little issue on what sequence things are being called when adding stuff to a RelativeLayout. I have a class extending Activity (name it RelActivity) where I want to create a RelativeLayout and put several custom Views (name it cusView) into that RelativeLayout. The topMargin and leftMargin of a custom View is calculated by using the position of another custom View (i.e. the first custom View has to be positioned directly by setting a number to topMargin and leftMargin). Please note that the Rules of RelativeLayout is not sufficient in this case.
So, over to the problem. In my RelActivity I do this:
Create a RelativeLayout (name it relLayout)
Iterate a cursor with cusViews recieved from a database
For the first cusView -> Set position by topMargin and leftMargin using a LayoutParameter
For the other cusViews -> calculate their topMargin and leftMargin by using one of the other cusViews and a LayoutParameter
Set RelActivity's contentView to relLayout
What happens is that all cusViews but the first one are squeezed in the top left corner because both leftMargin and topMargin are always calculated to be zero. This happens because I use the width of the cusViews to calculate the topMargin and leftMargin, and the width of the cusView has not given a value yet.
Is the width first calculated in the cusView's overrided method onSizeChanged()? Is the onSizeChanged() method get called first when the layout is presented on the screen? If so, how do I work around this issue? Do I have to calculate the positionings after onSizeChanged() is done?
Edit: Here is a minimum working example:
Here is my onCreate in RelActivity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
relLayout = new RelativeLayout(this);
cusViews = new ArrayList<CusView>();
listParams = new ArrayList<RelativeLayout.LayoutParams>();
readDBandSetLayout();
setContentView(relLayout);
}
There is too much information in the readDBandSetLayout() method to present it all here. below are the most important details. If I create the LayoutParams in the following way it works fine, the cusViews are listed downwards and rightwards of eachother:
queryCursor = customApplication.customData.query( number); //Fetches cursor
for ( int i = 0; i < numberOfRows; i++ ){
if ( i == 0 ){
LayoutParams p = new LayoutParams(this.getResources().getDimensionPixelSize(R.dimen.small), this.getResources().getDimensionPixelSize(R.dimen.small));
p.topMargin = 50;
p.leftMargin = 50;
listParams.add(p);
}
else{
LayoutParams p = new LayoutParams(this.getResources().getDimensionPixelSize(R.dimen.large),this.getResources().getDimensionPixelSize(R.dimen.large));
p.addRule(RelativeLayout.BELOW, cusViews.get(i-1).getId());
p.addRule(RelativeLayout.RIGHT_OF, cusViews.get(i-1).getId());
listParams.add(p);
}
relLayout.addView(cusViews.get(i), listParams.get(i));
}
However, what I want to do in the else statement is something like:
else{
LayoutParams p = new LayoutParams(this.getResources().getDimensionPixelSize(R.dimen.large),this.getResources().getDimensionPixelSize(R.dimen.large));
//Here I want to calculate cusView2Topmargin and cusView2Leftmargin based on the widths of the first or previosly positioned cusViews. But here the widths are 0 since they haven't been calculated yet.
p.topMargin = cusView2Topmargin; //Always zero
p.leftMargin = cusView2Leftmargin; //Always zero
listParams.add(p);
}
So the problem lies in that the widths of the cusViews are zero at the point I need them to calculate the layout parameters topMargin and leftMargin.
Unfortunately I cannot use the RelativeLayout's Rules for what I want to achieve. If there were some way to create rules like RelativeLayout.RIGHT_OF and RelativeLayout.BELOW I could do it like that. Is this possible?
Its not very clear what your goal is for this layout. It might well be possible to use a simple LinearLayout to get what you want.
If you want to size these from a database lookup then try simply adding each of the views, using addView() first, storing a reference to each, then go back and sett the margins to place them in the proper positions.

Setting width to wrap_content for TextView through code

Can anyone help me how to set the width of TextView to wrap_content through code and not from XML?
I am dynamically creating a TextView in code ,so is there anyway to how to set its width to wrap_content through code?
TextView pf = new TextView(context);
pf.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
For different layouts like ConstraintLayout and others, they have their own LayoutParams, like so:
pf.setLayoutParams(new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
or
parentView.addView(pf, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
There is another way to achieve same result. In case you need to set only one parameter, for example 'height':
TextView textView = (TextView)findViewById(R.id.text_view);
ViewGroup.LayoutParams params = textView.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
textView.setLayoutParams(params);
Solution for change TextView width to wrap content.
textView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
textView.requestLayout();
// Call requestLayout() for redraw your TextView when your TextView is already drawn (laid out) (eg: you update TextView width when click a Button).
// If your TextView is drawing you may not need requestLayout() (eg: you change TextView width inside onCreate()). However if you call it, it still working well => for easy: always use requestLayout()
// Another useful example
// textView.getLayoutParams().width = 200; // For change `TextView` width to 200 pixel
A little update on this post: if you are using ktx within your Android project, there is a little helper method that makes updating LayoutParams a lot easier.
If you want to update e.g. only the width you can do that with the following line in Kotlin.
tv.updateLayoutParams { width = WRAP_CONTENT }
I am posting android Java base multi line edittext.
EditText editText = findViewById(R.id.editText);/* edittext access */
ViewGroup.LayoutParams params = editText.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
editText.setLayoutParams(params); /* Gives as much height for multi line*/
editText.setSingleLine(false); /* Makes it Multi line */
I think this code answer your question
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)
holder.desc1.getLayoutParams();
params.height = RelativeLayout.LayoutParams.WRAP_CONTENT;
holder.desc1.setLayoutParams(params);

Categories

Resources