textview.getLayout()
在null
ListViewAdapter.getView()
我想我在显示textview.getLayout()
之前过早地呼叫textview
。
我应该何时致电textview.getLayout()
?
如果我使用下面的代码,名为getView()
c ontinuously
ViewTreeObserver vto = textview.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Layout layout = textview.getLayout();
textview.setText("something")
}
});
和textview.post(Runnable)
也会返回null
Layout layout = textview.getLayout();
String splitedText = text.substring(0, layout.getLineEnd(maxLines -1)).trim();
splitedText = splitedText + " ..." + moreStr;
使用layout.getLineEnd
会产生空指针异常。
在该阶段,textview不为null,但getLayout()返回null。 textview似乎已初始化。
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final Context context = parent.getContext();
ViewHolder holder = new ViewHolder();
if(convertView == null)
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
.....
holder.timeLineContents = (TextView) convertView.findViewById(R.id.item_time_line_contents);
答案 0 :(得分:1)
根据Android开发人员的文档,
public final Layout getLayout ()
Returns
the Layout that is currently being used to display the text.
This can be null if the text or width has recently changes.
如果文字的宽度发生变化,getLayout()
是否有机会成为null
?
答案 1 :(得分:0)
holder.timeLineContents.setOnLayoutListener(new OnLayoutListener() {
@Override
public void onLayoutChanged(SpanTextView view) {
SpannableString mLinkableText = null;
InternalMoreSpan span = new InternalMoreSpan(mContext);
if(view.getLineCount() >= 2) {
Layout layout = view.getLayout();
String splitedText = view.getText().toString().substring(0, layout.getLineEnd(2 - 1) - 6).trim();
splitedText = splitedText + moreStr;
mLinkableText = new SpannableString(splitedText);
mLinkableText.setSpan(span, mLinkableText.length()- moreStr.length(), mLinkableText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
view.setText(mLinkableText);
}
}
});
效果很好。
答案 2 :(得分:0)
在TextView.onPreDraw()
getLayout();
它在TextView中生成mLayout;
答案 3 :(得分:0)
在onStart或onResume之后调用它
if(textView.onPreDraw())
textLayout = textView.getLayout();