【发布时间】: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 并尝试输入某些内容(作为用户),视图也会失去其效果。谁能向我解释发生了什么以及为什么视图会向后移动?
【问题讨论】: