【问题标题】:Android XML background sizes adapted for all screen适用于所有屏幕的 Android XML 背景尺寸
【发布时间】:2014-01-03 12:19:33
【问题描述】:

假设你有一个类似这样的Layout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/mylayout" >

 //Other view elements like buttons, TextViews

</RelativeLayout>

然后您可以使用以下代码动态更改layoutbackground

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.mylayout);
        int images[] = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4};

        relativeLayout.setBackgroundResource(images[getRandomNumber()]);
    }


    private int getRandomNumber() {
        //Note that general syntax is Random().nextInt(n)
        //It results in range 0-4
        //So it should be equal to number of images in images[] array
        return new Random().nextInt(4);
    }



}

我如何automatically 使我的背景适应设备的屏幕尺寸?

【问题讨论】:

  • 设置宽度和高度属性匹配父级,它会自动适应

标签: android android-layout android-relativelayout


【解决方案1】:

只需将其添加到您的代码中即可将背景调整为任何屏幕。

relativeLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

【讨论】:

    【解决方案2】:

    由于您已经将 FillParent 用于 Ralative 布局,因此您不需要做任何额外的操作来调整屏幕大小。 您的 drawable 将被拉伸以适应屏幕。

    【讨论】:

    • 嗯,我想用我的 xml 做的是上面有相对布局(图像)和下面的线性布局(按钮),请参阅Image
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2012-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多