即时重新定位布局

3
在下面的main.xml布局中,是否可能在运行时更改FrameLayout的“layout_gravity”,并立即显示结果?
我的主要布局是一个LinearLayout和一个居中的FrameLayout子级,其中有两个子级,一个SurfaceView和一个ImageView(位于框架布局底部)。
我有一个菜单,让用户选择重新定位框架布局,这应该通过将layout_gravity更改为“top”,“bottom”或“center”来完成。
为了实现这一点,我使用以下代码在运行时更改重力:
int mGravity = Gravity.TOP  // gravity determined from menu selection
FrameLayout mFrameLayout = (FrameLayout)findViewById(R.id.my_framelayout);
((LinearLayout.LayoutParams) mFrameLayout.getLayoutParams()).gravity = mGravity;

然而,这并不能立即生效。我只有在用户单击其他菜单项后才能使其工作,这将带他们到Android市场。当用户从市场退出并返回到我的应用程序时,才会根据用户之前选择的内容绘制新的布局。

我是否遗漏了一些简单的东西?我如何在用户选择位置后强制重新绘制?我应该使什么无效?

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll_main"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<FrameLayout 
    android:id="@+id/my_framelayout"
    android:layout_width="fill_parent"
    android:layout_height="@dimen/surfaceview_default_h"
    android:layout_gravity="center">

    <SurfaceView 
        android:id="@+id/my_surfaceview" 
        android:layout_width="@dimen/surfaceview_default_w" 
        android:layout_height="@dimen/surfaceview_default_h">           
    </SurfaceView>

    <ImageView 
        android:id="@+id/my_imageview"
        android:layout_height="wrap_content" 
        android:layout_width="fill_parent"  
        android:src="@drawable/someimage" 
        android:layout_gravity="bottom">
    </ImageView>

</FrameLayout>
</LinearLayout>

menu.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item 
    android:id="@+id/mnu_position"
    android:title="@string/position">
    <!-- Position submenu -->
    <menu>
        <group
            android:id="@+id/grp_position" 
            android:menuCategory="container" 
            android:checkableBehavior="single">
            <item 
                android:id="@+id/mnu_position_top" 
                android:title="@string/top">
            </item>
            <item 
                android:id="@+id/mnu_position_center"
                android:title="@string/center"
                android:checked="true"> 
            </item>
            <item
                android:id="@+id/mnu_position_bottom"
                android:title="@string/bottom">
            </item>
        </group>
    </menu>
</item>
<item 
    android:id="@+id/mnu_android_market" 
    android:title="@string/market">
</item>
</menu>
1个回答

0

尝试添加

mFrameLayout.invalidate();

在设置重力之后。


谢谢您的建议,但不幸的是它没有任何效果。然而,我发现如果我在设置重力后立即在主LinearLayout(ll_main)上执行setBackgroundColor(),它会相应地更新FrameLayout的位置。但它只会这样做一次。如果我立即返回菜单并选择不同的位置,则无法重新定位,即使再次运行setBackgroundColor()。 - Jason

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接