安卓小部件尺寸



>我有一个宽度为"180dp"的小部件。我想在用户单击小部件上的按钮时显示一个活动,并且活动的宽度必须等于小部件的宽度。这似乎很简单,但我无法解决它。事实上,我想这三种方式中至少有一种对我有帮助,但它们没有:
1-在清单中将活动的维度设置为"180dp",但我在清单中找不到任何属性,例如"android:width"的活动标签。
阿拉伯数字-通过 intent.getSourceBounds().getWidth() 获取 AppWidgetProvider 中的 widget 维度,onReceive() 方法,并在 Activity 的 onAttachedToWindow() 中使用它:
在 AppWidgetProvider 中:

@Override
public void onReceive(Context context, Intent intent) {
            ...
            int mWidgetHeight = intent.getSourceBounds().height();
            int mWidgetWidth = intent.getSourceBounds().width();
            ...
            App.setmWidgetHeight(mWidgetHeight);
            App.setmWidgetWidth(mWidgetWidth);
            ...
    }

在活动中:

@Override
public void onAttachedToWindow() {
        View view = getWindow().getDecorView();
        WindowManager.LayoutParams lp = (LayoutParams) view.getLayoutParams();
        lp.gravity = Gravity.LEFT | Gravity.TOP;
        super.onAttachedToWindow();
        ...
        lp.width = App.getmWidgetWidth();
        lp.height = App.getmWidgetHeight();
        ...
        getWindowManager().updateViewLayout(view, lp);
    }     

在这种情况下,当我在模拟器上测试我的应用程序时,活动的宽度约为小部件宽度的一半。
3-将"180 dp"更改为像素:

@Override
public void onAttachedToWindow() {
    View view = getWindow().getDecorView();
    WindowManager.LayoutParams lp = (LayoutParams) view.getLayoutParams();
    lp.gravity = Gravity.LEFT | Gravity.TOP;
    ...
    super.onAttachedToWindow();
    ...
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    float xDpi = metrics.xdpi;
    float yDpi = metrics.ydpi;
    ...
    lp.width = (int) (180 * (xDpi / 160)) ;
    lp.height = (int) (120 * (yDpi / 160));
    ...
    getWindowManager().updateViewLayout(view, lp);
}     

在这种情况下,在模拟器结果中似乎很好,但在设备(GalaxyTab 2.3.3)中,活动的宽度约为小部件宽度的(2/3)。
综上所述,这是我的问题:
如果我的小部件的尺寸为 dp,如何将活动的尺寸设置为完全等于它?

尝试

DisplayMetrics metrics = getApplication().getApplicationContext().getResources().getDisplayMetrics();
metrics.widthPixels
metrics.heightPixels

只是出于好奇 - 为什么您需要设置活动的确切规模?使用 android:layout_width="fill_parent" 和 android:layout_height="fill_parent" 的布局会占用小部件中的所有可用空间,无论大小如何。

最新更新