动态添加了一个小按钮,但是按钮上的字体却没显示出来,代码如下
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);