当前位置: 动力学知识库 > 问答 > 编程问答 >

android textview getlayout return null

问题描述:

textview.getLayout() returns null in ListViewAdapter.getView()

I guess I'm calling textview.getLayout() too early, before textview has been displayed.

When should I call textview.getLayout() ?

If I use below code, called getView() c​ontinuously

ViewTreeObserver vto = textview.getViewTreeObserver();

vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

@Override

public void onGlobalLayout() {

Layout layout = textview.getLayout();

textview.setText("something")

}

});

and textview.post(Runnable) returns null too

Layout layout = textview.getLayout();

String splitedText = text.substring(0, layout.getLineEnd(maxLines -1)).trim();

splitedText = splitedText + " ..." + moreStr;

Using layout.getLineEnd produces null pointer exception.

At that stage, the textview is not null, but getLayout() returns null. The textview appears to be initialized.

@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);

网友答案:

As per documentation in Android developers,

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.

So is there a chance for getLayout() to become null in case the width of the text changes?

网友答案:
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);
                    }
                }
            });

it work well.

分享给朋友:
您可能感兴趣的文章:
随机阅读: