How to use textview.getLayout()? It returns null

匿名 (未验证) 提交于 2019-12-03 02:31:01

问题:

I’m trying set a layout for textview so I can use getEllipsisCount() method. But below code returns null as layout value. How can I take layout and then use getEllipsisCount(0) method.

    public class MainActivity extends Activity {   @Override public void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.activity_main);     TextView mytextview =(TextView) findViewById(R.id.textView1);     mytextview.setText(myText);          Layout layout = mytextview.getLayout();         if(layout != null){             mytextview.settext("very good layout worked\n");         }  }

回答1:

You are calling it too early, thats why it is returning null

Try this

  ViewTreeObserver vto = mytextview.getViewTreeObserver();     vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {         @Override         public void onGlobalLayout() {            Layout layout = mytextview.getLayout();           }     });


回答2:

From the documentation:

public final Layout getLayout ()

Added in API level 1 Returns the Layout that is currently being used to display the text. This can be null if the text or width has recently changes.

So probably your text has changes or you call it too early.

Look at this answer where is stated

This only works after the layout phase, otherwise the returned layout will be null, so call this at an appropriate place in your code.



回答3:

Call

TextView.onPreDraw();

It creates the layout.



回答4:

Call mytextview.getLayout() in onStart or onResume callback.



回答5:

First, I do not know if it is a typo or it is intentional but you have declared a "settext" method instead of the predefined setText. However to get a reference of your layout I suggest you the following:

LayoutInflater inflater = getLayoutInflater();  RelativeLayout textViewLayout = (RelativeLayout) inflater.inflate(R.layout.activity_main,null);  if (textViewLayout != null) {     mytextview.setText("very good layout worked\n"); }

supposing that your TextView belongs to a RelativeLayout.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!