动态添加的Button不显示字体

论坛 期权论坛 脚本     
匿名技术用户   2020-12-29 18:32   686   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);        
        
        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);


分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP