View.layout()一直工作到下一次UI更新



我的启动活动由带有两个按钮的线性布局组成。两个按钮都有监听器:第一个按钮(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并尝试输入一些内容(作为用户),视图也会失去效果。有人能向我解释一下发生了什么吗?为什么观点会倒退?

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

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

请记住,您还将父布局的重力值设置为center,这意味着当布局将定位其同级时,它将把它们定位在其中心。

试着用一些其他布局类进行实验,比如FrameLayout,它有绝对的方式来定位它的兄弟类和RelativeLayout,也试着摆脱布局的重力。

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

最新更新