嗨,我一直在努力解决这个问题,但我不能。我有这个按钮
<Button android:layout_alignLeft="@+id/button1" android:layout_below="@+id/button2"
android:id="@+id/button3"
android:layout_width="235dp"
android:text="@string/spire"
android:layout_gravity="center_horizontal"
android:layout_height="wrap_content"
>
当这个按钮出现在较小的屏幕上时,我怎样才能使按钮也缩小自己的尺寸?谢谢!
编辑:好的,这就是新代码。但我不确定如何使编辑功能工作?我有进口的东西吗?import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.view.View;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.Button;
public void getDisplay(){
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
switch(metrics.densityDpi){
case DisplayMetrics.DENSITY_LOW:
edit.putInt("SIZE", 12).commit();
edit.putInt("POSITION", -8).commit();
break;
case DisplayMetrics.DENSITY_MEDIUM:
edit.putInt("SIZE", 16).commit();
edit.putInt("POSITION", -6).commit();
break;
case DisplayMetrics.DENSITY_HIGH:
edit.putInt("SIZE", 25).commit();
edit.putInt("POSITION", 8).commit();
break;
case DisplayMetrics.DENSITY_XHIGH:
//edit.putInt("SIZE",35).commit();
//edit.putInt("POSITION",30);
break;
}
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
goHereButton = (Button) findViewById(R.id.button1);
goHereButton.setWidth(20);
goHereButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
Intent i = new Intent(UMassGuide.this, DirectionsScreenActivity.class);
startActivity(i);
}
});
另外我该怎么做xml文件?我删除宽度?
答案 0 :(得分:2)
因为你要设置一个宽度,你必须做这样的事情
public void getDisplay(){
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
switch(metrics.densityDpi){
case DisplayMetrics.DENSITY_LOW:
edit.putInt("SIZE", 12).commit();
edit.putInt("POSITION", -8).commit();
break;
case DisplayMetrics.DENSITY_MEDIUM:
edit.putInt("SIZE", 16).commit();
edit.putInt("POSITION", -6).commit();
break;
case DisplayMetrics.DENSITY_HIGH:
edit.putInt("SIZE", 25).commit();
edit.putInt("POSITION", 8).commit();
break;
case DisplayMetrics.DENSITY_XHIGH:
//edit.putInt("SIZE",35).commit();
//edit.putInt("POSITION",30);
break;
}
}
根据屏幕显示创建宽度尺寸
然后在创建按钮时使用
Button button = (Button)findViewById(R.id.your_button_id);
button.setWidth(pixels)
setWidth
以像素为单位设置宽度,因此您可能需要对大小进行一些处理,以便在不同的屏幕尺寸上获得所需的内容
答案 1 :(得分:0)
除@tyczj答案外,您可以致电:
Button button = (Button)findViewById(R.id.your_button_id);
button.setLayoutParams(new LayoutParams(pixels, LayoutParams.WRAP_CONTENT));