如何在运行时更改视图大小

时间:2014-09-07 16:52:03

标签: java android android-framelayout

如果方向在运行时发生变化,我想要左右显示片段。我所做的是声明两个framelayout,第二个大小为零,高度和宽度。

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- As the main content view, the view below consumes the entire
         space available using match_parent in both dimensions. -->
    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <FrameLayout
        android:id="@+id/conversation_history"
        android:layout_width="0px"
        android:layout_height="0px"/>


    <!-- android:layout_gravity="start" tells DrawerLayout to treat
         this as a sliding drawer on the left side for left-to-right
         languages and on the right side for right-to-left languages.
         The drawer is given a fixed width in dp and extends the full height of
         the container. A solid background is used for contrast
         with the content view. -->
    <ListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#111"/>
</android.support.v4.widget.DrawerLayout>

然后当方向改变时,我尝试调整框架布局的大小。而不是占据屏幕一半的每个片段都重叠并占据整个屏幕。那么为什么两者占据整个屏幕而不是占据屏幕的一半呢?

FrameLayout frame = (FrameLayout) findViewById(R.id.content_frame);
                int portraitWidth,portriatHeight;
                portraitWidth = frame.getWidth();
                portriatHeight = frame.getHeight();
                frame.getLayoutParams().width = portriatHeight/2;
                frame.getLayoutParams().height = portraitWidth/2;
                frame.setX(0);
                frame.setY(0);
                frame.requestLayout();
                frame.invalidate();

                FrameLayout contentFrame = (FrameLayout) findViewById(R.id.conversation_history);
                contentFrame.getLayoutParams().width = portriatHeight/2;
                contentFrame.getLayoutParams().height = portraitWidth/2;
                contentFrame.setX(portriatHeight/2);
                contentFrame.setY(portraitWidth/2);
                contentFrame.requestLayout();
                contentFrame.invalidate();

1 个答案:

答案 0 :(得分:0)

如果您在屏幕上显示了确定数量的片段,则表明您愿意/将会这样做。

我强烈建议您只创建一个布局横向变体。系统会注意到已经发生方向更改并查找相关布局 - 位于您的res下方 - &gt; layout-land文件夹。

如果您没有并且正在使用Android Studio,只需在设计模式下打开您的布局,然后找到带有Android头的文件图标,点击它 - 然后选择“创建横向布局”