【问题标题】:Button text cut off when added dynamically动态添加时按钮文本被截断
【发布时间】:2019-05-07 14:24:37
【问题描述】:

前 5 个按钮以编程方式添加,最后一个按钮通过 XML 添加。两种方式我都使用相同的参数。为什么动态添加的按钮文本会被截断?

程序化:

Button b = new Button(getActivity());
b.setText(text);
b.setAllCaps(false);
b.setBackgroundResource(R.drawable.button_tag_rect);
b.setTextColor(getResources().getColor(R.color.colorWhiteText));

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.WRAP_CONTENT,
        dpToPx(28));

int marginInPx = dpToPx(2);
params.setMargins(marginInPx, marginInPx, marginInPx, marginInPx);

tagCloudTwitter.addView(b, tagCloudTwitter.getChildCount()-1, params);

XML:

<Button
android:layout_width="wrap_content"
android:layout_height="28dp"
android:layout_margin="2dp"
android:textAllCaps="false"
android:background="@drawable/button_tag_rect"
android:textColor="@color/colorWhiteText"
android:text="test"/>

编辑:解决了!请参阅下面的答案。

【问题讨论】:

  • 我认为是因为高度太短了。试着让它更高,看看。
  • 确实如此,但是为什么XML的按钮没有截断文本,它是相同的高度(28dp)?我想我错过了一些标志。我尝试将重力设置为中心,但没有帮助。
  • 也许问题出在setMargins
  • 试试这个,去掉这一行 -- params.setMargins(marginInPx, marginInPx, marginInPx, marginInPx);

标签: android android-layout android-button


【解决方案1】:

有趣的是,设置“虚拟”填充有帮助:

b.setPadding(1,1,1,1);

¯\_(ツ)_/¯

【讨论】:

    【解决方案2】:

    尝试设置按钮的高度和宽度;

     b.setWidth(10);
        b.setHeight(100);
    

    【讨论】:

    • 尝试设置宽度和高度 - 没有帮助。
    • 感谢您的帮助。我已经设法解决了这个问题;请参阅下面的答案。
    猜你喜欢
    • 1970-01-01
    • 2012-07-25
    • 2012-11-09
    • 2012-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-26
    • 1970-01-01
    相关资源
    最近更新 更多