Saturday, November 8, 2014

Android change orientation of layout dynamically

In this post create demo for change orientation of layout programmatically on radio button click.

See more update about android

See below is the output of the example.


First create xml layout file for radio button.
Below is the code for main.xml file

<LinearLayout 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"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/lin_btn"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<RadioButton
android:id="@+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="vertical" />
<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Horizontal" />
</RadioGroup>
</LinearLayout>
</LinearLayout>

Now, For change orientation programtically from Java put below java activity in your project.

public class MainActivity extends ActionBarActivity {
public LinearLayout lin_btn;
RadioGroup group;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
group = (RadioGroup) findViewById(R.id.radioGroup1);
lin_btn = (LinearLayout) findViewById(R.id.lin_btn);
group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(final RadioGroup group, int checkedId) {
if (checkedId == R.id.radio0) {
group.setOrientation(RadioGroup.VERTICAL);
} else if (checkedId == R.id.radio1) {
group.setOrientation(RadioGroup.HORIZONTAL);
}
}
});
}
}

Hope this post may helpful for you.