2012-01-31 33 views
1

我发起的活动有两个按钮组成的线性布局。两个按钮都有监听器:第一个按钮(b)在点击时自动移动:30px到左边,30px返回到下一个点击。 第二个(b2)在点击后更改其文本。下面是代码:View.layout()的作品,直到下一个UI更新

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并尝试输入某些内容(如用户),则视图也会松动其效果。任何人都可以向我解释发生了什么事情,为什么意见会回退?

回答

0

看起来像父母布局为button2设置新文字后重新定位它的兄弟姐妹,因为正如xml中所述,button2通过宽度和高度来包装它的内容。

当你改变了按钮的内容,它要求它的父布局,以获得一个新的位置了。在这种情况下,父级布局将重新计算它所有兄弟的位置值。这就是为什么button1也回到它以前的位置。

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

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

0

Here说,这个问题可以得到解决,使用view.setLayoutParams()代替view.layout()

相关问题