使用Android: 背景png图片

3
我将为您翻译以下内容:

我希望找到一种最佳方法,将.png图像用作应用程序主活动屏幕的背景。我希望它能在尽可能多的设备上适当地显示。

我现有的代码可以运行,但我想知道可移植性的最佳实践是什么。

这是我在XML中使用的代码:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/main_background"
    android:padding="25dp"
    >

...other stuff like a few buttons that go on top of background 

当前文件"main_background.png"是一个800px x 600px的图像。我注意到在我的手机上至少水平尺寸会被缩小,从而扭曲图像。有没有一种理想的宽高比可以使我的背景图片更好?

谢谢。


1
你可以将宽度设置为match_parent,然后使用LayoutParams将高度设置为与宽度相同的值... - Jeeter
谢谢,这正是我在寻找的提示。请随意发布带有XML代码的答案,以便我可以接受 =) - JDS
1个回答

3
您需要做的是按照以下方式设置您的xml:

您需要这样设置您的XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:background="@drawable/main_background"
android:padding="25dp"
>

请注意缺少 layout_height 属性...
在你的主 Activity 中,你会找到该视图,并执行以下代码行:
myLinLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, myLinLayout.getWidth()));

在这里myLinLayout是线性布局,在使用LayoutParams方法时,请遵循以下格式:

setLayoutParams(int width, int height);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接