【问题标题】:setting margins on relative layout doesnt work在相对布局上设置边距不起作用
【发布时间】:2012-03-21 19:43:23
【问题描述】:

我使用 FragmentTransaction 将 Fragment 添加到 FrameLayout。我想动态更改 Fragment 使用的 RelativeLayout 的边距。但是,边距不会随 RelativeLayout.layoutParams 改变。我也用了setMargins(),但没用。

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.infocard, container, false);

        RelativeLayout infoLayout = (RelativeLayout) view.findViewById(R.id.info);
        infoLayout.setOnClickListener(new EmptyClickListener());

        final int width = 250;
        final int height = 320;
        int leftMargin = 0;
        int topMargin = 0;
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, height);

        if (x - width < 0) {
            leftMargin = 0;
            System.out.println("left " + leftMargin);
        }
        else {
            leftMargin = x - width;
        }

        if (y >= 450 && y <= 480) {
            topMargin = y - height;
        }

        params.leftMargin = leftMargin;
        params.topMargin = topMargin;

        infoLayout.setLayoutParams(params);

【问题讨论】:

    标签: android layout android-relativelayout margins


    【解决方案1】:

    尝试使用

    FrameLayout.LayoutParams
    

    而不是

    RelativeLayout.LayoutParams
    

    布局期望 params 类型是其父容器中的类型,而不是您设置它们的 View 类型

    【讨论】:

    • 由于某种原因,这适用于运行 3.2.1 的东芝选项卡,但不适用于 Kindle Fire 2.3.4
    • 它是否抛出任何错误?您是否在 KF 上尝试过另一种方式(您发布的方式),看看它是否可能倒退?
    • 它没有抛出任何错误。我发布的方式在kindle fire上不起作用。
    • 奇怪。这可能与为 KF 所做的操作系统的某些更改有关。不过,我不太确定。我发布的方式是正确的,并且是 Android 所期望的。如果它不起作用,那么可以尝试清理您的项目,卸载当前在设备上的项目,然后重新安装(只是为了耗尽所有可能性)。如果它仍然发生,则可能与 KF 处理 LayoutParams 的方式有关。
    • 如果有人能解决这个问题,我就专门针对 Kindle Fire 发表了一篇新帖子。 stackoverflow.com/questions/9813894/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    • 2017-02-25
    • 2014-04-02
    • 1970-01-01
    • 2012-10-12
    • 2013-05-12
    • 2013-10-20
    相关资源
    最近更新 更多