下一个代码显示三个按钮。您可以增加和减少其中一个按钮的文本大小,称为“主”按钮。主按钮还有一个图像(复合可绘制)
您会注意到文本位置会发生变化(例如:将文本增加到较大的大小,然后将其减小到原始大小)。此外,您可以看到文本大小更改int logcat。 此行为在Android 3.1中重现 Android 2.2中没有重现此行为
为什么会这样?
代码:
public class Acc extends Activity {
/**
* main button
*/
Button b;
/*
* the text size
*/
float textSize;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b = new Button(this); //create main button
b.setText("I'm main button"); //set its text
b.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.icon, 0, 0); //add a drawable
textSize=14;//assign initial textsize
b.setTextSize(textSize); //set it to the button's text size
b.setHeight(200);
LinearLayout layout = (LinearLayout) findViewById(R.id.main); //get the activity layout
layout.addView(b); //add the main button to the layout
addZoomInOutButtons(layout); //add two buttons to increase and decrease the main button's height and text size
Log.v("my log","FIRST TIME: text size:"+textSize);
}
/**
* Create two buttons, to increase and decrease with and text size of main button
* @param layout
*/
private void addZoomInOutButtons(LinearLayout layout){
Button bzi = new Button(this);
bzi.setText("zoom in");
Button bzo = new Button(this);
bzo.setText("zoom out");
layout.addView(bzi);
layout.addView(bzo);
bzi.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
textSize+=10;
b.setTextSize(textSize);
Log.v("my log","text size:"+textSize);
}
});
bzo.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
textSize-=10;
b.setTextSize(textSize);
Log.v("my log","text size:"+textSize);
}
});
}
}
也是清单:
<?xml version="1.0" encoding="utf-8"?>
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Acc"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="3" android:targetSdkVersion="8"/>