How an Edit Text can be created dynamically in Android - 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();
}
}); }

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 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.

Adding Table rows Dynamically in Android

I am trying to create a layout where I need to add table rows dynamically. Below is the table layout xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/displayLinear"
android:background="#color/background_df"
android:orientation="vertical" >
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/display_row"
android:layout_marginTop="280dip" >
</TableLayout>
The activity file where rows are being added dynamically is
public void init(){
menuDB = new MenuDBAdapter(this);
ll = (TableLayout) findViewById(R.id.displayLinear);
TableRow row=(TableRow)findViewById(R.id.display_row);
for (int i = 0; i <2; i++) {
checkBox = new CheckBox(this);
tv = new TextView(this);
addBtn = new ImageButton(this);
addBtn.setImageResource(R.drawable.add);
minusBtn = new ImageButton(this);
minusBtn.setImageResource(R.drawable.minus);
qty = new TextView(this);
checkBox.setText("hello");
qty.setText("10");
row.addView(checkBox);
row.addView(minusBtn);
row.addView(qty);
row.addView(addBtn);
ll.addView(row,i);
}
}
But when I run this, I am getting below error
08-13 16:27:46.437: E/AndroidRuntime(23568): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.roms/com.example.roms.DisplayActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
I understand that this is due to command ll.addView(row,i); but when I remove this its adding all stuff in a single row rather tan creating a new row for next item. I tried with giving index too as row.addView(addBtn,i) but still its not populating correctly. Please advise. Thanks.
Create an init() function and point the table layout.
Then create the needed rows and columns.
public void init() {
TableLayout stk = (TableLayout) findViewById(R.id.table_main);
TableRow tbrow0 = new TableRow(this);
TextView tv0 = new TextView(this);
tv0.setText(" Sl.No ");
tv0.setTextColor(Color.WHITE);
tbrow0.addView(tv0);
TextView tv1 = new TextView(this);
tv1.setText(" Product ");
tv1.setTextColor(Color.WHITE);
tbrow0.addView(tv1);
TextView tv2 = new TextView(this);
tv2.setText(" Unit Price ");
tv2.setTextColor(Color.WHITE);
tbrow0.addView(tv2);
TextView tv3 = new TextView(this);
tv3.setText(" Stock Remaining ");
tv3.setTextColor(Color.WHITE);
tbrow0.addView(tv3);
stk.addView(tbrow0);
for (int i = 0; i < 25; i++) {
TableRow tbrow = new TableRow(this);
TextView t1v = new TextView(this);
t1v.setText("" + i);
t1v.setTextColor(Color.WHITE);
t1v.setGravity(Gravity.CENTER);
tbrow.addView(t1v);
TextView t2v = new TextView(this);
t2v.setText("Product " + i);
t2v.setTextColor(Color.WHITE);
t2v.setGravity(Gravity.CENTER);
tbrow.addView(t2v);
TextView t3v = new TextView(this);
t3v.setText("Rs." + i);
t3v.setTextColor(Color.WHITE);
t3v.setGravity(Gravity.CENTER);
tbrow.addView(t3v);
TextView t4v = new TextView(this);
t4v.setText("" + i * 15 / 32 * 10);
t4v.setTextColor(Color.WHITE);
t4v.setGravity(Gravity.CENTER);
tbrow.addView(t4v);
stk.addView(tbrow);
}
}
Call init function in your onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
init();
}
Layout file like:
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#3d455b"
android:layout_alignParentLeft="true" >
<HorizontalScrollView
android:id="#+id/hscrll1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<RelativeLayout
android:id="#+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_gravity="center"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TableLayout
android:id="#+id/table_main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" >
</TableLayout>
</RelativeLayout>
</HorizontalScrollView>
</ScrollView>
Will look like:
You shouldn't be using an item defined in the Layout XML in order to create more instances of it. You should either create it in a separate XML and inflate it or create the TableRow programmaticaly. If creating them programmaticaly, should be something like this:
public void init(){
TableLayout ll = (TableLayout) findViewById(R.id.displayLinear);
for (int i = 0; i <2; i++) {
TableRow row= new TableRow(this);
TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
row.setLayoutParams(lp);
checkBox = new CheckBox(this);
tv = new TextView(this);
addBtn = new ImageButton(this);
addBtn.setImageResource(R.drawable.add);
minusBtn = new ImageButton(this);
minusBtn.setImageResource(R.drawable.minus);
qty = new TextView(this);
checkBox.setText("hello");
qty.setText("10");
row.addView(checkBox);
row.addView(minusBtn);
row.addView(qty);
row.addView(addBtn);
ll.addView(row,i);
}
}
You also can, as Fredigato said, declare a RelativeLayout in a separate Layout file. Then instantiate it using:
for(int i = 0; i < 6; i ++){
LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout row = (RelativeLayout) inflater.inflate(R.layout.table_view,null);
quizesTableLayout.addView(row,i);
}
In this approach you can easily design one custom row using XML and reuse it.
Now, to be able to change the children views in the instantiated RelativeLayout. You can call row.childAt(index).
So lets say you have a TextView in the RelativeLayout, you can use:
TextView tv = (TextView) row.childAt(0);
tv.setText("Text");
change code of init like following,
public void init(){
menuDB = new MenuDBAdapter(this);
ll = (TableLayout) findViewById(R.id.displayLinear);
ll.removeAllViews()
for (int i = 0; i <2; i++) {
TableRow row=(TableRow)findViewById(R.id.display_row);
checkBox = new CheckBox(this);
tv = new TextView(this);
addBtn = new ImageButton(this);
addBtn.setImageResource(R.drawable.add);
minusBtn = new ImageButton(this);
minusBtn.setImageResource(R.drawable.minus);
qty = new TextView(this);
checkBox.setText("hello");
qty.setText("10");
row.addView(checkBox);
row.addView(minusBtn);
row.addView(qty);
row.addView(addBtn);
ll.addView(row,i);
}
Activity
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableLayout
android:id="#+id/mytable"
android:layout_width="match_parent"
android:layout_height="match_parent">
</TableLayout>
</HorizontalScrollView>
Your Class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testtable);
table = (TableLayout)findViewById(R.id.mytable);
showTableLayout();
}
public void showTableLayout(){
Date date = new Date();
int rows = 80;
int colums = 10;
table.setStretchAllColumns(true);
table.bringToFront();
for(int i = 0; i < rows; i++){
TableRow tr = new TableRow(this);
for(int j = 0; j < colums; j++)
{
TextView txtGeneric = new TextView(this);
txtGeneric.setTextSize(18);
txtGeneric.setText( dateFormat.format(date) + "\t\t\t\t" );
tr.addView(txtGeneric);
/*txtGeneric.setHeight(30); txtGeneric.setWidth(50); txtGeneric.setTextColor(Color.BLUE);*/
}
table.addView(tr);
}
}
You can use an inflater with TableRow:
for (int i = 0; i < months; i++) {
View view = getLayoutInflater ().inflate (R.layout.list_month_data, null, false);
TextView textView = view.findViewById (R.id.title);
textView.setText ("Text");
tableLayout.addView (view);
}
Layout:
<TableRow
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_centerInParent="true"
android:gravity="center_horizontal"
android:paddingTop="15dp"
android:paddingRight="15dp"
android:paddingLeft="15dp"
android:paddingBottom="10dp"
>
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:gravity="center"
/>
</TableRow>
public Boolean addArtist(String artistName){
SQLiteDatabase db= getWritableDatabase();
ContentValues data=new ContentValues();
data.put(ArtistMaster.ArtistDetails.COLUMN_ARTIST_NAME,artistName);
long id = db.insert(ArtistMaster.ArtistDetails.TABLE_NAME,null,data);
if(id>0){
return true;
}else{
return false;
}
}
I am trying the above code with modification as per my requirement. The table is created properly. Bu the problem is when I am opening the activity 1st time, the table is not displaying. It is displaying 2nd time only.
My code is
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getSupportActionBar().hide();
setContentView(R.layout.activity_aggre_ascendingorder);
drawerLayout = findViewById(R.id.drawer_layout);
init();
}
#SuppressLint("ResourceType")
public void init() {
stk = (TableLayout) findViewById(R.id.table_main);
TableRow tbrow0 = new TableRow(this);
TextView tv0 = new TextView(this);
tv0.setText("Actual Values ");
tv0.setWidth(330);
tv0.setGravity(Gravity.CENTER);
tv0.setTextColor(Color.WHITE);
tv0.setTextSize(12);
tv0.setBackgroundResource(R.drawable.border4);
tbrow0.addView(tv0);
TextView tv1 = new TextView(this);
tv1.setText("Meter Values ");
tv1.setWidth(330);
tv1.setGravity(Gravity.CENTER);
tv1.setTextColor(Color.WHITE);
tv1.setTextSize(12);
tv1.setBackgroundResource(R.drawable.border4);
tbrow0.addView(tv1);
TextView tv2 = new TextView(this);
tv2.setText("Error ");
tv2.setWidth(315);
tv2.setGravity(Gravity.CENTER);
tv2.setTextColor(Color.WHITE);
tv2.setTextSize(12);
tv2.setBackgroundResource(R.drawable.border4);
tbrow0.addView(tv2);
Intent z = getIntent();
input1 = z.getIntExtra(EDIT, 1);
input2 = z.getIntExtra(TEXT, 1);
if (input2 == 0) {
x = 400;
} else {
x = input1 / input2;
}
stk.addView(tbrow0);
try {
for (int i = 0; i < x + 1; i++) {
TableRow tbrow = new TableRow(this);
final EditText t1v = new EditText(this);
t1v.setId(1);
if (input2 == 0) {
t1v.setHint("");
} else {
t1v.setText("" + i * input2);
}
final EditText t2v;
TextView t3v = null;
t1v.setTextColor(Color.BLACK);
t1v.setGravity(Gravity.CENTER);
t1v.setTextSize(12);
t1v.setInputType(InputType.TYPE_CLASS_NUMBER);
t1v.setBackgroundResource(R.drawable.border);
t2v = new EditText(this);
t2v.setHint("");
t2v.setTextColor(Color.BLACK);
t2v.setGravity(Gravity.CENTER);
t2v.setTextSize(12);
t2v.setInputType(InputType.TYPE_CLASS_NUMBER);
t2v.setBackgroundResource(R.drawable.border);
t3v = new TextView(this);
t3v.setHint("");
t3v.setTextColor(Color.BLACK);
t3v.setGravity(Gravity.CENTER);
t3v.setTextSize(12);
t3v.setBackgroundResource(R.drawable.border);
String stb = "0,0,0";
if((Integer.parseInt(Prefs.getString("aggasstabLength",""))-1) > i){
stb = Prefs.getString("aggasstabVal_" + (i + 1), "");
}
//t1v.setText(stb.split(",")[0]);
t2v.setText(stb.split(",")[1]);
t3v.setText(stb.split(",")[2]);
tbrow.addView(t1v);
tbrow.addView(t2v);
tbrow.addView(t3v);
stk.addView(tbrow);
`
Can you clear me what is the mistake I am doing on this

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>

Categories

Resources