Here's my code:
public class MyActivity extends Activity implements View.OnClickListener {
private Button mHorizontalButton;
private Button mVerticalButton;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mHorizontalButton = (Button) findViewById(R.id.horizontal_button);
mVerticalButton = (Button) findViewById(R.id.vertical_button);
mHorizontalButton.setOnClickListener(this);
mVerticalButton.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.horizontal_button:
setContentView(R.layout.horizontal);
break;
case R.id.vertical_button:
setContentView(R.layout.main);
break;
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This layout is vertical." />
<Button
android:text="Click for a horizontal layout"
android:id="@+id/horizontal_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
horizontal.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This layout is horizontal." />
<Button
android:text="Click for a vertical layout"
android:id="@+id/vertical_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
It is supposed, that by clicking on button I'll get the horizontal view, and then after clicking once again - vertical.
But after clicking nothing happens. What might be the issue?
You must either call setOnClickListener, as suggested by others or set the onclick XML attribute in your layout.
Like this:
<Button
android:onClick="buttonClick"
android:id="+@id/button1"
android:text="@string/button" />
in your code:
public void buttonClick(View button)
{
if (button.getId() == R.id.button1)
{ // do something
}
}