【问题标题】:Assign match_parent as a dimen programmatically以编程方式将 match_parent 分配为维度
【发布时间】:2016-06-05 12:28:55
【问题描述】:

我正在使用 dimens.xml 文件为不同的布局大小分配值(即 dimens.xml@valuesdimens.xml@values-sw600dp)。

当尝试将尺寸设置为 wrap_Contentmatch_parent 时,我使用以下方式:

<resources>
    <item name="match_parent" format="integer" type="dimen">-1</item>
    <dimen name="popup_width">@dimen/match_parent</dimen>
</resources>

当在布局 xml 文件中使用这个维度时,它可以完美地工作,但是当尝试以编程方式使用它时,就像在声明弹出窗口时一样:

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 维度以便在我的代码中有效地使用它?或者我如何才能在我的代码中有效地使用当前的维度形式?

【问题讨论】:

  • match_parentwrap_content 不是维度。
  • @CommonsWare 所以,没有办法以编程方式将它们中的任何一个用作动态维度?!!甚至像其他任何东西一样?!!
  • 我的第一个问题是,为什么需要以编程方式使用match_parent 作为维度?您可以找到设备的宽度,并以编程方式将此宽度设置为您的PopupWindow 的宽度。
  • 不可能这样,因为我想在某些设备上将宽度设置为 match_parent 而在其他设备上设置为 700dp,因此它必须是为每个不同布局分配的动态参数在其对应的dimens.xml 文件中
  • 创建一个布尔资源(例如,use_match_parent),在适当的资源集中设置为truefalse。如果use_match_parent 为真,请将MATCH_PARENT 传递给您的PopupWindow。否则,请传递您的维度。

标签: android xml android-layout android-resources


【解决方案1】:

我使用-1.0px 代表match_parent-2.0px 代表wrap_content 解决了我的问题,因为dp 以不同的屏幕密度缩放,而px 不会对不同的屏幕密度做出反应(并且这就是我在解决方案中所需要的):

<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

【讨论】:

    猜你喜欢
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-29
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    相关资源
    最近更新 更多