可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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
.