如何根据TextView的大小在运行时设置文本?

时间:2018-08-01 13:56:13

标签: android text textview android-framelayout

我有一个FrameLayout,里面装有TextView(实际上是芯片)。

我的文本选项很少,我想选择适合该视图的最长文本选项。

我想这样做

    public class AccountMenuBodyView<T> extends FrameLayout {


      private final android.support.design.chip.Chip myAccountView;


      public AccountMenuBodyView(Context context) {
        this(context, null);
      }

      public AccountMenuBodyView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    ...
      }

      public void initialize(
          @NonNull AccountMenuManager<T> accountMenuManager,
          @Nullable AccountSelectedListener<T> accountSelectedListener,
          OneGoogleMobileEvent loggingContext) {
       ..
 }
      }


      @Override
      protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
      }


      @Override
      protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
...
      }

      private void setChipTextWithCorrectLength() {
        // myAccountView.setText(R.string.og_my_account_desc_long_length);
        myAccountView.setText("long long long long long long long long long long long long long long long long");

        Toast.makeText(getContext().getApplicationContext(), "myAccountView.getTextSize() = "+myAccountView.getTextSize()+" myAccountView.getWidth()= "+myAccountView.getWidth(),
            Toast.LENGTH_SHORT).show();

        if (myAccountView.getTextSize() > myAccountView.getWidth()) {
          myAccountView.setText(R.string.og_my_account_desc_meduim_length);

          Toast.makeText(getContext().getApplicationContext(), "myAccountView.getTextSize() = "+myAccountView.getTextSize()+" myAccountView.getWidth()= "+myAccountView.getWidth(),
              Toast.LENGTH_SHORT).show();


          if (myAccountView.getTextSize() > myAccountView.getWidth()) {
            //
            // Toast.makeText(getContext().getApplicationContext(), "myAccountView.getTextSize() = "+myAccountView.getTextSize()+" myAccountView.getWidth()= "+myAccountView.getWidth(),
            //     Toast.LENGTH_SHORT).show();
            myAccountView.setText(R.string.og_my_account_desc_short_length);
          }
        }
      }

但是我不确定onMesure()方法可能为时已晚。

在测量完成后,我是否希望视图绘制新文本?

0 个答案:

没有答案