我有一个类似下面这样的相对布局,其中包含一些图片。
<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" >
<ImageView
android:id="@+id/image_2"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignLeft="@+id/increase"
android:layout_alignParentTop="true"
android:layout_marginLeft="34dp"
android:layout_marginTop="34dp"
android:src="@drawable/ic_launcher" />
<ImageView
android:id="@+id/image_1"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignBottom="@+id/image_2"
android:layout_marginBottom="14dp"
android:layout_toRightOf="@+id/increase"
android:src="@drawable/ic_launcher" />
<ImageView
android:id="@+id/image_8"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="@drawable/ic_launcher" />
</RelativeLayout>
在我的Java文件中,我需要执行一个小任务。当我点击一个图像时,它的大小应该增加。我尝试过这个,并且它是有效的,这是我的代码:
public class MainActivity extends Activity implements OnClickListener {
View imageView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView i1 = (ImageView ) findViewById(R.id.image_1);
ImageView i2 = (ImageView ) findViewById(R.id.image_2);
ImageView i3 = (ImageView ) findViewById(R.id.image_8);
i1.setOnClickListener(this);
i2.setOnClickListener(this);
i3.setOnClickListener(this);
}
public void onClick(View arg0) {
Log.v("clicked ", "clicked");
imageView = arg0;
Toast.makeText(this, "looking to resize the image ", 1).show();
Toast.makeText(this, "clicked 2", 1).show();
height = imageView.getHeight();
width = imageView.getWidth();
height += 50;
width += 50;
imageView.setLayoutParams(new RelativeLayout.LayoutParams(height, width));
}
}
但我遇到了一个问题。当我点击图片时,它的位置会改变。请看下面的屏幕截图...
下面是应用程序启动时的屏幕截图:
下面是当图像视图被点击时的屏幕截图。
有人能建议一下,这样图片就不会改变位置。我可以尝试使用像“网格视图”这样的东西(如果可能的话),但我也在尝试添加一些拖动选项。所以有人能给我建议吗?
更新后的代码:
onclick方法更新如下:
public void onClick(View arg0) {
Log.v("clicked ", "clicked");
imageView = arg0;
Toast.makeText(this, "looking to resize the image ", 1).show();
Toast.makeText(this, "clicked 2", 1).show();
height = imageView.getHeight();
width = imageView.getWidth();
height += 50;
width += 50;
RelativeLayout.LayoutParams params = new
RelativeLayout.LayoutParams(height, width);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
params.setMargins(
imageView.getLeft()-30,imageView.getTop()-30,imageView.getRight()+30,
imageView.getBottom()+30);
imageView.setLayoutParams(params);
}