【问题标题】:View.layout() works until next UI updateView.layout() 一直有效,直到下一次 UI 更新
【发布时间】:2012-01-31 13:25:13
【问题描述】:

我的启动活动由带有两个按钮的线性布局组成。两个按钮都有监听器:第一个 (b) 在单击时自行移动:向左移动 30px,在下次单击时向后移动 30px。 第二个(b2)在单击时更改其文本。代码如下:

public class TestActivity extends Activity {
public final String TAG="TestActivity";
boolean toTop=true;
boolean setInitialText=false;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main); 
    Button b=(Button)findViewById(R.id.button);
    Button b2=(Button)findViewById(R.id.button2);
    b.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            int modifier;
            if(toTop) modifier=-30; 
            else modifier=30;
            v.layout(v.getLeft()+modifier,v.getTop(),v.getRight()+modifier,v.getBottom());
            toTop=!toTop;
        }
    });

    b2.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            String currentText;
            if(setInitialText)currentText="Press to change text";
            else currentText="Press to change back";
            ((Button)v).setText(currentText);
            setInitialText=!setInitialText;
        }
    });
}
}

XML 布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Press to begin animation" />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Press to change text" />

我的问题:当 b 向左移动并按下 b2 时,b 移动到其初始位置。为什么?我不希望它向后移动,也没有在任何地方指定它。

看起来 View.layout 失去了效果。为什么会发生?我在其他情况下进行了测试,似乎任何 UI 更新都会使所有调用的 View.layout 方法失去作用。

在我的主项目中,有一个 ListView,其中填充了来自背景的图像 - 当新图像出现时,所有视图都会移动松散效果。此外,如果我添加 EditText 并尝试输入某些内容(作为用户),视图也会失去其效果。谁能向我解释发生了什么以及为什么视图会向后移动?

【问题讨论】:

    标签: android layout view


    【解决方案1】:

    在您为 button2 设置新文本后,父布局似乎会重新定位它的兄弟,因为正如 xml 中所述,button2 按宽度和高度包装其内容。

    当您更改按钮的内容时,它会请求其父布局为其获取新位置。在这种情况下,父布局将重新计算其所有兄弟的位置值。这就是为什么button1 也回到它之前的位置。

    请记住,您还将父布局的重力值设置为center,这意味着当布局定位它的兄弟姐妹时,它会将它们定位在它的中心。

    尝试尝试一些其他布局类,例如FrameLayout,它具有绝对定位其兄弟姐妹的方式和RelativeLayout,并尝试摆脱布局的重力。

    【讨论】:

      【解决方案2】:

      Here 表示这个问题可以解决,使用view.setLayoutParams() 而不是view.layout()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-20
        • 2021-11-21
        • 2016-04-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多