Delete button in TableRow - android

I have an Edit button in my header. And I populating my TableLayout in a loop. In The loop I am inflating a Delete button.
Following is the code I have used :
MainActivity :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cookbooklist);
btnHeaderEdit = (Button)findViewById(R.id.btnEdit);
btnHeaderEdit.setVisibility(View.VISIBLE);
delete_button = (View)findViewById(R.id.btnDelete);
listTable = (TableLayout)findViewById(R.id.cookbookListTable);
btnHeaderEdit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
delete_button.getTag();
delete_button.setVisibility(View.VISIBLE);
}
});
for(int i=0;i<=10;i++)
{
// Row to display news title
final TableRow newsRow = new TableRow(this);
newsRow.setMinimumHeight(200);
newsRow.setClickable(true);
newsRow.setTag(i);
newsRow.setBackgroundColor(Color.WHITE);
// Some other views
//create inflater
LayoutInflater inflater = getLayoutInflater();
delete_button = inflater.inflate(R.layout.deletebutton,
(ViewGroup) newsRow, false);
delete_button.setTag(i);
delete_button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
listTable.removeView(newsRow);
}
});
//Add views in table
newsRow.addView(delete_button);
listTable.addView(newsRow);
}
}
delebutton.xml :
<Button
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/btnDelete"
android:layout_width="100dip"
android:visibility="invisible"
android:layout_height="40dip"
android:padding="10sp"
android:text="Delete">
</Button>
Question :
The problem I am facing is that when I click the Edit button in header, Delete button appears only in the last row. When I setVisibility of Delete button to Visible in layout, it appears in all rows. But I want it to be invisible in the start. And on clicking the Edit button it should appear in all rows. I Am wondering how to achieve that.
Can someone assist me? Let me know if more code is needed.
Thanks
The problem I am facing is that when

Hi Stone i think you have to use a boolean flag. which wil determine whether the delete button should be visible or not. Try with the following example. Its working fine. On click of edit button if delete buttons are invisible i make all as visible and viceversa. Try the following code.
See My Working Example
Sample2.java
import java.util.ArrayList;
import java.util.Iterator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Sample2 extends Activity {
boolean showDeleteButtonFlag = false;
Button delteBtn2 = null;
Button delteBtn1 = null;
Button editBtn = null;
ArrayList<Button> deleteButtonList = new ArrayList<Button>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.tablerow);
delteBtn1 = (Button) findViewById(R.id.delete1);
delteBtn2 = (Button) findViewById(R.id.delete2);
// add all delete buttons buttons to the array list
deleteButtonList.add(delteBtn1);
deleteButtonList.add(delteBtn2);
editBtn = (Button) findViewById(R.id.edit);
setVisibilityOfDeleteButtons();
editBtn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// if delete button is visible make it as invisible and viceversa
showDeleteButtonFlag = !showDeleteButtonFlag;
setVisibilityOfDeleteButtons();
}
});
}
void setVisibilityOfDeleteButtons(){
if(showDeleteButtonFlag){
Iterator<Button> itr =deleteButtonList.iterator();
while(itr.hasNext()){
itr.next().setVisibility(View.VISIBLE);
}
}else{
Iterator<Button> itr =deleteButtonList.iterator();
while(itr.hasNext()){
itr.next().setVisibility(View.INVISIBLE);
}
}
}
}
tablerow.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TableRow>
<Button
android:id="#+id/edit"
android:layout_width="100dip"
android:layout_height="60dip"
android:text="Edit" />
<Button
android:id="#+id/delete1"
android:layout_width="100dip"
android:layout_height="60dip"
android:text="Delete" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password:"
android:textColor="#ffffff"
android:textStyle="bold" />
<Button
android:id="#+id/delete2"
android:layout_width="100dip"
android:layout_height="60dip"
android:text="Delete" />
</TableRow>
</TableLayout>

Related

how to change the header dynamically in android by clicking on any view like textview or button?

i need to change my text in the header when i click on the textview , i made my best effort to do somethings, but i m not getting the result
i will post the code and if anyone can help me out and tell me where i m going wrong , it will be of great help
this is my results.xml where my listview and the header with textview(the one which is to be set inside the java code) is there ,
<?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="#color/White" >
<RelativeLayout
android:id="#+id/rltHeader"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#27acc3" >
<ImageView
android:id="#+id/imgBackReuslt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:onClick="onClick"
android:src="#drawable/arrow" />
<TextView
android:id="#+id/txtHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="#color/White"
android:textSize="20dp"
android:textStyle="bold" />
</RelativeLayout>
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/rltHeader"
android:layout_marginRight="5dp"
android:divider="#color/LightGray"
android:dividerHeight="4px" >
</ListView>
</RelativeLayout>
this is my another xml where i have displayed how the listviews every Row will appear
<?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" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="100dp">
<RelativeLayout
android:id="#+id/rltRow"
android:layout_width="17dp"
android:layout_height="100dp"
android:layout_alignParentTop="true"
android:background="#drawable/r_list" >
</RelativeLayout>
<ImageView
android:id="#+id/imageView1"
android:layout_width="83dp"
android:layout_height="80dp"
android:layout_alignBottom="#+id/rltRow"
android:layout_alignParentRight="true" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/imageView1"
android:layout_marginLeft="16dp"
android:layout_marginTop="22dp"
android:layout_toRightOf="#+id/rltRow"
android:text="TextView"
android:textColor="#color/Black"
android:textSize="14dp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView2"
android:layout_alignLeft="#+id/textView2"
android:text="TextView"
android:textColor="#color/Black" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/rltRow"
android:layout_alignLeft="#+id/textView2"
android:text="TextView"
android:textColor="#color/Black" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_alignTop="#+id/imageView1"
android:text="TextView"
android:textColor="#color/Black"
android:textSize="12dp" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_below="#+id/textView2"
android:text="TextView"
android:textColor="#color/Black"
android:textSize="12dp" />
</RelativeLayout>
</RelativeLayout>
Now the Java part
This is the List_Activity class where i have displayed all the textviews , there are 6 textviews which when clicked , an activity will appear Results.java , for all the textviews when clicked the same activity Results.java is opened.
package com.demo.Test;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class List_Activity extends Activity {
ImageView iv;
TextView t1, t2, t3, t4, t5, t6;
String header_result = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
//TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list_info);
iv = (ImageView)findViewById(R.id.imgBackReuslt);
t1 = (TextView) findViewById(R.id.text1);
t2 = (TextView) findViewById(R.id.text2);
t3 = (TextView) findViewById(R.id.text3);
t4 = (TextView) findViewById(R.id.text4);
t5 = (TextView) findViewById(R.id.text5);
t6 = (TextView) findViewById(R.id.text6);
t1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// String str = headervalue.getText().toString();
Intent intent = new Intent("com.demo.Test.RESULTS");
intent.putExtra("Results for Self", header_result);
startActivity(intent);
}
});
t2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent("com.demo.Test.RESULTS");
intent.putExtra("Results for Mary(Wife)", header_result);
startActivity(intent);
}
});
t3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// name = t3.getText().toString();
Intent intent = new Intent("com.demo.Test.RESULTS");
intent.putExtra("Results for Alex(Child-1)", header_result);
startActivity(intent);
}
});
t4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent("com.demo.Test.RESULTS");
intent.putExtra("Results for Steven(Child-2)", header_result);
startActivity(intent);
}
});
t5.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent("com.demo.Test.RESULTS");
intent.putExtra("Results for Robert(Father)", header_result);
startActivity(intent);
}
});
t6.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent("com.demo.Test.RESULTS");
intent.putExtra("Results for Diana(Mother)", header_result);
startActivity(intent);
}
});
}
public void onClick(View v) {
super.onBackPressed();
finish();
}
}
Now the main class Results.java , the activity which opens when clicked on the textviews described the previous class
package com.demo.Test;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class Results extends Activity{
TextView header;
ImageView iv;
ListView lv;
String title;
int[] images = { R.drawable.photo_bg, R.drawable.photo_bg,
R.drawable.photo_bg, R.drawable.photo_bg, R.drawable.photo_bg,
R.drawable.b_list, R.drawable.g_list, R.drawable.r_list,
R.drawable.v_list };
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.results);
iv = (ImageView) findViewById(R.id.imgBackReuslt);
header = (TextView) findViewById(R.id.txtHeader);
lv = (ListView) findViewById(R.id.listView1);
Bundle extras = getIntent().getExtras();
if (extras != null) {
title = extras.getString("header_result");
}
ResultsAdapter adapter = new ResultsAdapter(getBaseContext(), doc,
diag, dt, images, docname, diagname);
lv.setAdapter(adapter);
}
so what changes i have to make so that the header text gets changed when i click on the textviews in the List_Activity accordingly
any suggestions are welcomed
Do you mean changing the title of your action bar in each activity?
you can do it by calling this short code
getActionBar().setTitle("the title you want");
you can check this link http://developer.android.com/guide/topics/ui/actionbar.html
Hope it helps, and tell me if you need anything else ;)
according to what you want
t2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent("com.demo.Test.RESULTS");
// this header_result you want pass it textview (txtHeader)
// prefer don't write long description in key of your extra
intent.putExtra("Results for Mary(Wife)", header_result);
startActivity(intent);
}
});
put in your jave file that contain
header = (TextView) findViewById(R.id.txtHeader);
header.setText("YourPassingValue"); // in your case getIntent().getStringExtra("Results for Mary(Wife)");
Refine your code
if you want move from activity yo anther
Intent intent = new Intent (YourFirstActivity.this , SecondActivity.class);
intent.putExtra("Result", PassingVariable); // prefer to make the key of your extra short to make east to call back , PassingVariable is what ever you want pass to the anther activity
startActivity(intent);
in Anther activity get you extra data
in your on create method
String PassedData = getIntent().getStringExtra("Result"); // Result is Your used key
make any thing with passed data
in Your case you want set it on Textview
t2.setText(PassedData);

Android onclick Buttons Sequence

I have 5 buttons every one has letter (Button "H",Button "E"Button "L"Button "L"Button "O") which make the word "HELLO". what I need is to make on click sequence to these buttons so if I click "H" first and "E" second until complete the word the app will do something, But if I click "L" first will give me some error message.
Any Idea to do this sequence?
Thanks
Just have an Array like this:
int[] tracker = new int[5];
and when you click a button, say "H", set tracker[0] = 1;
but when you click a button, say "L", check whether all the previous button values are 1. If yes, then set the corresponding tracker to 1 else, show an error message, and do not make any change to the tracker Array.
Something Like this:
onHClick{
tracker[0] = 1;
}
onEClick{
for(int i=0; i<1; i++){
if(tracker[i] == 0){
//show error message and return;
}else{
tracker[1] = 1;
return;
}
}
}
You can do something like
When activity started you just make other button Enabled = false of something like that. But make the first button Enabled. Don't make the Visible=false.
Now on click of Button "H" make enable Button "E" and so on.
So user will only have to click the button in sequence. Button can not be presses in any random manner.
Try this and let me know that it works or not.
Very Interesting and exactly same to your requirement..check once..
If you give any string other than HELLO also works better.
public class ButtonTest extends Activity
{
private String result="";
String sampleText = "HELLO";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
int noOfBtns = sampleText.length();
LinearLayout ll = (LinearLayout)findViewById(R.id.btnlay);
final TextView tvtext = (TextView)findViewById(R.id.result);
final Button[] btns = new Button[noOfBtns];
for(int i=0;i<noOfBtns;i++)
{
btns[i] = new Button(this);
btns[i].setText(sampleText.substring(i,i+1));
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(btns[i], lp);
final int j = i;
btns[i].setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
System.out.println(j+" "+result.length());
if(j == result.length())
{
result = result+btns[j].getText().toString();
if(sampleText.startsWith(result))
{
tvtext.setText(result);
}
}
else
{
Toast.makeText(getApplicationContext(), "Wrong Button Pressed", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
Layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/result"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:textColor="#fff"/>
<LinearLayout
android:id="#+id/btnlay"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
</LinearLayout>
</LinearLayout>
Try the following
package com.example.buttonsequence;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
ArrayList<Button> buttonList=null;
TextView resultTextView=null;
Button buttons[]=null;
String helloStr="HELLO";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonList=new ArrayList<Button>();
buttons=new Button[5];
this.resultTextView=(TextView) this.findViewById(R.id.result_text);
this.resultTextView.setText("");
buttons[0]=(Button)this.findViewById(R.id.h_button);
buttons[1]=(Button)this.findViewById(R.id.e_button);
buttons[2]=(Button)this.findViewById(R.id.l_button);
buttons[3]=(Button)this.findViewById(R.id.l2_button);
buttons[4]=(Button)this.findViewById(R.id.o_button);
for(int k=0;k<5;k++)
buttons[k].setOnClickListener(onClickListener);
Button button=(Button)this.findViewById(R.id.exit_button);
button.setOnClickListener
(
new OnClickListener()
{
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
}
);
}
OnClickListener onClickListener=new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Button b=(Button)v;
buttonList.add(b);
int size=buttonList.size();
if(size>0)
{
StringBuilder resultBuilder=new StringBuilder();
for(int i=0;i<size;i++)
{
Button tempButton=buttonList.get(i);
if(tempButton==buttons[i])
{
resultBuilder.append(helloStr.charAt(i));
if(i==4)
{
resultTextView.setText(resultBuilder.toString()+" clicked");
buttonList.clear();
}
else
{
resultTextView.setText(resultBuilder.toString()+" clicked");
}
}
else
{
buttonList.remove(i);
Toast.makeText(getApplicationContext(), "No correctly clicked", Toast.LENGTH_SHORT).show();
break;
}
}
}
else
{
resultTextView.setText("Invalid pressed");
}
}
};
}
activity_main.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/h_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="H" />
<Button
android:id="#+id/e_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="E" />
<Button
android:id="#+id/l_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="L" />
<Button
android:id="#+id/l2_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="L" />
<Button
android:id="#+id/o_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="O" />
<TextView
android:id="#+id/result_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
<Button
android:id="#+id/exit_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Exit" />
</LinearLayout>
I don't know exactly your flow but you can try this.
set Tag to each button as its Text, like this.
b.setTag("H");
and than after like this.
Button b;
String name = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s = (String) v.getTag();
name +=s;
if( "HELLO".startsWith(name)){
<VALID>
}else{
<ERROR>
}
}
});
}
check the variable name on each button click with your original word i.e. HELLO like above.

Android Quote app, next and back buttons

Im trying to make a simple quote app, but every time I hit my back button after my next button it will go to the next array and not backwards. Im using an int num to keep track of with quote the user is on.
here is my back button
package me.me.quote;
public class Startme extends Activity {
Random gen= new Random();
int num;
String[] quotes = new String[15];
public void next(View N){
quotes[0]= "Love is timeless";
quotes[1]= "I hate you";
quotes[2]= "arggg!";
quotes[3]= "The end is near";
quotes[4]= "Leave be";
if(num == 5){
num =0;}
TextView text = (TextView) findViewById(R.id.Quote);
text.setText(quotes[num++]);
TextView number = (TextView) findViewById(R.id.Qn);
number.setText(""+num);
}
public void back(View B){
quotes[0]= "Love is timeless";
quotes[1]= "I hate you";
quotes[2]= "arggg!";
quotes[3]= "The end is near";
quotes[4]= "Leave be";
TextView text = (TextView) findViewById(R.id.Quote);
text.setText(quotes[num--]);
TextView number = (TextView) findViewById(R.id.Qn);
number.setText(""+num);}
public void rand(View G) {
num = gen.nextInt(5);
quotes[0]= "Love is timeless";
quotes[1]= "I hate you";
quotes[2]= "arggg!";
quotes[3]= "The end is near";
quotes[4]= "Leave be";
TextView text = (TextView) findViewById(R.id.Quote);
text.setText(quotes[num]);
TextView number = (TextView) findViewById(R.id.Qn);
number.setText(""+num);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.startquotes);
TextView Dark=(TextView)findViewById(R.id.Quote);
Typeface face=Typeface.createFromAsset(getAssets(), "fonts/font1.ttf");
Dark.setTypeface(face);
}
}
//LAYOUT FILE text.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_alignParentTop="true"
android:text="VISIBLE EVERY TIME"
android:visibility="visible" />
<Button
android:id="#+id/back"
android:layout_width="wrap_content"
android:layout_alignParentLeft="true"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:text="NEXT" >
</Button>
<Button
android:id="#+id/next"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:text="BACK" >
</Button>
</RelativeLayout>
///ACTIVITY CLASS
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Test extends Activity {
Button next;
Button back ;
TextView quoteText;
int currentSelectedQuote=0;
String[] quote={"QUOTE1","QUOTE2","QUOTE3","QUOTE4","QUOTE5",};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
quoteText=(TextView)findViewById(R.id.textView);
quoteText.setText(quote[currentSelectedQuote]);
next=(Button)findViewById(R.id.next);
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
currentSelectedQuote++;
if(currentSelectedQuote == 5){
currentSelectedQuote =0;}
quoteText.setText(quote[currentSelectedQuote]);
}
});
back=(Button)findViewById(R.id.back);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(currentSelectedQuote==0)
{
currentSelectedQuote=4;
}
else
{
currentSelectedQuote--;
}
quoteText.setText(quote[currentSelectedQuote]);
// TODO Auto-generated method stub
}
});
}
}

displaying a string on the textview when clicking a button in android

I'm very new to Android development and just started to study.
What I'm trying is to add a button and when that button is pressed a text "my first project" to get displayed in the text view.
With the help of some experts I created the button and text view.
So the button is showing in the simulator but when I click that button nothing happens.
Can anyone please help me with how can I display the text when pressing the button?
.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/txtView"
android:layout_width="150dp"
android:layout_height="150dp"
android:text="#string/hello" />
<Button
android:id="#+id/mybtn"
android:layout_width="50dp"
android:layout_height="30dp" />
<TextView
android:id="#+id/viewwidth"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/viewheight"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
.java
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.view.View;
import android.widget.Toast;
public class NameonbuttonclickActivity extends Activity implements View.OnClickListener {
Button mybtn;
TextView txtView;
String hello;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.main);
super.onCreate(savedInstanceState);
mybtn= new Button(this);
txtView=new TextView(this);
mybtn.setOnClickListener(this);
printmyname();
mybtn = (Button)findViewById(R.id.mybtn);
txtView=(TextView)findViewById(R.id.txtView);
txtView = (TextView)findViewById(R.id.viewwidth);
txtView = (TextView)findViewById(R.id.viewheight);
hello="This is my first project";
//setContentView(mybtn);
// setContentView(R.layout.main);
}
public void onClick(View view){
txtView.setText(hello);
//printmyname();
Toast.makeText(NameonbuttonclickActivity.this, hello, Toast.LENGTH_LONG).show();
}
private void printmyname(){
System.out.println("coming");
}
}
You can do like this:
String hello;
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.main);
super.onCreate(savedInstanceState);
mybtn = (Button)findViewById(R.id.mybtn);
txtView=(TextView)findViewById(R.id.txtView);
txtwidth = (TextView)findViewById(R.id.viewwidth);
hello="This is my first project";
mybtn.setOnClickListener(this);
}
public void onClick(View view){
txtView.setText(hello);
}
Check your textview names. Both are same . You must use different object names and you have mentioned that textview object which is not available in your xml layout file.
Hope this will help you.
First create xml file as follows. Create one textview and a button:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<Button
android:id="#+id/mybutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
The first TextView is created by default. You can leave or remove it if you want.
Next one is to create a button
The next one is TextView where you want to display text.
Now coming to the main activity code...
package com.android.example.simple;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class SimpleActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView textView=(TextView)findViewById(R.id.textView1);
final Button button1 = (Button)findViewById(R.id.mybutton);
//Implement listener for your button so that when you click the
//button, android will listen to it.
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
textView.setText("You clicked the button");
} });
}
}
This is because you DON'T associated the OnClickListener() on the button retrieve from the XML layout.
You don't need to create object because they are already created by the Android system when you inflate XML file (with the Activity.setContentLayout( int resourceLayoutId ) method).
Just retrieve them with the findViewById(...) method.
Just check your code in .java class
You had written below line
mybtn.setOnClickListener(this);
before initializing the mybtn object I mean
mybtn = (Button)findViewById(R.id.mybtn);
just switch this two line or put that line "mybtn.setOnClickListener(this)" after initializing your mybtn object and you will get the answer what you want..
Try this
public void onClick(View view){
txtView.setText("hello");
//printmyname();
Toast.makeText(NameonbuttonclickActivity.this, "hello", Toast.LENGTH_LONG).show();
}
Also in toast use "Hello"
you use this as txtView.setText("hello");
MainActivity.java:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
Button button1;
TextView textView1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1=(Button)findViewById(R.id.button1);
textView1=(TextView)findViewById(R.id.textView1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView1.setText("TextView displayed Successfully");
}
});
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click here" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
public void onCreate(Bundle savedInstanceState)
{
setContentView(R.layout.main);
super.onCreate(savedInstanceState);
mybtn = (Button)findViewById(R.id.mybtn);
txtView=(TextView)findViewById(R.id.txtView);
mybtn .setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
txtView.SetText("Your Message");
}
});
}
Check this:
hello.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View paramView) {
text.setText("hello");
}
});

Add and Remove Views in Android Dynamically?

How do I add and remove views such as TextViews from Android app like on the original stock Android contacts screen where you press a small icon on the right side of a field and it adds or deletes a field which consists of a TextView and an editTextView (from what I can see).
Any examples on how to achieve this?
ViewParents in general can't remove views, but ViewGroups can. You need to cast your parent to a ViewGroup (if it is a ViewGroup) to accomplish what you want.
For example:
View namebar = View.findViewById(R.id.namebar);
((ViewGroup) namebar.getParent()).removeView(namebar);
Note that all Layouts are ViewGroups.
I need the exact same feature described in this question. Here is my solution and source code: https://github.com/laoyang/android-dynamic-views. And you can see the video demo in action here: http://www.youtube.com/watch?v=4HeqyG6FDhQ
Layout
Basically you'll two xml layout files:
A horizontal LinearLayout row view with a TextEdit, a Spinner and an ImageButton for deletion.
A vertical LinearLayout container view with just a Add new button.
Control
In the Java code, you'll add and remove row views into the container dynamically, using inflate, addView, removeView, etc. There are some visibility control for better UX in the stock Android app. You need add a TextWatcher for the EditText view in each row: when the text is empty you need to hide the Add new button and the delete button. In my code, I wrote a void inflateEditRow(String) helper function for all the logic.
Other tricks
Set android:animateLayoutChanges="true" in xml to enable animation
Use custom transparent background with pressed selector to make the buttons visually the same as the ones in the stock Android app.
Source code
The Java code of the main activity ( This explains all the logic, but quite a few properties are set in xml layout files, please refer to the Github source for complete solution):
public class MainActivity extends Activity {
// Parent view for all rows and the add button.
private LinearLayout mContainerView;
// The "Add new" button
private Button mAddButton;
// There always should be only one empty row, other empty rows will
// be removed.
private View mExclusiveEmptyView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.row_container);
mContainerView = (LinearLayout) findViewById(R.id.parentView);
mAddButton = (Button) findViewById(R.id.btnAddNewItem);
// Add some examples
inflateEditRow("Xiaochao");
inflateEditRow("Yang");
}
// onClick handler for the "Add new" button;
public void onAddNewClicked(View v) {
// Inflate a new row and hide the button self.
inflateEditRow(null);
v.setVisibility(View.GONE);
}
// onClick handler for the "X" button of each row
public void onDeleteClicked(View v) {
// remove the row by calling the getParent on button
mContainerView.removeView((View) v.getParent());
}
// Helper for inflating a row
private void inflateEditRow(String name) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.row, null);
final ImageButton deleteButton = (ImageButton) rowView
.findViewById(R.id.buttonDelete);
final EditText editText = (EditText) rowView
.findViewById(R.id.editText);
if (name != null && !name.isEmpty()) {
editText.setText(name);
} else {
mExclusiveEmptyView = rowView;
deleteButton.setVisibility(View.INVISIBLE);
}
// A TextWatcher to control the visibility of the "Add new" button and
// handle the exclusive empty view.
editText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
// Some visibility logic control here:
if (s.toString().isEmpty()) {
mAddButton.setVisibility(View.GONE);
deleteButton.setVisibility(View.INVISIBLE);
if (mExclusiveEmptyView != null
&& mExclusiveEmptyView != rowView) {
mContainerView.removeView(mExclusiveEmptyView);
}
mExclusiveEmptyView = rowView;
} else {
if (mExclusiveEmptyView == rowView) {
mExclusiveEmptyView = null;
}
mAddButton.setVisibility(View.VISIBLE);
deleteButton.setVisibility(View.VISIBLE);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
// Inflate at the end of all rows but before the "Add new" button
mContainerView.addView(rowView, mContainerView.getChildCount() - 1);
}
This is my general way:
View namebar = view.findViewById(R.id.namebar);
ViewGroup parent = (ViewGroup) namebar.getParent();
if (parent != null) {
parent.removeView(namebar);
}
Hi You can try this way by adding relative layout and than add textview in that.
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
(LayoutParams.WRAP_CONTENT), (LayoutParams.WRAP_CONTENT));
RelativeLayout relative = new RelativeLayout(getApplicationContext());
relative.setLayoutParams(lp);
TextView tv = new TextView(getApplicationContext());
tv.setLayoutParams(lp);
EditText edittv = new EditText(getApplicationContext());
edittv.setLayoutParams(lp);
relative.addView(tv);
relative.addView(edittv);
Just use myView.setVisibility(View.GONE); to remove it completely.
But if you want to reserve the occupied space inside its parent use myView.setVisibility(View.INVISIBLE);
Kotlin Extension Solution
Add removeSelf to directly call on a view. If attached to a parent, it will be removed. This makes your code more declarative, and thus readable.
myView.removeSelf()
fun View?.removeSelf() {
this ?: return
val parent = parent as? ViewGroup ?: return
parent.removeView(this)
}
Here are 3 options for how to programmatically add a view to a ViewGroup.
// Built-in
myViewGroup.addView(myView)
// Reverse addition
myView.addTo(myViewGroup)
fun View?.addTo(parent: ViewGroup?) {
this ?: return
parent ?: return
parent.addView(this)
}
// Null-safe extension
fun ViewGroup?.addView(view: View?) {
this ?: return
view ?: return
addView(view)
}
ViewGroup class provides API for child views management in run-time, allowing to add/remove views as well.
Some other links on the subject:
Android, add new view without XML Layout
Android Runtime Layout Tutorial
http://developer.android.com/reference/android/view/View.html
http://developer.android.com/reference/android/widget/LinearLayout.html
For Adding the Button
LinearLayout dynamicview = (LinearLayout)findViewById(R.id.buttonlayout);
LinearLayout.LayoutParams lprams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
Button btn = new Button(this);
btn.setId(count);
final int id_ = btn.getId();
btn.setText("Capture Image" + id_);
btn.setTextColor(Color.WHITE);
btn.setBackgroundColor(Color.rgb(70, 80, 90));
dynamicview.addView(btn, lprams);
btn = ((Button) findViewById(id_));
btn.setOnClickListener(this);
For removing the button
ViewGroup layout = (ViewGroup) findViewById(R.id.buttonlayout);
View command = layout.findViewById(count);
layout.removeView(command);
Hi First write the Activity class. The following class have a Name of category and small add button. When you press on add (+) button it adds the new row which contains an EditText and an ImageButton which performs the delete of the row.
package com.blmsr.manager;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.blmsr.manager.R;
import com.blmsr.manager.dao.CategoryService;
import com.blmsr.manager.models.CategoryModel;
import com.blmsr.manager.service.DatabaseService;
public class CategoryEditorActivity extends Activity {
private final String CLASSNAME = "CategoryEditorActivity";
LinearLayout itsLinearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category_editor);
itsLinearLayout = (LinearLayout)findViewById(R.id.linearLayout2);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_category_editor, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.action_delete:
deleteCategory();
return true;
case R.id.action_save:
saveCategory();
return true;
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Adds a new row which contains the EditText and a delete button.
* #param theView
*/
public void addField(View theView)
{
itsLinearLayout.addView(tableLayout(), itsLinearLayout.getChildCount()-1);
}
// Using a TableLayout as it provides you with a neat ordering structure
private TableLayout tableLayout() {
TableLayout tableLayout = new TableLayout(this);
tableLayout.addView(createRowView());
return tableLayout;
}
private TableRow createRowView() {
TableRow tableRow = new TableRow(this);
tableRow.setPadding(0, 10, 0, 0);
EditText editText = new EditText(this);
editText.setWidth(600);
editText.requestFocus();
tableRow.addView(editText);
ImageButton btnGreen = new ImageButton(this);
btnGreen.setImageResource(R.drawable.ic_delete);
btnGreen.setBackgroundColor(Color.TRANSPARENT);
btnGreen.setOnClickListener(anImageButtonListener);
tableRow.addView(btnGreen);
return tableRow;
}
/**
* Delete the row when clicked on the remove button.
*/
private View.OnClickListener anImageButtonListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
TableRow anTableRow = (TableRow)v.getParent();
TableLayout anTable = (TableLayout) anTableRow.getParent();
itsLinearLayout.removeView(anTable);
}
};
/**
* Save the values to db.
*/
private void saveCategory()
{
CategoryService aCategoryService = DatabaseService.getInstance(this).getCategoryService();
aCategoryService.save(getModel());
Log.d(CLASSNAME, "successfully saved model");
Intent anIntent = new Intent(this, CategoriesListActivity.class);
startActivity(anIntent);
}
/**
* performs the delete.
*/
private void deleteCategory()
{
}
/**
* Returns the model object. It gets the values from the EditText views and sets to the model.
* #return
*/
private CategoryModel getModel()
{
CategoryModel aCategoryModel = new CategoryModel();
try
{
EditText anCategoryNameEditText = (EditText) findViewById(R.id.categoryNameEditText);
aCategoryModel.setCategoryName(anCategoryNameEditText.getText().toString());
for(int i= 0; i< itsLinearLayout.getChildCount(); i++)
{
View aTableLayOutView = itsLinearLayout.getChildAt(i);
if(aTableLayOutView instanceof TableLayout)
{
for(int j= 0; j< ((TableLayout) aTableLayOutView).getChildCount() ; j++ );
{
TableRow anTableRow = (TableRow) ((TableLayout) aTableLayOutView).getChildAt(i);
EditText anEditText = (EditText) anTableRow.getChildAt(0);
if(StringUtils.isNullOrEmpty(anEditText.getText().toString()))
{
// show a validation message.
//return aCategoryModel;
}
setValuesToModel(aCategoryModel, i + 1, anEditText.getText().toString());
}
}
}
}
catch (Exception anException)
{
Log.d(CLASSNAME, "Exception occured"+anException);
}
return aCategoryModel;
}
/**
* Sets the value to model.
* #param theModel
* #param theFieldIndexNumber
* #param theFieldValue
*/
private void setValuesToModel(CategoryModel theModel, int theFieldIndexNumber, String theFieldValue)
{
switch (theFieldIndexNumber)
{
case 1 :
theModel.setField1(theFieldValue);
break;
case 2 :
theModel.setField2(theFieldValue);
break;
case 3 :
theModel.setField3(theFieldValue);
break;
case 4 :
theModel.setField4(theFieldValue);
break;
case 5 :
theModel.setField5(theFieldValue);
break;
case 6 :
theModel.setField6(theFieldValue);
break;
case 7 :
theModel.setField7(theFieldValue);
break;
case 8 :
theModel.setField8(theFieldValue);
break;
case 9 :
theModel.setField9(theFieldValue);
break;
case 10 :
theModel.setField10(theFieldValue);
break;
case 11 :
theModel.setField11(theFieldValue);
break;
case 12 :
theModel.setField12(theFieldValue);
break;
case 13 :
theModel.setField13(theFieldValue);
break;
case 14 :
theModel.setField14(theFieldValue);
break;
case 15 :
theModel.setField15(theFieldValue);
break;
}
}
}
2. Write the Layout xml as given below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#006699"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.blmsr.manager.CategoryEditorActivity">
<LinearLayout
android:id="#+id/addCategiryNameItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/categoryNameTextView"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="#string/lbl_category_name"
android:textStyle="bold"
/>
<TextView
android:id="#+id/categoryIconName"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="#string/lbl_category_icon_name"
android:textStyle="bold"
/>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="#+id/categoryNameEditText"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:hint="#string/lbl_category_name"
android:inputType="textAutoComplete" />
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="#+id/linearLayout3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
</LinearLayout>
<ImageButton
android:id="#+id/addField"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_below="#+id/addCategoryLayout"
android:src="#drawable/ic_input_add"
android:onClick="addField"
/>
</LinearLayout>
</ScrollView>
</LinearLayout>
Once you finished your view will as shown below
//MainActivity :
package com.edittext.demo;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText edtText;
private LinearLayout LinearMain;
private Button btnAdd, btnClear;
private int no;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtText = (EditText)findViewById(R.id.edtMain);
btnAdd = (Button)findViewById(R.id.btnAdd);
btnClear = (Button)findViewById(R.id.btnClear);
LinearMain = (LinearLayout)findViewById(R.id.LinearMain);
btnAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!TextUtils.isEmpty(edtText.getText().toString().trim())) {
no = Integer.parseInt(edtText.getText().toString());
CreateEdittext();
}else {
Toast.makeText(MainActivity.this, "Please entere value", Toast.LENGTH_SHORT).show();
}
}
});
btnClear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LinearMain.removeAllViews();
edtText.setText("");
}
});
/*edtText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});*/
}
protected void CreateEdittext() {
final EditText[] text = new EditText[no];
final Button[] add = new Button[no];
final LinearLayout[] LinearChild = new LinearLayout[no];
LinearMain.removeAllViews();
for (int i = 0; i < no; i++){
View view = getLayoutInflater().inflate(R.layout.edit_text, LinearMain,false);
text[i] = (EditText)view.findViewById(R.id.edtText);
text[i].setId(i);
text[i].setTag(""+i);
add[i] = (Button)view.findViewById(R.id.btnAdd);
add[i].setId(i);
add[i].setTag(""+i);
LinearChild[i] = (LinearLayout)view.findViewById(R.id.child_linear);
LinearChild[i].setId(i);
LinearChild[i].setTag(""+i);
LinearMain.addView(view);
add[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Toast.makeText(MainActivity.this, "add text "+v.getTag(), Toast.LENGTH_SHORT).show();
int a = Integer.parseInt(text[v.getId()].getText().toString());
LinearChild[v.getId()].removeAllViews();
for (int k = 0; k < a; k++){
EditText text = (EditText) new EditText(MainActivity.this);
text.setId(k);
text.setTag(""+k);
LinearChild[v.getId()].addView(text);
}
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
// Now add xml main
<LinearLayout 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"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal" >
<EditText
android:id="#+id/edtMain"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_weight="1"
android:ems="10"
android:hint="Enter value" >
<requestFocus />
</EditText>
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="Add" />
<Button
android:id="#+id/btnClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:text="Clear" />
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp" >
<LinearLayout
android:id="#+id/LinearMain"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
// now add view xml file..
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal" >
<EditText
android:id="#+id/edtText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:ems="10" />
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="Add" />
</LinearLayout>
<LinearLayout
android:id="#+id/child_linear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:orientation="vertical" >
</LinearLayout>

Categories

Resources