我的窗口xml如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >    <TextView
    android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
android:layout_centerHorizontal="true"           
        android:text="@string/hello_world" />    <RelativeLayout 
        android:id="@+id/layout" 
        android:layout_width="250sp"
        android:layout_height="350sp"
android:layout_centerHorizontal="true"           
        android:layout_below="@+id/textview" 
        android:background="#778899" >
        
        <ImageView
        android:id="@+id/magicpen"
        android:layout_width="wrap_content"
         android:layout_height="wrap_content"
android:layout_centerInParent="true"
        android:src="@drawable/magicpen"
        android:contentDescription="@string/desc" />"
        
    </RelativeLayout>
    
    <Button 
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true" 
        android:layout_below="@+id/layout" 
        android:text="@string/button1" />
        
    <Button 
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@id/button1" 
        android:layout_below="@+id/layout" 
        android:text="@string/button3" /></RelativeLayout>
关键是里面有个TextView和一个ImageView和两个Button。
关联图片的宽高都很小,一开始显示在屏幕的中间,这好像是默认的。按其中的一个Button后,我将图片显示置于左上角: b2.setOnClickListener(new OnClickListener(){ @Override
public void onClick(View v) {
// TODO Auto-generated method stub
int l=iv.getLeft();
int t=iv.getTop();
int r=iv.getRight();
int b=iv.getBottom();
r-=l;
b-=t;
l=0;
t=0;
iv.layout(l, t, r, b);
}

});
用到了layout,这好像也是没有问题的。再按另外一个Button,我希望是将ImageView中的图片的位置值显示在TextView中,问题就出现了:
b1.setOnClickListener(new OnClickListener(){ @Override
public void onClick(View v) {
// TODO Auto-generated method stub
tv.setText(" 左"+iv.getLeft()+" 顶"+iv.getTop()+" 右"+iv.getRight()+" 底"+iv.getBottom());
}

});
在TextView显示的值没有错,左和顶的位置都是0,但是图片却靠中显示,貌似使用了默认值。这是不是RelativeLayout里面还要设置什么呢?如何清除默认的靠中设置?

解决方案 »

  1.   

    android:layout_centerHorizontal="true" 这句代码不就是垂直居中么
      

  2.   

    试一下把btn1的点击事件改成这样btn1.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
    RelativeLayout.LayoutParams lParams = (LayoutParams) iv.getLayoutParams();

    lParams.addRule(RelativeLayout.CENTER_IN_PARENT, 0);
    lParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 1);
    lParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, 1);
    iv.setLayoutParams(lParams);
    }
    });
      

  3.   

    我是继承了layout,重载了onLayout,在里面做了拦截。