Android TabHost/TabWidget-缩放背景图像?

Android TabHost/TabWidget-缩放背景图像?,android,background,scale,android-tabhost,tabwidget,Android,Background,Scale,Android Tabhost,Tabwidget,我需要缩放TabWidget背景图像,以便它们保持纵横比。 我将TabHost与TabWidget一起使用。然后我使用setBackgroundDrawable设置图像 我在这里找到了一个很接近的答案-。但是,我不确定在哪里添加新的可绘制代码。(使用HelloTabWidget示例时,我的模块中没有一个使用RelativeLayout,我也没有看到“tabcontent”的任何布局。) 我还发现了这条线-。根据它的说法,这听起来像是我必须对我的图像进行预缩放,这违背了使它们可缩放的全部目的 我还

我需要缩放TabWidget背景图像,以便它们保持纵横比。
我将TabHost与TabWidget一起使用。然后我使用setBackgroundDrawable设置图像

我在这里找到了一个很接近的答案-。但是,我不确定在哪里添加新的可绘制代码。(使用HelloTabWidget示例时,我的模块中没有一个使用RelativeLayout,我也没有看到“tabcontent”的任何布局。)

我还发现了这条线-。根据它的说法,这听起来像是我必须对我的图像进行预缩放,这违背了使它们可缩放的全部目的

我还发现了另一个线程,其中有人对Drawable类进行了子类化,这样它要么不能伸缩,要么可以正确伸缩。我现在找不到它,但当您只需要执行一些简单的操作,如mTab.setScaleType(centerInside)时,这似乎需要经历很多

这是我的密码:

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/main_background"> 
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1"/>        
    <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" 
            android:layout_weight="0"/>
    </LinearLayout>
</TabHost>
我也尝试了9patch图像,但结果太小了


那么,最好的方法是什么呢?

我想,您之所以难以找到一种开箱即用的方法来执行背景图像缩放,是因为它通常不被视为良好的做法。图像的缩放倾向于引入工件和带状,这会使您的UI看起来很糟糕。Imageview中有一个例外,但我认为该类提供的缩放支持更适合于支持照片或web内容(即应用程序中未附带的图像)

用户界面布局的设计应确保任何基于资源的背景图像都应预缩放到设备密度/屏幕大小的正确分辨率。换句话说,您应该使用《开发人员指南》中概述的资源文件夹命名约定,提供每个可绘制文件的多个版本,以适应多种屏幕密度和大小

然后,UI的布局应确保可以处理设备之间屏幕大小的任何细微差异,而无需缩放其包含视图的背景图像。显然,我不知道你建议的UI是什么样子,所以很难提出任何具体的建议,但通常我使用简单的背景块颜色或s来动态填充视图之间的空间

然而,如果你真的确定你想要缩放你的背景图像,尽管上面讲了:-),为什么不试着用一个来包装你现有的可绘制图像呢

如果您知道视图和背景图像可绘制的高度和宽度,则可以执行以下操作:

Drawable backgroundDrawable = getResources().getDrawable(R.drawable.tab_license_off); 
tempView.setBackgroundDrawable(
    new ScaleDrawable(
        backgroundDrawable,
        Gravity.CENTER,
        tempView.getWidth() / backgroundDrawable.getIntrinsicWidth(),
        tempView.getHeight() / backgroundDrawable.getIntrinsicHeight());

看看这个,让我知道它是否适合你

Drawable backgroundDrawable = getResources().getDrawable(R.drawable.tab_license_off); 
tempView.setBackgroundDrawable(
    new ScaleDrawable(
        backgroundDrawable,
        Gravity.CENTER,
        tempView.getWidth() / backgroundDrawable.getIntrinsicWidth(),
        tempView.getHeight() / backgroundDrawable.getIntrinsicHeight());