3

I want to create textview programmatically and display horizontally if it fits on device screen else display in next row.

I have the screen's available width and some text. Based on that text I want to create textview and display it. I also have additional text which i want to display in first row if it fits there. Otherwise, it should go on the next row. The only problem is that I am not able to get the width of textview based on its text. I can't use wrap_content as it will not give me its width value.

NightShadeQueen
  • 3,284
  • 3
  • 24
  • 37
  • 1
    Take a look at [layout params](http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html) – Udit Mukherjee Aug 29 '15 at 13:39
  • as i told if i use wrap_content as layout params. it will not let me get exact width in numbers to apply my logic to check whether width is less then available screen width. – Chintan Kavathia Aug 29 '15 at 16:41
  • Using the native Paint.measureText() you can get the rendered size (or close to it) and then using that width, decide whether to append the text to the first row or not, detailed answers @ http://stackoverflow.com/questions/7549182/android-paint-measuretext-vs-gettextbounds – SushiHangover Aug 29 '15 at 21:13

1 Answers1

0

In the activity that includes your textview, implement this interface;

global::Android.Views.ViewTreeObserver.IOnGlobalLayoutListener

This will make you implement OnGlobalLayout method.

You will also need to add;

rootLayout = FindViewById<RelativeLayout>(Resource.Id.rootLayout);
rootLayout.ViewTreeObserver.AddOnGlobalLayoutListener(this);

Root layout here can be your root layout that includes your text views.

On the method you implemented,

public void OnGlobalLayout()
    {
        if (textView != null)
        {
            int height = textView .Height;
        }
    }

if you call textView.Height or textView.Width, it will return the true width and height of your textview after the view is created, instead of the wrap content -1 value.

Can Canbek
  • 334
  • 3
  • 16