以编程方式将 match_parent 分配为维度
Assign match_parent as a dimen programmatically
我正在使用 dimens.xml
文件为不同的布局大小分配值(即 dimens.xml@values、dimens.xml@values-sw600dp).
当尝试将维度设置为 wrap_Content
或 match_parent
时,我使用以下方式:
<resources>
<item name="match_parent" format="integer" type="dimen">-1</item>
<dimen name="popup_width">@dimen/match_parent</dimen>
</resources>
并且在布局 xml 文件中使用此 dimen 时它工作得很好,但是当试图以编程方式使用它时,就像在声明弹出窗口时一样 window:
PopupWindow pw = new PopupWindow(layout, mContext.getResources().getDimension(R.dimen.popup_width),
ViewGroup.LayoutParams.MATCH_PARENT, true);
pw.showAtLocation(layout, Gravity.CENTER, 40, 0);
它根本不起作用,它认为如果我向它传递了一个 -1dp
值(它执行直接引用),所以布局完全被破坏了。
那么我怎样才能在 dimens.xml
文件中声明 match_parent 维,以便在我的代码中有效地使用它?或者我怎样才能在我的代码中有效地使用当前的尺寸形式?
我使用 -1.0px
来表示 match_parent
并使用 -2.0px
来表示 wrap_content
解决了我的问题,因为 dp
与不同的屏幕密度不同 [= =17=] 对不同的屏幕密度没有反应(这就是我在解决方案中需要的):
<dimen name="popup_width">-1.0px</dimen> <!-- for match_parent -->
<dimen name="popup_height">-2.0px</dimen> <!-- for wrap_content -->
然后我以编程方式使用它,例如:
PopupWindow pw = new PopupWindow(layout, (int)mContext.getResources().getDimension(R.dimen.popup_width),
(int)mContext.getResources().getDimension(R.dimen.popup_height), true); // notice that they have to be casted as int
我正在使用 dimens.xml
文件为不同的布局大小分配值(即 dimens.xml@values、dimens.xml@values-sw600dp).
当尝试将维度设置为 wrap_Content
或 match_parent
时,我使用以下方式:
<resources>
<item name="match_parent" format="integer" type="dimen">-1</item>
<dimen name="popup_width">@dimen/match_parent</dimen>
</resources>
并且在布局 xml 文件中使用此 dimen 时它工作得很好,但是当试图以编程方式使用它时,就像在声明弹出窗口时一样 window:
PopupWindow pw = new PopupWindow(layout, mContext.getResources().getDimension(R.dimen.popup_width),
ViewGroup.LayoutParams.MATCH_PARENT, true);
pw.showAtLocation(layout, Gravity.CENTER, 40, 0);
它根本不起作用,它认为如果我向它传递了一个 -1dp
值(它执行直接引用),所以布局完全被破坏了。
那么我怎样才能在 dimens.xml
文件中声明 match_parent 维,以便在我的代码中有效地使用它?或者我怎样才能在我的代码中有效地使用当前的尺寸形式?
我使用 -1.0px
来表示 match_parent
并使用 -2.0px
来表示 wrap_content
解决了我的问题,因为 dp
与不同的屏幕密度不同 [= =17=] 对不同的屏幕密度没有反应(这就是我在解决方案中需要的):
<dimen name="popup_width">-1.0px</dimen> <!-- for match_parent -->
<dimen name="popup_height">-2.0px</dimen> <!-- for wrap_content -->
然后我以编程方式使用它,例如:
PopupWindow pw = new PopupWindow(layout, (int)mContext.getResources().getDimension(R.dimen.popup_width),
(int)mContext.getResources().getDimension(R.dimen.popup_height), true); // notice that they have to be casted as int