How to set maxLines and ellipsize of a TextView at the same time

前端 未结 7 1668
挽巷
挽巷 2021-01-30 12:54

I want to limit my text view to have maximum of 5 lines, so I did:



        
7条回答
  •  说谎
    说谎 (楼主)
    2021-01-30 13:04

    try this code...

        final TextView tv_yourtext = (TextView)findViewById(R.id.text);
    
        tv_yourtext.setText("A really long text");
        ViewTreeObserver vto = tv_yourtext.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    
            @Override
            public void onGlobalLayout() {
                ViewTreeObserver obs = tv_yourtext.getViewTreeObserver();
                obs.removeGlobalOnLayoutListener(this);
                if(tv_yourtext.getLineCount() > 6){
                    Log.d("","Line["+tv_yourtext.getLineCount()+"]"+tv_yourtext.getText());
                    int lineEndIndex = tv_yourtext.getLayout().getLineEnd(5);
                    String text = tv_yourtext.getText().subSequence(0, lineEndIndex-3)+"...";
                    tv_yourtext.setText(text);
                    Log.d("","NewText:"+text);
                }
    
            }
        });
    

提交回复
热议问题