azizbekian azizbekian - 1 month ago 8
Android Question

Android beginner layout

Here's my code.

public class Business extends Activity implements OnClickListener
{
private Button mHorizontalButton;
private Button mVerticalButton;
/** Called when the activity is first created. */
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;
}
}
}


This is 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>


And this is 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>


Actually this example is taken from Merrifield Mew book.
It is supposed, that by clicking on button I'll get the horizontal view, and then after clicking once again - vertical. But after clicking I get nothing, even I can't see my log.i message in logcat.

Answer

SOLVED!

Here's the code:

public class myClass extends Activity
{           
private Button mHorizontalButton;
private Button mVerticalButton;
/** Called when the activity is first created. */
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);
}

public void buttonClick(View button)
{
   if (button.getId() == R.id.vertical_button)
   { 
       setContentView(R.layout.main);
   }
   if(button.getId() == R.id.horizontal_button)
   {
        setContentView(R.layout.horizontal);           
   }
}
}
Comments