How to add and remove linear layout by button click - android

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!

Related

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

"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

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);

Dynamicaly add layout in layout?

I have a layout and i need to insert into in some kind of blocks with text - like comments date, name, text. Is there a way to use it like this
for (int r=0; r<10;r++) {
TextView t1=(TextView) findviewbyid(R.id.text1);
t1="BlaBla";
mainlayout.add(commentLayout);
}
So i get something like listview but without adapter and etc.
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:id="#+id/comm_name"
android:layout_marginLeft="20dp"
android:layout_marginTop="24dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Date"
android:id="#+id/comm_date"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_margin="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="60dp"
android:layout_marginLeft="20dp"
android:id="#+id/comm_text" />
you can do it, but the way you are doing it will throw an exception, because findViewById returns always the same object, and after the first iteration t1 has already a parent. You should create a new instance of the TextView programmatically, at every iteration.
Try adding views dynamically in linear layout which is inside scroll view.
Try this code.I know it is not exact solution.But,Hope it gives you some idea.
public class MainActivity extends Activity {
ScrollView scrollview;
LinearLayout linearLayout;
LinearLayout.LayoutParams layoutParams;
static int i;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scrollview = (ScrollView)findViewById(R.id.scrollview);
linearLayout = (LinearLayout)findViewById(R.id.linearlayout);
Button button = (Button)findViewById(R.id.button);
layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
TextView view = new TextView(MainActivity.this);
view.setText(++i+" view");
linearLayout.addView(view, layoutParams);
}
});
}}
Use Following approach
Looping to add dynamically Views to Linear Layout
TextView textView1, textView2;
LinearLayout completeLinearLayout = (LinearLayout) findViewById(R.id.ll);
for (int i = 0; i < 10; i++) {
textView1 = new TextView(Activity.this);
textView2 = new TextView(Activity.this);
String name1 = "xyz";
String name2 = "abc"
completeLinearLayout.addView(textView1);
completeLinearLayout.addView(textView2);
setTextViewParam(textView1, name1);
setTextViewParam(textView2, name2);
}
Method to set TextView Parameters Dynamically
private void setTextViewParam(TextView tv, String text) {
LayoutParams textLayoutParams = new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
textLayoutParams.setMargins(5, 0, 0, 0);
tv.setGravity(Gravity.LEFT);
tv.setText(text);
tv.setTextSize(13);
tv.setTextColor(Color.BLACK);
tv.setLayoutParams(textLayoutParams);
}
Now you can customize the views according to need and container as well.
Happy Coding!!
So, this code works exactlay as i need.
Is there anything wrong with it??
public class InflateView extends Activity {
LinearLayout lLayout;
TextView t,f;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
lLayout = (LinearLayout)findViewById(R.id.layout1);
for (int i=0;i<10;i++)
{
RelativeLayout tv = (RelativeLayout)inflater.inflate(R.layout.text, null);
lLayout.addView(tv);
t = (TextView) tv.findViewById(R.id.ttt);
t.setText("aaaaaaa" + i) ;
f = (TextView) tv.findViewById(R.id.textView);
f.setText(String.valueOf(i));
}
}}

How to rename the checkbox text which is dynamically created in android

In my code, If we need particular number of checkbox or radio button, by giving the count value in EditText, we can get the particular number of checkbox. But It is displaying the checkbox with random alphabets from a to z. But, I need it to change/rename specifically based on my need. Your help is highly appreciated. Thanks in advance. Here is my code.
XML Layout:
<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"
tools:context=".MainActivity" >
<EditText
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="12dp"
android:layout_marginTop="05dp"
android:hint="Enter Text" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button1"
android:layout_alignBottom="#+id/button1"
android:layout_alignParentRight="true"
android:layout_marginRight="05dp"
android:text="Edit Text" />
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/button2"
android:text="Check Box" />
<Button
android:id="#+id/button5"
android:layout_width="98dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/button4"
android:text="Radio Button" />
<EditText
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button4"
android:layout_alignParentLeft="true"
android:hint="Enter no" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/button5"
android:gravity="left"
android:orientation="vertical" />
<RadioGroup
android:id="#+id/radiogroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout"
android:layout_centerHorizontal="true"
android:orientation="vertical" />
</RelativeLayout>
Main Activity
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.*;
import android.widget.LinearLayout.*;
import java.util.Random;
public class MainActivity extends Activity {
private LinearLayout mLayout;
private EditText mEditText;
private Button mButton;
Button abutton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLayout = (LinearLayout) findViewById(R.id.linearLayout);
mEditText = (EditText) findViewById(R.id.button1);
mButton = (Button) findViewById(R.id.button2);
mButton.setOnClickListener(onClick());
TextView textView = new TextView(this);
textView.setText("New text");
final EditText button2=(EditText)findViewById(R.id.button3);
findViewById(R.id.button5).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int number=Integer.parseInt(button2.getText().toString());
addRadioButtons(number);
}
});
findViewById(R.id.button4).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int number=Integer.parseInt(button2.getText().toString());
addCheckBox(number);
}
});
}
public void addRadioButtons(int number) {
for (int row = 0; row < 1; row++) {
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
for (int i = 1; i <= number; i++) {
RadioButton rdbtn = new RadioButton(this);
rdbtn.setId((row * 2) + i);
rdbtn.setText("Radio " + rdbtn.getId());
ll.addView(rdbtn);
}
((ViewGroup) findViewById(R.id.radiogroup)).addView(ll);
}
}
public void addCheckBox(int number) {
//Edited Here
String[] names = {"Sanket", "Kumar", "Rahul"};
for (int row = 0; row < 1; row++) {
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
for (int i = 1; i <= number; i++) {
CheckBox ch = new CheckBox(this);
ch.setId((row * 2) + i);
//ch.setText(randomString(3));
ch.setText(names[i]);
ll.addView(ch);
}
((ViewGroup) findViewById(R.id.radiogroup)).addView(ll);
}
}
private String randomString(int len) {
char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
StringBuilder sb = new StringBuilder(len);
Random random = new Random();
for (int i = 0; i < 3; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
String output = sb.toString();
System.out.println(output);
return sb.toString();
}
private OnClickListener onClick() {
return new OnClickListener() {
#Override
public void onClick(View v) {
mLayout.addView(createNewTextView(mEditText.getText().toString()));
}
};
}
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("" + text);
return textView;
}
}
make an String Array like
String[] names = {"Sanket", "Kumar", ......};
then in the code
for (int i = 1; i <= number; i++) {
CheckBox ch = new CheckBox(this);
ch.setId((row * 2) + i);
// Replace the line with
//ch.setText(randomString(3));
// with this line
ch.setText(names[i]);
ll.addView(ch);
}
In your addCheckBox() method, you have set the text of checkbox to randomstring (ch.setText(randomString(3))). Just change this line as your choice just like this ch.setText("Checkbox" + i).
for (int i = 1; i <= number; i++) {
CheckBox ch = new CheckBox(this);
ch.setId((row * 2) + i);
ch.setText(randomString(3)); // Change Here
ll.addView(ch);
}
change the text of checkBox in ch.setText that you want to be
Ok.. I really don't understand... When you create the checkbox you set its text to ch.setText(randomString(3)); Why would you do that if you want specific text ?
Random != Specific.
Just write something like this:
ch.setText("Your desired text");
Or you could create an
String[] checkBoxFruits= {"apple","mango","kiwi"};
and then set the text something like:
for ( int i=0; i<numberOfCheckBoxes; i++ )
{
CheckBox ch = new CheckBox(this);
ch.setId((row * 2) + i);
ch.setText(checkBoxFruits[i]);
ll.addView(ch);
}
public void addCheckBox(int number) {
String[] names = {"Sanket", "Kumar", "Eagle"};
for (int row = 0; row < 1; row++) {
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
for (int i = 1; i <= number; i++) {
CheckBox ch = new CheckBox(this);
ch.setId((row * 2) + i);
if(i != names.length)
ch.setText(names[i-1]);
else
ch.setText("New name");
ll.addView(ch);
}
((ViewGroup) findViewById(R.id.radiogroup)).addView(ll);
}
}
Use above code.. And check it...
I think you should try using RadioGroup and create an array of strings with which can easily use .setText method to run a loop throgh all the Radio Buttons.

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