动态添加的Button不显示字体

本文介绍了解决Android应用中动态添加的小尺寸按钮字体被遮挡的问题。通过调整按钮的填充(padding)为0,成功使字体正常显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


动态添加了一个小按钮,但是按钮上的字体却没显示出来,代码如下

LinearLayout layout;
    	
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        layout = (LinearLayout)findViewById(R.id.myLayout);
        
        LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(20,20);

        Button bt = new Button(this);
        bt.setBackgroundColor(0xffffffff);
        bt.setText("L");
        bt.setTextSize(TypedValue.COMPLEX_UNIT_PX,15);
        bt.setTextColor(0xff000000);        
        
        layout.addView(bt, param);


一模一样的按钮,如果是在布局文件中添加的,则可以显示字体

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/myLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:layout_width="20px"
        android:layout_height="20px"
        android:background="#ffffffff"
        android:textSize="15px"
        android:textColor="#ff000000"
        android:text="L" />

</LinearLayout>

 

 

后来发现好像动态添加的按钮会有默认的padding,所以当Button大小比较小的时候,就把字体给挤掉了,那么加上padding设置为0就可以解决了:

LinearLayout layout;
    	
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        layout = (LinearLayout)findViewById(R.id.myLayout);
        
        LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(20,20);

        Button bt = new Button(this);
        bt.setBackgroundColor(0xffffffff);
        bt.setText("L");
        bt.setTextSize(TypedValue.COMPLEX_UNIT_PX,15);
        bt.setTextColor(0xff000000);
        bt.setPadding(0,0,0,0);        
        
        layout.addView(bt, param);


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值