4

I have a widget that it's width is "180dp".I want to display an activity when user clicks on a button on widget,and activity's width must be equal to widget's width.It seems to be simple but I could not solve it.Indeed I guess that at least one of these three ways help me,but they do not:
1- Setting activity's dimension in manifest exactly "180dp",but I could not find any property like "android:width" for Activity tag in manifest.
2- Getting widget dimensions in it's AppWidgetProvider, onReceive() method by intent.getSourceBounds().getWidth() and use it in Activity's onAttachedToWindow():
In 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);
            ...

    }

In Activity:

@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);
    }     

In this case,when I test my App on emulator,activity's width is in about half of the widget's width.
3- Changing "180 dp" to pixel:

@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);
}     

In this case, in emulator result seems fine,but in device (GalaxyTab 2.3.3), Activity's width is in about (2/3) of widget's width.
In summary,this is my question:
If I have my widget's dimensions in dp,how I can set Activity's dimensions exactly equal to it?

4

1 回答 1

-1

尝试

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

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

于 2013-06-04T16:29:04.647 回答