I have a simple demo with two buttons. They are laid out with a RelativeLayout at the top and bottom of the screen.
When I click one of them, I want them to switch places. What is the best way to do that?This is my res/layout/main.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageButton
android:id="@+id/android_button_1"
android:layout_width="200dip"
android:layout_height="wrap_content"
android:src="@drawable/icon"
android:layout_alignParentTop="true" />
<ImageButton
android:id="@+id/android_button_2"
android:layout_width="200dip"
android:layout_height="wrap_content"
android:src="@drawable/icon2"
android:layout_alignParentBottom="true" />
</RelativeLayout>
And this is my Activity:
public class HelloButtons extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageButton button1 = (ImageButton) findViewById(R.id.android_button_1);
final ImageButton button2 = (ImageButt开发者_开发知识库on) findViewById(R.id.android_button_2);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
Toast.makeText(HelloButtons.this, "Beep Bop", Toast.LENGTH_SHORT).show();
}
});
button2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
Toast.makeText(HelloButtons.this, "Beep Bop", Toast.LENGTH_SHORT).show();
}
});
}
}
Use something along these lines
RelativeLayout.LayoutParams lp1 = (LayoutParams) b1.getLayoutParams();
RelativeLayout.LayoutParams lp2 = (LayoutParams) b2.getLayoutParams();
lp2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
lp2.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
lp1.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
lp1.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 0);
b1.setLayoutParams(lp1);
b2.setLayoutParams(lp2);
(and the opposite to revert them again) in you OnClickListeners
I would say the best way to do that is not to switch the actual ImageButton
locations, but to instead switch the ImageButton
images and keep track of the state inside your application so it can react to onClicks
correctly.
精彩评论