how to create quiz section using radio group and textview dynamically? - android

"I want to create a quiz section inside fragment tab and the structure should be as below
Question1
RadioGroup1
RadioButton1
RadioButton2
RadioButton3
RadioButton4
Question2
RadioGroup2
RadioButton5
RadioButton6
RadioButton7
RadioButton8
Question3
RadioGroup3
RadioButton9
RadioButton10
RadioButton11
RadioButton12
With the below code i could able to create just one question and one radio button, i want to make it dynamic in the future
private void creatRadioButtons() {
group = new RadioGroup(this.getContext());
// group = (RadioGroup) view.findViewById(R.id.radioGroup);
int[] panels = getResources().getIntArray(R.array.no_of_solar_panels);
int no_of_que = 2;
for(int i = 0; i < no_of_que; i++){
// textView = (TextView) view.findViewById(R.id.question);
textView = new TextView(this.getContext());
textView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
textView.setText("Question number " + i);
linearLayout.addView(textView);
for (int j = 0; j< panels.length; j++){
button = new RadioButton(this.getContext());
button.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
button.setText(String.valueOf(panels[j]));
group.setLayoutParams(new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT));
group.addView(button);
}
linearLayout.addView(group);
}
}
"
This is how my screen is coming up now

Please try this code
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
android:id="#+id/parentLayout"/>
</ScrollView>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private LinearLayout parentLayout;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=MainActivity.this;
parentLayout=findViewById(R.id.parentLayout);
createRadioButtons();
}
private void createRadioButtons(){
//Number pf questions
int[] panels = new int[]{1,2,3,4,5};
int no_of_que = 20;
TextView question;
RadioGroup radioGroup;
RadioButton radioButton;
for (int i=0;i<no_of_que;i++){
question = new TextView(context);
question.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
question.setText("Question: "+i);
parentLayout.addView(question);
radioGroup=new RadioGroup(context);
radioGroup.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
parentLayout.addView(radioGroup);
for(int j=0;j<panels.length;j++){
radioButton=new RadioButton(context);
radioButton.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));;
radioButton.setText("Radio Button");
radioGroup.addView(radioButton);
}
}
}
}

Try This I Already Did Quiz Kind Of Application With Question Type Fill In The Blank, Match The Following, Check Box, Radio Button
This is activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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"
android:id="#+id/rel_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:id="#+id/questionsLinearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
</RelativeLayout>
This is my QuestionChoiceVo.java (This class to hold question and it's choices)
import java.io.Serializable;
import java.util.ArrayList;
public class QuestionChoiceVo implements Serializable {
String question;
ArrayList<String> choiceArrayList;
public QuestionChoiceVo(String question, ArrayList<String> choiceArrayList)
{
this.question = question;
this.choiceArrayList = choiceArrayList;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public ArrayList<String> getChoiceArrayList() {
return choiceArrayList;
}
public void setChoiceArrayList(ArrayList<String> choiceArrayList) {
this.choiceArrayList = choiceArrayList;
}
}
This is my MainActivity class.
public class MainActivity extends AppCompatActivity {
LinearLayout linearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialiseView();
}
private void initialiseView() {
linearLayout = (LinearLayout) findViewById(R.id.questionsLinearLayout);
ArrayList<QuestionChoiceVo> questionChoiceVoArrayList = new ArrayList<>();
QuestionChoiceVo mQuestionChoiceVoOne = new QuestionChoiceVo("Question One", new ArrayList<String>() {{add("Choice One");add("Choice Two");add("Choice Three");}});
QuestionChoiceVo mQuestionChoiceVoTwo = new QuestionChoiceVo("Question Two", new ArrayList<String>() {{add("Choice One");add("Choice Two");add("Choice Three");}});
QuestionChoiceVo mQuestionChoiceVoThree = new QuestionChoiceVo("Question Three", new ArrayList<String>() {{add("Choice One");add("Choice Two");add("Choice Three");}});
questionChoiceVoArrayList.add(mQuestionChoiceVoOne);
questionChoiceVoArrayList.add(mQuestionChoiceVoTwo);
questionChoiceVoArrayList.add(mQuestionChoiceVoThree);
prepareQuestionAnswerLayout(questionChoiceVoArrayList);
}
private void prepareQuestionAnswerLayout(ArrayList<QuestionChoiceVo> questionChoiceVoArrayList) {
for (QuestionChoiceVo mQuestionChoiceVo : questionChoiceVoArrayList) {
LinearLayout mSingleQuestionLinearLayout = new LinearLayout(this);
mSingleQuestionLinearLayout.setOrientation(LinearLayout.VERTICAL);
mSingleQuestionLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
TextView mTextView = new TextView(this);
mTextView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
mTextView.setText(mQuestionChoiceVo.getQuestion());
mTextView.setTextSize(20f);
mSingleQuestionLinearLayout.addView(mTextView);
RadioGroup mChoiceRadioGroup = setUpChoices(mQuestionChoiceVo);
RelativeLayout.LayoutParams radioGroupLayoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
mChoiceRadioGroup.setLayoutParams(radioGroupLayoutParams);
mSingleQuestionLinearLayout.addView(mChoiceRadioGroup);
linearLayout.addView(mSingleQuestionLinearLayout);
}
}
private RadioGroup setUpChoices(QuestionChoiceVo mQuestionChoiceVo) {
RadioGroup radioGroup = new RadioGroup(this);
radioGroup.setId(View.generateViewId());
for (int i = 0; i < mQuestionChoiceVo.getChoiceArrayList().size(); i++){
RadioButton radioButton = new RadioButton(this);
radioButton.setText(mQuestionChoiceVo.getChoiceArrayList().get(i));
radioButton.setTextSize(18f);
RadioGroup.LayoutParams radioGroupLayoutParams = new RadioGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
radioGroupLayoutParams.setMargins(10, 10, 10, 10);
radioButton.setPadding(10, 10, 10, 10);
radioButton.setLayoutParams(radioGroupLayoutParams);
radioButton.setId(View.generateViewId());
radioGroup.addView(radioButton);
}
return radioGroup;
}
}
Output As Your Requirement :

You should use RecyclerView instead of just adding fix number of question at design time,via RecyclerView you can add as much as question you want dynamically.

You need to use recyclerview to create dynamic no. of questions. In recycler layout, create a question with four radio buttons.
For recycler example, see this

Related

How to tag data in toggle buttons and loop through them to fetch the selected button's data

I am trying to add toggle buttons dynamically in a linear layout. I have successfully done this- 2 rows with each row having 2 buttons.
Below is the code for it::
public class MainActivity extends Activity
{
LinearLayout VertLayout;
LayoutInflater inflater;
LinearLayout lnrLay_forXaxis;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
make_seat();
}
private void initialize()
{
VertLayout = (LinearLayout) findViewById(R.id.lnrLyMain);
inflater = (LayoutInflater) this.getLayoutInflater();
}
private void make_seat()
{
try{
for(int y=0;y<2;y++)
{
lnrLay_forXaxis = new LinearLayout(this);
lnrLay_forXaxis.setBackgroundColor(Color.CYAN);
lnrLay_forXaxis.setOrientation(LinearLayout.HORIZONTAL);
LayoutParams LLParams = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
lnrLay_forXaxis.setLayoutParams(LLParams);
for(int x=0;x<2;x++)
{
final View sngl_lnrLay = (View) inflater.inflate(R.layout.lnrly_btn, null);
final ToggleButton btt = (ToggleButton) sngl_lnrLay.findViewById(R.id.ToggleButton01);
btt.setChecked(false);
btt.setText("btn-"+x+y);
btt.setTextOn("btn-"+ x+y+" -ON");
btt.setTextOff("btn-"+x+y);
lnrLay_forXaxis.addView(sngl_lnrLay);
}
VertLayout.addView(lnrLay_forXaxis);
}
}
catch(Exception ex)
{Log.d("exp",ex.toString());}
}
}
in activity_main.xml:
<LinearLayout
android:id="#+id/lnrLyMain"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#CCFFCC"
android:orientation="vertical" >
</LinearLayout>
in lnrly_btn.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ToggleButton
android:background="#drawable/btn_toggle_bg"
style="#style/YourThemeName"
android:checked="true"
android:id="#+id/ToggleButton01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="3dp">
</ToggleButton>
</LinearLayout>
Now i want to add some data with each toggle button(think it should be tag i should be using) and add another button to the activity(lets say button-x). So, after selecting few toggle buttons and then clicking on button-x; a toast/Log will appear showing the selected toggle buttons added/tagged values.
How can i do this.
You can do something like that:
Add field to your Activity:
ArrayList<View> toggles = new ArrayList<>();
Then:
for(int y=0;y<2;y++)
{
lnrLay_forXaxis = new LinearLayout(this);
lnrLay_forXaxis.setBackgroundColor(Color.CYAN);
lnrLay_forXaxis.setOrientation(LinearLayout.HORIZONTAL);
LayoutParams LLParams = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
lnrLay_forXaxis.setLayoutParams(LLParams);
for(int x=0;x<2;x++)
{
final View sngl_lnrLay = (View) inflater.inflate(R.layout.lnrly_btn, null);
final ToggleButton btt = (ToggleButton) sngl_lnrLay.findViewById(R.id.ToggleButton01);
Object tag; //your object,int, string ,whatever
//init your tag
btt.setTag(tag);
btt.setChecked(false);
btt.setText("btn-" + x + y);
btt.setTextOn("btn-" + x + y + " -ON");
btt.setTextOff("btn-" + x + y);
toggles.add(btt);
lnrLay_forXaxis.addView(sngl_lnrLay);
}
VertLayout.addView(lnrLay_forXaxis);
}
Button add = new Button(this);
LayoutParams btParams = new LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
btParams.gravity = Gravity.CENTER;
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (View toggle: toggles)
Log.d("TAG", toggle.getTag().toString());
}
});
VertLayout.addView(add, btParams);

How to get location of table layout cell in ANDROID

I am adding dynamic row with textview in table layout, Also I want x y coordinates of that textview. For that I used view.getLocationOnScreen(loc) method.
But is showing only last item coordinates, I want to show all item coordinates.
This is my source code please help me for that.
Thanks you.
public class MainActivity extends Activity {
TextView tv1, tv2;
TableRow row;
TextView txt;
TableLayout tl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tl = (TableLayout) findViewById(R.id.tableLayout1);
for (int i = 0; i <= 15; i++) {
row = new TableRow(this);
txt = new TextView(this);
tl.addView(row);
row.addView(txt);
readLocation();
}
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
readLocation();
}
private void readLocation() {
int[] locationOnScreen = new int[2];
txt.getLocationOnScreen(locationOnScreen);
txt.setText(locationOnScreen[0] + " : " + locationOnScreen[1]);
}
}
and my following xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</TableLayout>
</ScrollView>
You shouldn't try to get those coordinates in onCreate method in this way since layout procedures are not yet completed at this point.
Here is a little bit modified demo base on your code:
public class MainActivity extends Activity {
ArrayList<TextView> txt = new ArrayList<TextView>();
TableLayout tl;
Handler _h = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tl = (TableLayout) findViewById(R.id.tableLayout1);
for (Integer i = 0; i <= 15; i++) {
TableRow therow = new TableRow(this);
TextView thetxt = new TextView(this);
therow.addView(thetxt);
tl.addView(therow);
txt.add(thetxt);
thetxt.setText("stub");
}
tl.requestLayout();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
_h.postDelayed(new Runnable() {
#Override
public void run() {
for (Integer i = 0; i <= 15; i++) {
TextView thetxt = txt.get(i);
int[] locationOnScreen = new int[2];
thetxt.getLocationOnScreen(locationOnScreen);
thetxt.setText(locationOnScreen[0] + " : " + locationOnScreen[1]);
}
}
}, 1000);
}
}
The key point is postDelayed in onResume that lets the system to position all views correctly.

How to add and remove linear layout by button click

I'm trying to use two buttons to dynamically add and remove linear layout.
protected void createT () {
// -----------------------------------------------
count++;
LinearLayout temp_ll, frame;
frame = new LinearLayout(this);
frame.setOrientation(LinearLayout.VERTICAL);
frame.setId(count);
EditText temp1, temp2;
for (int i=0; i<numClass; i++) {
temp_ll = new LinearLayout(this);
temp_ll.setOrientation(LinearLayout.HORIZONTAL);
temp1 = new EditText(this);
temp2 = new EditText(this);
temp2.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
temp1.setHint("class name");
temp2.setHint("grade");
temp_ll.addView(temp1);
temp_ll.addView(temp2);
frame.addView(temp_ll);
}
ll.addView(frame);
}
protected void deleteT() {
// --------------------------------------
if (count > 0) {
LinearLayout temp = new LinearLyout(this);
temp = (LinearLayout) findViewById(count);
temp.removeAllViews();
temp.setVisibility(View.GONE);
count--;
}
}
Every time I press add button, it calls the createT()
Every time i press del button it calls the deleteT()
The problem is that I'm using count variable to keep track of linearLayout IDs.
First time when I press add button x times and then press del button everything is fine.
THE PROBLEM IS THAT AFTER PRESSING ADD SECOND TIME .
I checked your code and I found a little mistake inside the deleteT() method, you remove all view inside the LinearLayout, but you didn't remove the actual layout from the root layout.
And an another suggestion, you don't need a new LinearLayout instance when you want to use findviewbyid method, and use ll.removeView(View) method to delete the dynamic LinearLayout container.
Here is the code:
private int count;
private LinearLayout ll;
private final int numClass = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ll = (LinearLayout) findViewById(R.id.main_linearlayout);
}
public void createT(View view) {
count++;
final LinearLayout frame = new LinearLayout(this);
frame.setOrientation(LinearLayout.VERTICAL);
frame.setId(count);
for (int i = 0; i < numClass; i++) {
final LinearLayout temp_ll = new LinearLayout(this);
final EditText temp1;
final EditText temp2;
temp_ll.setOrientation(LinearLayout.HORIZONTAL);
temp1 = new EditText(this);
temp2 = new EditText(this);
temp2.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
temp1.setHint("class name");
temp2.setHint("grade");
temp_ll.addView(temp1);
temp_ll.addView(temp2);
frame.addView(temp_ll);
}
ll.addView(frame);
}
public void deleteT(View view) {
if (count > 0) {
final LinearLayout temp = (LinearLayout) ll.findViewById(count);
temp.removeAllViews();
ll.removeView(temp);
count--;
}
}
And the layout xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="#+id/main_linearlayout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="add"
android:onClick="createT" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="delete"
android:onClick="deleteT" />
</LinearLayout>
I hope it helps!

How to horizontally align some programmatically added views?

I have designed a layout as in the image below:
After entering text in the EditText, when I press the Add+ Button the TextView and Button will be added as shown in the image below:
I want to show the Button on the right side of the TextView. How should I do this?
Another question, how should I remove corresponding View when user clicks a button? The code:
public class ExampleActivity extends Activity {
private LinearLayout mLayout;
private EditText mEditText;
private Button mButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLayout = (LinearLayout) findViewById(R.id.linearLayout);
mEditText = (EditText) findViewById(R.id.editText);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mLayout.addView(createNewTextView(mEditText.getText()
.toString()));
mLayout.addView(createNewButton());
}
});
}
private TextView createNewTextView(String text) {
final LayoutParams lparams = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(this);
textView.setLayoutParams(lparams);
textView.setText("New text: " + text);
return textView;
}
private Button createNewButton() {
final LayoutParams lparams = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final Button button = new Button(this);
button.setLayoutParams(lparams);
button.setText(" - ");
return button;
}
}
The TextViews and Buttons are stacked because you probably use a LinearLayout with the orientation vertical. You could wrap your TextView + Button into a LinearLayout and then add this LinearLayout to your own layout or you could use a TableLayout like below(I've added some ids so you can delete the rows you want):
public class SomeActivity extends Activity {
private EditText mInput;
private TableLayout mTable;
private static int sCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button addButton = (Button) findViewById(R.id.add);
mInput = (EditText) findViewById(R.id.editText1);
mTable = (TableLayout) findViewById(R.id.table1);
addButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mTable.addView(addRow(mInput.getText().toString()));
}
});
}
private TableRow addRow(String s) {
TableRow tr = new TableRow(this);
tr.setId(1000 + sCount);
tr.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.FILL_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
TableRow.LayoutParams tlparams = new TableRow.LayoutParams(
TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT);
TextView textView = new TextView(this);
textView.setLayoutParams(tlparams);
textView.setText("New text: " + s);
tr.addView(textView);
TableRow.LayoutParams blparams = new TableRow.LayoutParams(
TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT);
final Button button = new Button(this);
button.setLayoutParams(blparams);
button.setText(" - ");
button.setId(2000 + sCount);
button.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
mTable.removeView(findViewById(v.getId() - 1000));
}
});
tr.addView(button);
sCount++;
return tr;
}
}
where the main layout file is:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="#+id/parent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/add"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TableLayout
android:id="#+id/table1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TableLayout>
</LinearLayout>
</ScrollView>
If for some reason, you don't like the TableLayout use a LinearLayout to wrap you TextView and Button with the layout file above(and of course remove the TableLayout):
//...
ll = (LinearLayout) findViewById(R.id.parent);
addButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//where ll is the LinearLayout with the id parent
ll.addView(addRow(mInput.getText().toString()));
}
});
}
private LinearLayout addRow(String s) {
LinearLayout tr = new LinearLayout(this);
tr.setId(1000 + sCount);
tr.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
LinearLayout.LayoutParams tlparams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
TextView textView = new TextView(this);
textView.setLayoutParams(tlparams);
textView.setText("New text: " + s);
tr.addView(textView);
LinearLayout.LayoutParams blparams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
final Button button = new Button(this);
button.setLayoutParams(blparams);
button.setText(" - ");
button.setId(2000 + sCount);
button.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
ll.removeView(findViewById(v.getId() - 1000));
}
});
tr.addView(button);
sCount++;
return tr;
}
LinearLayout having the property Orientation to align control either Vertically/Horizontally
so just set Orientation of the same
http://developer.android.com/reference/android/widget/LinearLayout.html
mLayout = (LinearLayout) findViewById(R.id.linearLayout);
mLayout.setOrientation(LinearLayout.HORIZONTAL);
Updated
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="schemas.android.com/apk/res/android";
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/editText"
android:layout_width="293dp"
android:layout_height="wrap_content" >
<requestFocus /> </EditText>
<Button android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add+" />
</LinearLayout>

How an Edit Text can be created dynamically in Android

I am new to android programming and I have a problem of creating text fields dynamically;
I want to create a view in which there is a button named "Create text fields" and two Edit Text one Edit Text name is ROW and the second edit text name is COLUMN. As a user enters numbers in the both Edit Text let say ROW =2 and COLUMN =3 and press the button "Create text fields" it may create 6 Edit Text below the button of "Create text fields". These 6-edit text should be positioned in 2 rows and 3 columns like below
EditText-1 EditText-2 EditText-3
EditText-1 EditText-2 EditText-3
setContentView(R.layout.main);
LinearLayout ll = (LinearLayout)findViewById(R.id.ll);
Display display = ((WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth()/3;
for(int i=0;i<2;i++){
LinearLayout l = new LinearLayout(this);
l.setOrientation(LinearLayout.HORIZONTAL);
for(int j=0;j<3;j++){
EditText et = new EditText(this);
LayoutParams lp = new LayoutParams(width,LayoutParams.WRAP_CONTENT);
l.addView(et,lp);
}
ll.addView(l);
}
use the above code in your onCreate() where "main" is xml file. and you can replace i<2 and j<3 with values of edittext 1 & 2.
sample main.xml which i am using is below::
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ll"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/et1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/et2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
public class DynamicEditTextActivity extends Activity {
private EditText row, column;
private Button submit;
private LinearLayout main, matrix;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
main = (LinearLayout) findViewById(R.id.mainlayout);
row = (EditText) findViewById(R.id.row);
column = (EditText) findViewById(R.id.column);
matrix = (LinearLayout) findViewById(R.id.matrix);
matrix.setOrientation(LinearLayout.VERTICAL);
submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(generate);
}
OnClickListener generate = new OnClickListener() {
public void onClick(View v) {
matrix.removeAllViews();
int rows = Integer.parseInt(row.getText().toString());
int cols = Integer.parseInt(column.getText().toString());
for (int i = 0; i < rows; i++) {
LinearLayout layout = new LinearLayout(
DynamicEditTextActivity.this);
layout.setOrientation(LinearLayout.HORIZONTAL);
for (int j = 0; j < cols; j++) {
TextView text = new TextView(DynamicEditTextActivity.this);
text.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
text.setText((j+1) + " ");
text.setTextColor(Color.RED);
layout.addView(text);
}
matrix.addView(layout);
}
}
};
This is how you create an EditText box dynamically...
Hope this is useful...
This is just an example... You can reference this...
EditText t = new EditText(myContext);
t.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
layout.addView(t);
final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final EditText edit_text = new EditText(this);
edit_text.setLayoutParams(lparams);
edit_text.setText("New text: " + text);
try like this function
public static void display(final Activity activity, Button btn) {
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout scrollViewlinerLayout = activity.findViewById(R.id.linearLayoutForm);
java.util.ArrayList<String> msg = new ArrayList<String>();
for (int i = 0; i < scrollViewlinerLayout.getChildCount(); i++)
{
LinearLayout innerLayout = (LinearLayout) scrollViewlinerLayout.getChildAt(i);
EditText edit = innerLayout.findViewById(R.id.editDescricao);
msg.add(edit.getText().toString().trim());
int childcount = scrollViewlinerLayout.getChildCount();
for( i =0 ; i < childcount; i++){
View view = scrollViewlinerLayout.getChildAt(i);
}
}
Toast t = Toast.makeText(activity.getApplicationContext(), msg.toString(), Toast.LENGTH_SHORT);
t.show();
}
}); }

Categories

Resources