0

Инициализирую LinearLayout, TextView

linearLayout=new LinearLayout(context);
    textView=new TextView(context);
    textView.setText(text);
    textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, Const.hintSize);
    textView.setTypeface(Assets.font);
    textView.setTextColor(Color.WHITE);
    textView.setMaxWidth(width);
    textView.setMaxHeight(height);
    textView.setMovementMethod(new ScrollingMovementMethod());
    linearLayout.addView(textView);
    linearLayout.measure(width,height);
    linearLayout.layout(0,0,width,height);
    textView.post(new Runnable() {
        @Override
        public void run() {
            lineCount=textView.getLineCount();
            max=Const.hintSize*lineCount;
        }
    });
    Log.d("lineCount",lineCount+"");

В логе

D/lineCount﹕ 0

Обращаемся к документации getLineCount()

Return the number of lines of text, or 0 if the internal Layout has not been built.

Значит, лэйаут не был построен, так как его построить?

9
  • Этот кусок кода взят из onCreate? 10 мар 2016 в 8:03
  • Из конструктора собственного класса ScrollableText
    – kekonyan
    10 мар 2016 в 8:04
  • getLineCount() Вам вернет значение, только когда ваша вью(ScrollableText) уже лежит в разметке 10 мар 2016 в 8:07
  • Что значит "лежит"? Отрисована на канвасе (в моем случае) или что?
    – kekonyan
    10 мар 2016 в 8:16
  • А если так? postDelayed(Runnable, long)?
    – ЮрийСПб
    10 мар 2016 в 8:29

1 ответ 1

1

Подпишитесь на изменение в дереве view (т.е. когда все view перестроятся), в нем получайте lineCount...

textView.getViewTreeObserver().addOnGlobalLayoutListener(
    new ViewTreeObserver.OnGlobalLayoutListener() {
        @SuppressWarnings("deprecation")
        @SuppressLint("NewApi")
        @Override
        public void onGlobalLayout() {
            // Не забываем отписываться, притом сразу
            if (Build.VERSION.SDK_INT >= 16) {
                textView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            } else {
                textView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
            lineCount=textView.getLineCount();
            max=Const.hintSize*lineCount;
            Log.d("lineCount",lineCount+"");
        }
    });

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.