Dynamically added TextView has zero width and height
I have a programatically created RelativeLayout as shown in code below. The RelativeLayout has same width and height of an EditText and lies above the EditText. I add a programatically created TextView to it with certain width and height.
overlay = new RelativeLayout(context);
overlay.setBackgroundColor(Color.TRANSPARENT); //NO I18N
viewGroup.addView(overlay);
overlay.bringToFront();
RelativeLayout.LayoutParams lp = ((RelativeLayout.LayoutParams) overlay.getLayoutParams());
lp.width = getMeasuredWidth();
lp.height = getMeasuredHeight();
Log.d(TAG, "initOverlay: width " + lp.width + " height " + lp.height);
lp.addRule(RelativeLayout.ALIGN_BOTTOM, R.id.formulaView);
lp.addRule(RelativeLayout.RIGHT_OF, R.id.fxImg);
lp.setMargins(0, ((int) Util.dptopx(context, 1) + getTotalPaddingTop()), 0, ((int) Util.dptopx(context, 1) + getTotalPaddingBottom()));
overlay.setLayoutParams(lp);
setOverScrollMode(OVER_SCROLL_NEVER);
overlay.setOverScrollMode(OVER_SCROLL_NEVER);
overlay.requestLayout();
The first time when the TextView is added, the views are shown with specified width and height. But when i remove the TextView from RelativeLayout and add a new TextView again, the TextView is not being shown. It has zero width and height though i'm setting a width and height. What could possibly be the problem?
TextView
textview = new CustomTextView(edittext.getContext());
Editable editable = edittext.getEditableText();
String spantext = editable.subSequence(startidx, endidx).toString();
float[] location = Util.determineTextViewLocation(startidx, endidx);
textview.setText(spantext);
textview.setTextSize(TypedValue.COMPLEX_UNIT_PX, edittext.getTextSize());
textview.setX(location[0]);
textview.setY(location[1]);
textview.setLayoutParams(new ViewGroup.LayoutParams((int) location[2], (int) location[3]));
textview.setPadding(0, ((int) location[4]), 0, 0);
overlay.addView(textview);
Log.d(TAG, "width "+textview.getWidth()+" height "+textview.getHeight()+" view"+textview);
Edit: The TextView's onMeasure() method is never getting called.
Try below code :
XTextView textView= new XTextView(this);
textView.setLayoutParams(new RelativeLayout.LayoutParams(100,500));
textview.setText("Sample");
textview.setX(location[0]);
textview.setY(location[1]);
textview.setLayoutParams(lp);
overlay.addView(textview);
textview.requestLayout();
Also for overlay don't use getLayoutParams() method. Use
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
I had the same problem. What fixed it for me was to add the textview to its parent first, then post a runnable to the text view with
textView.post(new Runnable() { ... })
and then set the layout params within that runnable
I know this question is super old but just in case anyone else runs into this problem :)
链接地址: http://www.djcxy.com/p/14840.html上一篇: 选择Linux I / O调度程序