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.
Related
I simply want to know . is there a way to create an id's using for loop
I have 10 buttons in xml . there id's are button1,button2,button3... button10 Now i create an Array of Button in java class and do it like this
public class Menu extends Activity
{
Button[] arrayButton=new Button[10];
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
init();
}
private void init()
{
for(int i=1 ; i<9 ; i++)
{
String abc = "but"+String.valueof(i);
int x = Integer.parseInt(abc);
Log.d("abc", abc);
Log.d("x", String.valueOf(x) );
//arrayButton[i] = (Button) findViewById(R.id.x); // giving error
//arrayButton[i].setText("Hello:");
}
}
}
I want to know how can i do this kind of work . Getting all button using for loop to make my work faster and some time when i want to set the text of all the buttons .
use getResources().getIdentifier like
String abc = "but"+String.valueof(i);
int resID = getResources().getIdentifier(abc, "id", getPackageName());
arrayButton[i] = (Button) findViewById(resID );
arrayButton[i].setText("Hello:");
i.e. simply rewrite init() method as
private void init()
{
for(int i=1 ; i<9 ; i++)
{
String abc = "but"+String.valueof(i);
int resID = getResources().getIdentifier(abc, "id", getPackageName());
arrayButton[i] = (Button) findViewById(resID);
arrayButton[i].setText("Hello:");
}
}
Or simple you may use
int[] buttonIDs = new int[] {R.id.but1, R.id.but2, R.id.but3,R.id.but4, ... }
for(int i=0; i<buttonIDs.length; i++) {
Button b = (Button) findViewById(buttonIDs[i]);
b.setText("Hello:" + b.getText().toString());
}
If you already know all the ids, you can simply use:
int [] ids = new int [] {R.id.btn1, R.id.btn2, ...};
Button [] arrayButton = new Button[ids.length];
for(int i=0 ; i < arrayButton.length ; i++)
{
arrayButton[i] = (Button) findViewById(ids[i]);
}
Or if you don't know them, use:
getResources().getIdentifier("btn1","id",getPackageName())
Try this way,hope this will help you to solve your problem.
main.xm
<LinearLayout
android:id="#+id/lnrMain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/button6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/button7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/button8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/button9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/button10"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
MainActvity.java
public class MainActivity extends Activity {
private LinearLayout lnrMain;
private Button[] arrayButton;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lnrMain = (LinearLayout) findViewById(R.id.lnrMain);
arrayButton=new Button[10];
init();
}
private void init()
{
for(int i=0;i<lnrMain.getChildCount() ; i++)
{
arrayButton[i] = (Button) lnrMain.getChildAt(i);
arrayButton[i].setText("Hello:"+(i+1));
}
}
}
You can create a helper void like:
public static int getResourceID(Context mContext, String StrId) {
return mContext.getResources().getIdentifier(StrId, "id", mContext.getPackageName());
}
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!
When I'm trying to get the values to calculate the total I'm unable to get the values, instead getting android.widget.TableRow#4103c468. How can I overcome this situation and more I need to pass those values to another Activity. My code:
public class ProvisionActivity extends Activity {
private TableLayout mTable;
private static int sCount = 0;
Button btnAdd;
String[] pnames = { "provision1", "provision2", "provision3", "provision4",
"provision5" };
String[] pprice = { "45", "85", "125", "15", "198" };
StringBuffer xpenses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnAdd = (Button) findViewById(R.id.button1);
mTable = (TableLayout) findViewById(R.id.tableprovision);
xpenses = new StringBuffer();
btnAdd.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mTable.addView(addRow(pnames, pprice));
for (int i = 0; i < mTable.getChildCount(); i++) {
mTable.getChildAt(i);
System.out.println("Table Row values are "
+ mTable.getChildAt(i));
xpenses = xpenses.append(mTable.getChildAt(i).toString());
System.out
.println("Expense Table Values Are After Storing it in a String variable "
+ xpenses);
}
}
});
}
private TableRow addRow(String[] sname, final String[] sprice) {
TableRow tr = new TableRow(this);
tr.setId(1000 + sCount);
tr.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.FILL_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
TableRow.LayoutParams blparams = new TableRow.LayoutParams(150, 35);
final Spinner spinner = new Spinner(this);
spinner.setLayoutParams(blparams);
spinner.setBackgroundColor(Color.DKGRAY);
ArrayAdapter<String> xtypeadapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, sname);
spinner.setAdapter(xtypeadapter);
tr.addView(spinner);
TableRow.LayoutParams tlparams = new TableRow.LayoutParams(55,
TableLayout.LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(this);
textView.setLayoutParams(tlparams);
textView.setTextColor(Color.BLACK);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
textView.setText(" "
+ sprice[spinner.getSelectedItemPosition()]);
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
tr.addView(textView);
TableRow.LayoutParams blparams1 = new TableRow.LayoutParams(
TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT);
final Button button = new Button(this);
button.setLayoutParams(blparams1);
button.setBackgroundColor(Color.LTGRAY);
button.setText(" - ");
button.setId(2000 + sCount);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mTable.removeView(findViewById(v.getId() - 1000));
}
});
tr.addView(button);
sCount++;
return tr;
}
}
LAYOUT
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="154dp"
android:layout_marginLeft="42dp"
android:text="Total"
android:textColor="#000000" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView1"
android:layout_alignBottom="#+id/textView1"
android:layout_alignParentRight="true"
android:layout_marginRight="80dp"
android:text="TextView"
android:textColor="#000000" />
<TableLayout
android:id="#+id/tableprovision"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="74dp" >
</TableLayout>
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="33dp"
android:text="Expenses "
android:textColor="#000000"
android:textSize="18sp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView3"
android:layout_marginRight="30dp"
android:text="Add" />
</RelativeLayout>
i solved the above issue in the below shown way.. with some modifications to the above code
public class ProvisionActivity extends Activity {
private TableLayout mTable;
private static int sCount = 0;
Button btnAdd, btntot;
TextView tot;
int sum = 0;
String[] pnames = { "provision1", "provision2", "provision3", "provision4",
"provision5" };
String[] pprice = { "45", "85", "125", "15", "195" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnAdd = (Button) findViewById(R.id.button1);
mTable = (TableLayout) findViewById(R.id.tableprovision);
tot = (TextView) findViewById(R.id.textViewsum);
btntot = (Button) findViewById(R.id.buttontotal);
btnAdd.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mTable.addView(addRow(pnames, pprice));
}
});
btntot.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int total = 0;
for (int i = 0; i < mTable.getChildCount(); i++) {
TableRow mRow = (TableRow) mTable.getChildAt(i);
Spinner mspinner = (Spinner) mRow.getChildAt(0);
TextView mTextView = (TextView) mRow.getChildAt(1);
Log.i("mspinner", "" + mspinner.getSelectedItem());
total = total
+ Integer.parseInt(mTextView.getText().toString());
}
System.out.println("Sum of the provision are " + total);
tot.setText("" + total);
}
});
}
private TableRow addRow(String[] sname, final String[] sprice) {
TableRow tr = new TableRow(this);
tr.setId(1000 + sCount);
tr.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
TableRow.LayoutParams blparams = new TableRow.LayoutParams(150, 35);
final Spinner spinner = new Spinner(this);
spinner.setLayoutParams(blparams);
spinner.setBackgroundColor(Color.DKGRAY);
ArrayAdapter<String> xtypeadapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, sname);
spinner.setAdapter(xtypeadapter);
tr.addView(spinner);
TableRow.LayoutParams tlparams = new TableRow.LayoutParams(55,
TableLayout.LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(this);
textView.setLayoutParams(tlparams);
textView.setTextColor(Color.BLACK);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
private boolean flag = false;
public void onItemSelected(AdapterView<?> spin, View arg1,
int position, long arg3) {
if (flag) {
flag = true;
return;
}
textView.setText(sprice[position]);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
tr.addView(textView);
TableRow.LayoutParams blparams1 = new TableRow.LayoutParams(
TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT);
final Button button = new Button(this);
button.setLayoutParams(blparams1);
button.setBackgroundColor(Color.LTGRAY);
button.setText(" - ");
button.setId(2000 + sCount);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sCount--;
mTable.removeView(findViewById(v.getId() - 1000));
}
});
tr.addView(button);
sCount++;
return tr;
}
}
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();
}
}); }
i want to add row dynamically to my tableview like iphone with two TextViews and one EditText for Editing data to webservices also i want Scrolling tableview . ineed som sample code so i can proceed or if any have any alternet solution plz suggest me .
I have this Json and want to bind json data with each row in tableview
try {
json = new JSONObject(status);
getArray_Meter_Reading = new JSONArray();
getArray_Meter_Reading = json.getJSONArray("meterReadings");
if (getArray_Meter_Reading.length() == 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(
NewTransaction.this);
builder.setTitle("WARNING");
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setMessage("No Meters Found");
builder.setPositiveButton("ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
});
AlertDialog diag = builder.create();
diag.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Plz help to achive this im new to android so i need help
Can any buddy have solution for this .
Thanks in advance
public View getView(final int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
EditText ed_Current = (EditText) view.findViewById(R.id.ed_Current);
ed_Current.setTag(position);
ed_Current.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View arg0, boolean arg1) {
if (v == null) {
v = arg0;
int tag = (Integer) arg0.getTag();
Caption = (EditText) arg0;
previous_Meter_Reading = new HashMap<String, String>();
previous_Meter_Reading = c.get(tag);
String getPreviousReading = previous_Meter_Reading
.get("previousMeterReading");
String CumulativeIndex = previous_Meter_Reading
.get("Cumulative");
previousMeterReading = Integer.parseInt(getPreviousReading);
Cumulative = Integer.parseInt(CumulativeIndex);
}
Toast.makeText(context, "getPrevious" + previousMeterReading,
Toast.LENGTH_SHORT);
Toast.makeText(context, "Cumulative" + Cumulative,
Toast.LENGTH_SHORT);
Log.i("Hello", "getPrevious" + previousMeterReading);
Log.i("Hello1", "Cumulative" + Cumulative);
if (v != arg0) {
if (!Caption.getText().toString().equals("")
&& Cumulative == 1) {
int tag = ((Integer) arg0.getTag());
CurrentMeterReading = Integer.valueOf(Caption.getText()
.toString());
CurrentReading =new HashMap<String, Integer>();
CurrentReading.put("Tag"+tag,CurrentMeterReading);
getReading.add(CurrentReading);
Log.i("Curr", "Current" + CurrentMeterReading);
Log.i("Pre", "previous" + previousMeterReading);
if (CurrentMeterReading < previousMeterReading) {
AlertDialog.Builder builder = new AlertDialog.Builder(
context);
builder.setTitle("WARNING");
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setMessage("Please Enter UserName");
builder.setPositiveButton("ok",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
// Caption.requestFocus();
}
});
AlertDialog diag = builder.create();
diag.show();
// Caption.requestFocus();
// v = null;
// Caption = null;
}else if(Cumulative==0 && !Caption.getText().toString().equals("")){
//int tag1 = ((Integer) arg0.getTag());
CurrentMeterReading = Integer.valueOf(Caption.getText()
.toString());
CurrentReading =new HashMap<String, Integer>();
CurrentReading.put("Tag"+tag,CurrentMeterReading);
getReading.add(CurrentReading);
}
}
v = null;
Caption = null;
}
}
});
return view;
}
Layout:-
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="154dp"
android:layout_marginLeft="42dp"
android:text="Total"
android:textColor="#000000" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView1"
android:layout_alignBottom="#+id/textView1"
android:layout_alignParentRight="true"
android:layout_marginRight="80dp"
android:text="TextView"
android:textColor="#000000" />
<TableLayout
android:id="#+id/tableprovision"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="74dp" >
</TableLayout>
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="33dp"
android:text="Expenses "
android:textColor="#000000"
android:textSize="18sp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView3"
android:layout_marginRight="30dp"
android:text="Add" />
</RelativeLayout>
After creating Layout Then First You need to retrieve the json data
then store it in the String[] assign the values to the table according
to your requirement.For example go through the following.
Activity :-
public class ProvisionActivity extends Activity {
private TableLayout mTable;
private static int sCount = 0;
Button btnAdd;
String[] pnames = { "provision1", "provision2", "provision3", "provision4",
"provision5" };
String[] pprice = { "45", "85", "125", "15", "198" };
StringBuffer xpenses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnAdd = (Button) findViewById(R.id.button1);
mTable = (TableLayout) findViewById(R.id.tableprovision);
xpenses = new StringBuffer();
btnAdd.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mTable.addView(addRow(pnames, pprice));
for (int i = 0; i < mTable.getChildCount(); i++) {
mTable.getChildAt(i);
System.out.println("Table Row values are "
+ mTable.getChildAt(i));
xpenses = xpenses.append(mTable.getChildAt(i).toString());
System.out
.println("Expense Table Values Are After Storing it in a String variable "
+ xpenses);
}
}
});
}
private TableRow addRow(String[] sname, final String[] sprice) {
TableRow tr = new TableRow(this);
tr.setId(1000 + sCount);
tr.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.FILL_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
TableRow.LayoutParams blparams = new TableRow.LayoutParams(150, 35);
final Spinner spinner = new Spinner(this);
spinner.setLayoutParams(blparams);
spinner.setBackgroundColor(Color.DKGRAY);
ArrayAdapter<String> xtypeadapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, sname);
spinner.setAdapter(xtypeadapter);
tr.addView(spinner);
TableRow.LayoutParams tlparams = new TableRow.LayoutParams(55,
TableLayout.LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(this);
textView.setLayoutParams(tlparams);
textView.setTextColor(Color.BLACK);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
textView.setText(" "
+ sprice[spinner.getSelectedItemPosition()]);
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
tr.addView(textView);
TableRow.LayoutParams blparams1 = new TableRow.LayoutParams(
TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT);
final Button button = new Button(this);
button.setLayoutParams(blparams1);
button.setBackgroundColor(Color.LTGRAY);
button.setText(" - ");
button.setId(2000 + sCount);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mTable.removeView(findViewById(v.getId() - 1000));
}
});
tr.addView(button);
sCount++;
return tr;
}
}