Hi Friends!
I am going to share how to designe
android view in Java file dynamically instead of xml file.
package
hello.test.android;
import
android.app.Activity;
import
android.os.Bundle;
import
android.widget.EditText;
import
android.widget.LinearLayout;
import
android.widget.RadioButton;
import
android.widget.RadioGroup;
import
android.widget.TextView;
public
class
DynamicUIDesigning extends
Activity {
String countryName[] = { "India", "Pakistan", "China", "Nepal", "Bangladesh" };
public
void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dynamic);
//
Getting first layout from main.xml file
LinearLayout
mLinearLayout = (LinearLayout) findViewById(R.id.linear1);
//
create a loop how many time you want repeat the content
for
(int
k = 1; k < 5; k++) {
//
create a base linear layout for linear1
LinearLayout
mLinearLayout1 = new
LinearLayout(this);
mLinearLayout1.setOrientation(0);
mLinearLayout.addView(mLinearLayout1);
//
create dynamic text box and label
TextView
title = new
TextView(this);
title.setText("User Info-" + k);
//
create name label
TextView
name = new
TextView(this);
name.setText("User Name:");
//
create title2
TextView
title2 = new
TextView(this);
title2.setText("User Info-" + k);
//
create city label
TextView
city = new
TextView(this);
city.setText("City
of residence");
//
create text box
EditText
editName = new
EditText(this);
editName.setText("User Name:");
//
setting values of second layout in linear1
LinearLayout
mLinearLayout2 = new
LinearLayout(this);
mLinearLayout2.setOrientation(1);
mLinearLayout1.addView(mLinearLayout2);
mLinearLayout2.addView(title);
mLinearLayout2.addView(name);
mLinearLayout2.addView(editName);
//
setting value of third layout in linear1
LinearLayout
mLinearLayout3 = new
LinearLayout(this);
mLinearLayout3.setOrientation(1);
mLinearLayout1.addView(mLinearLayout3);
mLinearLayout3.addView(title2);
mLinearLayout3.addView(city);
//
create radio button
final
RadioButton[] rb = new
RadioButton[5];
RadioGroup
rg = new
RadioGroup(this);
// create the RadioGroup
rg.setOrientation(RadioGroup.VERTICAL);//
or RadioGroup.VERTICAL
for
(int
i = 0; i < 5; i++) {
rb[i]
= new
RadioButton(this);
rg.addView(rb[i]);
// the RadioButtons are added to the
//
radioGroup instead of the layout
rb[i].setText(countryName[i]);
}
mLinearLayout3.addView(rg);
}
}
}
3-dynamic.xml
<?xml
version="1.0"
encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearBase"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linear1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
</LinearLayout>
</ScrollView>
</LinearLayout>
How to get value ?
ReplyDelete