Android: programmatically adding buttons to a layout - android

I'm trying to get an add button to add another button to the layout, based on the edittext to the left of the button. The point is for a person to list the rooms in their house, and then when they type in each room, a new button is generated so they can click the room, and then start working on the next page.
I had an xml layout all done, and then I realized I'm "programmatically" adding buttons, so I redid the layout programmatically, and then in the switch/case (that's how I do onclicks) for the add button I tried to add a button to the view, but it's getting very tricky. I'd like to have a scrollview below the edittext and add buttons, and as they add all the rooms to their house it eventually is populated with a scrollable list of buttons for their entire home. Is there a way to add buttons programmatically to an xml'd layout. I was thinking you can but everything I'm trying just isn't working.
Thanks for your help everybody, any recommendations you have would be greatly appreciated.
First Edit (in response to Tanuj's solution)
My XML file (not sure if we're going to use this or just use the java):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tvAddARoom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tvAddARoom" />
<EditText
android:id="#+id/etAddARoom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/etAddARoom" />
<Button
android:id="#+id/btnAddARoom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btnAdd" />
<TextView
android:id="#+id/tvSelectARoom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tvSelectARoom" />
<TextView
android:id="#+id/tvNoRooms"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tvNoRooms" />
<Button
android:id="#+id/btnViewAll"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btnViewAll" />
</LinearLayout>
And the Java. This isn't at all correct, as in the java I'm creating the whole layout instead of using the layout above. Just not sure if I can bridge the two.
package com.bluej.movingbuddy;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
//import android.widget.ScrollView;
import android.widget.TextView;
public class EstimatorByRoom extends Activity implements OnClickListener {
String roomName;
EditText etAddARoom;
LinearLayout layout;
LinearLayout.LayoutParams layoutParam;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//setContentView(R.layout.estimatorbyroom);
LayoutParams params =
new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
//create a layout
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
//create a text view
TextView tvAddARoom = new TextView(this);
tvAddARoom.setText("Add a Room");
tvAddARoom.setLayoutParams(params);
//create an edittext
EditText etAddARoom = new EditText(this);
etAddARoom.setHint("Living Room, Dining Room, etc.");
etAddARoom.setLayoutParams(params);
//create a button
Button btnAddARoom = new Button(this);
btnAddARoom.setText("Add");
btnAddARoom.setLayoutParams(params);
//adds the textview
layout.addView(tvAddARoom);
//add the edittext
layout.addView(etAddARoom);
//add the button
layout.addView(btnAddARoom);
//create the layout param for the layout
LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
this.addContentView(layout, layoutParam);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnAddARoom:
//add a room
//this part isn't working!
roomName = etAddARoom.getText().toString();
Button createdButton = new Button(this);
createdButton.setText(roomName);
layout.addView(createdButton);
this.addContentView(layout, layoutParam);
//if no rooms make tvnorooms disappear
break;
}
}
}

Try this :
//the layout on which you are working
LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout_tags);
//set the properties for button
Button btnTag = new Button(this);
btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
btnTag.setText("Button");
btnTag.setId(some_random_id);
//add button to the layout
layout.addView(btnTag);

Try this code:
LinearLayout l_layout = (LinearLayout) findViewById(R.id.linear_layout);
l_layout.setOrientation(LinearLayout.VERTICAL); // or HORIZONTAL
Button btn1 = new Button(this);
btn1.setText("Button_text");
l_layout.addView(btn1);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// put code on click operation
}
});
that is a way to create button dynamically and add in Layout.
remember that when you create button programmatically you just use this not Class_name.this

public class AndroidWalkthroughApp1 extends Activity implements View.OnClickListener {
final int TOP_ID = 3;
final int BOTTOM_ID = 4;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// create two layouts to hold buttons
LinearLayout top = new LinearLayout(this);
top.setId(TOP_ID);
LinearLayout bottom = new LinearLayout(this);
bottom.setId(BOTTOM_ID);
// create buttons in a loop
for (int i = 0; i < 2; i++) {
Button button = new Button(this);
button.setText("Button " + i);
// R.id won't be generated for us, so we need to create one
button.setId(i);
// add our event handler (less memory than an anonymous inner class)
button.setOnClickListener(this);
// add generated button to view
if (i == 0) {
top.addView(button);
}
else {
bottom.addView(button);
}
}
// add generated layouts to root layout view
LinearLayout root = (LinearLayout)this.findViewById(R.id.root_layout);
root.addView(top);
root.addView(bottom);
}
#Override
public void onClick(View v) {
// show a message with the button's ID
Toast toast = Toast.makeText(AndroidWalkthroughApp1.this, "You clicked button " + v.getId(), Toast.LENGTH_LONG);
toast.show();
// get the parent layout and remove the clicked button
LinearLayout parentLayout = (LinearLayout)v.getParent();
parentLayout.removeView(v);
}
}

Each button needs to have an onclicklistener to tell it what to do. this can be added to your java code under where you state your button.
Button createdButton = new Button(this);
createdButton.setOnClickListener(new OnClickListener()
{
code you want implemented
}

I would add an id to your LinearLayout in xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#id/llContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
And then change your onClick to this:
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnAddARoom:
//add a room
//Find you parent layout which we'll be adding your button to:
LinearLayout layout = (LinearLayout) findViewById(R.id.llContainer);
roomName = etAddARoom.getText().toString();
Button createdButton = new Button(this);
createdButton.setText(roomName);
createdButton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
layout.addView(createdButton);
//if no rooms make tvnorooms disappear
break;
}
}

Related

Is there a way to change background color behind a button (button.setBackgroundResource)

I'm a new Android dev student, and I'm trying to create a dynamic layout witch contains a TextView and a button inside the same row.
but I have a little problem.
I set my Button in my Drawables ressources by
button.setBackgroundResource(R.drawable.ic_comment_black_48px);
and now, I cannot change the backgroundcolor behind it.
I have created a newLinearlayout inside my main LinearLayout and have created a new textView and a new Button.
I have put them inside the LinearLayout's child and put it inside the main.
That's work but not the background color behind my button.
is there a way to do that?
my xml layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/grey"
android:id="#+id/historyLayout">
</LinearLayout>
my complete activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
mLinearLayout = findViewById(R.id.historyLayout);
mMoodSaved = new ArrayList(7); // Define the max size of my ArrayList
loadData();
for (int i = 1; i <= 7; i++) {
final TextView textView = new TextView(this);
mLinearLyt = new LinearLayout(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mLinearLyt.setOrientation(LinearLayout.HORIZONTAL);
textView.setHeight(300);
textView.setWidth(400);
textView.setBackgroundColor(Color.RED);
textView.setTextColor(Color.BLACK);
textView.setTextSize(12);
textView.setText(String.valueOf(i));
mLinearLyt.setBackgroundColor(Color.YELLOW);
mLinearLyt.addView(textView);
mLinearLyt.setLayoutParams(params);
ImageButton button = new ImageButton(this);
LinearLayout.LayoutParams param2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
param2.setMargins(20,50,0,0);
param2.height = 100;
param2.width = 100;
button.setLayoutParams(param2);
button.setBackgroundResource(R.drawable.ic_comment_black_48px);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
soundConfirm();
Toast.makeText(getApplicationContext(), textView.getText(), Toast.LENGTH_LONG).show(); //Display Toast Message
}
});
mLinearLyt.addView(button);
mLinearLayout.addView(mLinearLyt);
}
}
Since this an ImageButton, set
button.setImageResource(R.drawable.ic_comment_black_48px)
instead of setBackgroundResource.

How to correctly populate list items for my requirement

I was thinking of something and I would like to know if there is any solution.
I want to make a program, where when I am going to press the "add" button, a new row will be created with an Edittext on left and a TextView on right. Every time I press the "add" button, a new row with an Edittext and a Textview will be added.
I have read some tutorials, but all said for only one field and the use of a listview.
How can I add both fields?
I can't figure out how can I set the position of each row and field? For example, I want the 2 fields to have 30dp distance or each row has distance 25dp.
Also, how will I know the id of each one in order to make some calculations?
Can anyone explain me something, give some code or suggest me any tutorial?
Thank you very much!
Something like below (I made it on paint)
...UPDATE...
So, I make some changes to go a little bit further.. I made two lists for TextViews and EditTexts in order to retrieve them later easier.. But It get stuck when I press the button for the second time.. In the first press, it creates the first row, but in the second press, it stuck and not even craches. I am sure, is something stupid that I haven't see it..
EditText ed;
List<EditText> allEds = new ArrayList<EditText>();
TextView tv;
List<TextView> allTvs = new ArrayList<TextView>();
for (i = 0; i < counter; i++) {
ed = new EditText(Main_5.this);
allEds.add(ed);
ed.setId(counter);
ed.setLayoutParams(new TableLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 0.5f));
linearLayout.addView(ed);
ed.setInputType(InputType.TYPE_CLASS_NUMBER| InputType.TYPE_NUMBER_FLAG_DECIMAL);
tv = new TextView(Main_5.this);
allTvs.add(tv);
tv.setId(counter);
tv.setLayoutParams(new TableLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 0.5f));
linearLayout.addView(tv);
mainLinearLayout.addView(linearLayout);
}
Also, could you give me a little help for retreiving the ids?? I am trying to get the EditText id's and show then on specific TextView id's.. I thought something like this for start, but I cannot test it because of the error.. And I want to take it further in order to put on TextView the EditText.. Any ideas??
Double[] doubles = new Double[allEds.size()];
for(i=0;i<allEds.size();i++){
doubles[i] = allEds.get(i).getText().toDouble();
}
Thank you!!
So i've just written a quick program to help you with your problem. This will need tweaking to suit your case.
activity_main.xml
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add Row"/>
<LinearLayout
android:id="#+id/linearLayout"
android:layout_below="#id/button"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
</LinearLayout>
</RelativeLayout>
So here we add a Button to add the things you would like and a LinearLayout to contain them.
MainActivity.java
public class MainActivity extends Activity {
private LinearLayout mainLinearLayout;
private int counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
mainLinearLayout = (LinearLayout) findViewById(R.id.linearLayout);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter++;
LinearLayout linearLayout = new LinearLayout(MainActivity.this);
TableLayout.LayoutParams lp = new TableLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1f);
linearLayout.setLayoutParams(lp);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
EditText editText = new EditText(MainActivity.this);
editText.setId(counter);
editText.setLayoutParams(new TableLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 0.5f));
editText.setHint("Edit Text");
TextView textView = new TextView(MainActivity.this);
textView.setId(counter);
textView.setLayoutParams(new TableLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 0.5f));
textView.setText("TextView");
linearLayout.addView(editText);
linearLayout.addView(textView);
mainLinearLayout.addView(linearLayout);
}
});
}
#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_main, 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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
So what this will do now is when the add row button is clicked, it'll create a new instance of an EditText and a new instance of a TextView and add them to a horizontal LinearLayout and then add that linearlayout to the parent linearLayout created in the XML.
oh!
I added and a clear button for everyone who search it.
Button delete = (Button) findViewById(R.id.delete);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mainLinearLayout.removeAllViews();
}
});

Displaying linear layout VS R.layout.activity main

So I'm new to android development and I'm having a bit a of a trouble.
I'm developing an an app which is going to have a similar background every time but imports a new image every time the user touches the screen.
HOWEVER my problem is that I'm having an issue right now in which I'm trying to load a new activity when a user click a button, 1) I followed one tutorial which had me use XML to add the button and program MAIN_activity to to switch to second_Activity using setcontent(R.layout.main_Activity) and works fine.
2) I also started another tutorial which had me use setContent(layout1) where layout one is in fact a LinearLayout which you addView(stuff) such as a button and program it to switch the second activity, but I'm failing terribly.
long story short, using this line setcontent(R.layout.main_Activity) overrides the setContent(layout1) info and I cant combine them. In addition I dont know how to make a button and click to switch activity except using the first method, I'm open to suggestions.
package self.name.firstandroidprogram;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
LinearLayout layout1;
EditText number1Text;
EditText number2Text;
Button calcButton, switchButton;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
layout1 = new LinearLayout(this);
number1Text = new EditText(this);
number2Text = new EditText(this);
calcButton = new Button(this);
switchButton = (Button)findViewById(R.id.button1);
////////////////////////////////////////////////////////////////////////BUTTON ACTIVITY SWTICH
switchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Class2.class);
startActivity(intent);
}
});
////////////////////////////////////////////////////////////////////////////
answerText.setText("0");
calcButton.setText("X");
layout1.addView(number1Text);
layout1.addView(number2Text);
layout1.addView(calcButton);
layout1.addView(answerText);
layout1.addView(switchButton);
setContentView(R.layout.activity_main);// Works
// setContentView(layout1) failes when i run
}
I am not sure, but try it
public class MainActivity extends Activity {
LinearLayout layout1;
EditText number1Text;
EditText number2Text;
Button calcButton, switchButton;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
layout1 = new LinearLayout(this);
// Do it before adding views in it.
setContentView(layout1);
number1Text = new EditText(this);
number2Text = new EditText(this);
calcButton = new Button(this);
switchButton = (Button)findViewById(R.id.button1);
////////////////////////////////////////////////////////////////////////BUTTON ACTIVITY SWTICH
switchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Class2.class);
startActivity(intent);
}
});
////////////////////////////////////////////////////////////////////////////
answerText.setText("0");
calcButton.setText("X");
layout1.addView(number1Text);
layout1.addView(number2Text);
layout1.addView(calcButton);
layout1.addView(answerText);
layout1.addView(switchButton);
// setContentView(R.layout.activity_main);// Works
}
You can set LinearLayout as your main layout. When user clicks the switch button, you need to set background of the LinearLayout
activity_main.xml :
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="#+id/main"
android:background="#drawable/default"
>
<!-- put your Button here switch button -->
</LinearLayout>
MainActivity.java :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchButton = (Button)findViewById(R.id.button1);
LinearLayout lv1 = (LinearLayout) findViewById(R.id.main);
switchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// we have reference of LinearLayout as lv1
// we will change background of lv1 here when user clicks
lv1.setBackgroundResource(<your_new_background_image_id>);
}
});
<your_new_background_image_id> can be fetched from /res/drawable/ folder. You store 10-20 images of small size in drawable and rename them with similar name i.e. image1, image2 etc
When setting them as background, you can code like :
int[] imageArray = {R.drawable.image1, R.drawable.image2,...}
lv1.setBackgroundResource(imageArray[(i++)%10]);
If you are creating view programatically you have to set each view LayourParameters using view.setLayoutParams()
Try this
layout1 = new LinearLayout(this);
EditText number1Text = new EditText(this);
EditText number2Text = new EditText(this);
Button calcButton = new Button(this);
calcButton.setText("X");
//impt : width=MATCH_PARENT and height=MATCH_PARENT
layout1.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
layout1.setOrientation(LinearLayout.VERTICAL); //setting LL orientation
layout1.addView(number1Text);
layout1.addView(number2Text);
layout1.addView(calcButton);
setContentView(layout1);

How to remove dynamically created views on button click

public void Add_text() {
ll.setOrientation(LinearLayout.HORIZONTAL);
ll.setId(i);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView product = new TextView(getActivity());
product.setText(" Product" + 5 + " ");
ll.addView(product);
EditText qty = new EditText(getActivity());
qty.setText(i + "");
qty.setId(i);
qty.setWidth(120);
ll.addView(qty);
Button btn = new Button(getActivity());
ll.addView(btn);
btn.setLayoutParams(params);
btn.setOnClickListener(o);
ly.addView(ll);
i++;
}
I wrote the above code to create the textfields and buttons dynamically; But now I need to remove 2 textfields and a button when the button is clicked. How do I do that?
Try following code.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
LinearLayout linearParent = (LinearLayout) v.getParent().getParent();
LinearLayout linearChild = (LinearLayout) v.getParent();
linearParent.removeView(linearChild);
}
});
Explanation
Here first take "GrandParent" of any view.
Then take its "Parent" view
With reference to "GrandParent" remove that "Parent" view.
this will remove all views which that "Parent" holds. As per your code, your "ll" will be "linearChild" here. And "ly" will be "linearParent" here. So whole "ll" will be removed from "ly" which you have added dynamically.
If you want to permanently remove the views you created.
OnClick(View view){
ly.removeAllViews()
}
If you do not want to permanently remove the views you created.
OnClick(View view){
ly.setVisibility(View.GONE); //This will hide the all views
qty.setVisibility(View.GONE);//This will hide the EditText qty
product .setVisibility(View.GONE);//This will hide the TextView product
}
So use appropriate code line which you want.
EDIT:
Use this code for your situation:
public void Add_text() {
ll.setOrientation(LinearLayout.HORIZONTAL);
ll.setId(i);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView product = new TextView(getActivity());
product.setText(" Product" + 5 + " ");
ll.addView(product);
EditText qty = new EditText(getActivity());
qty.setText(i + "");
qty.setId(i);
qty.setWidth(120);
ll.addView(qty);
Button btn = new Button(this);
ll.addView(btn);
btn.setLayoutParams(params);
ly.addView(ll);
i++;
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View button) {
qty.setVisibility(View.GONE);//This will hide the EditText qty
product .setVisibility(View.GONE);//This will hide the TextView product
}
});
}
i think you got to use this method on your LinearLayout :
public void removeView (View view)
first you call :
EditText et = (EditText)linearLayout.findViewById(yourEditText.getId());
then call the remove view method :
linearLayout.removeView (et) ;
and to remove all of the Views that are in the LinearLayout do the following :
public void removeAllViews ()
like the following :
linearLayout.removeAllViews()
and give me some feedback
Hope that Helps .
you can simply use qty.setVisibility(View.GONE) on the onClickListener() of the Button of your choice. like this.
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
qty.setVisibility(View.GONE); //for temporary purpose
//or u can also do this
layout.removeView(qty); //removes permanently
}
});
The benefit of using View.GONE is that you can get the View back if you want but layout.removeView(qty) will remove the view permanently and you have to re add the view again.
[EDIT] 1. changed to View.GONE instead of View.INVISIBLE because of reasons explained here
Hope I answered your question. :)
just use index for which you want to remove your view from linear layout
Linearlayout.removeViewAt();
if you want again that view then you can call addViewAt()in same way.
I hope it will help you.
Add this line
mLayout.removeViewAt(mLayout.getChildCount()-1);

Getting Array index on item click

I have created an Android RSS Reader App.I have a text marquee in my android app.Iam fetching RSS feed and store RSS title as an array.Iam setting this array as the marque text.Check the code,
String MarqueeStr="";
TextView flashnews;
for (int i = 0; i < nl.getLength(); i++) {
MarqueeStr = MarqueeStr +" | "+ Headlines.Title[i];
}
flashnews.setText(MarqueeStr);
Now I have to set an onclick listener for my marquee, so that user can view detailed description of title which they are clicked.I know how to set it.But my problem is, how can i get the array index of clicked string in the marquee text when a user click on the marquee?
here is my XML layout,
<TextView
android:id="#+id/flashs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:lines="1"
android:ellipsize="marquee"
android:layout_marginLeft="70dp"
android:fadingEdge="horizontal"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"
android:textColor="#e7e7e7" />
screen shote here..
can you see that "Latest News"? its my marquee text
I think that will only be possible if you will create your textviews dynamically and set id for them. like if you are having 10 news link then use 10 textviews
TextView txt = null;
View.OnClickListener marquee_click = new View.OnClickListener() {
#Override
public void onClick(View v) {
int selected_item = v.getTag();
switch (selected_item) {
case 0:
break;
case 1:
break;
case 2:
break;
default:
break;
}
}
};
LinearLayout news_text_layout = new LinearLayout(getApplicationContext());
news_text_layout.setOrientation(LinearLayout.HORIZONTAL);
for (int i = 0; i < 10; i++) {
txt = new TextView(getApplicationContext());
txt.setTag(i); // OR txt.setId(i);
txt.setText("new " + i);
txt.setOnClickListener(marquee_click);
news_text_layout.addView(txt);
}
// ADD YOUR LINEAR LAYOUT ON WHICH YOU HAVE ADDED ALL TEXT VIEW IN YOUR LISTVIEW FOOTER.
// NOW PERFORM SAME ANIMATION OR TRICK ON LINEAR LAYOUT WHICH YOU WERE PERFORMING ON marquee text.
Hope it can help you...
You can add every FlashNews as a dynamically created TextView. And you can put all of these in
one HorizontalScrollView. And set their listeners seperatly.
For marquee function, you can programmatically scroll the horizontalView within your code.
I dont know if it's possible to make it with your idea. (Actually it can be done, but it will contain pain i guess)
for animation look at this i have just created.
Create new project then add class and xml file which i am giving.
public class Test_stflowActivity extends Activity {
LinearLayout ll = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final LinearLayout ll = (LinearLayout) findViewById(R.id.linearLayout1);
final TranslateAnimation ts = new TranslateAnimation(200, -100, 0, 0);
ll.setAnimation(ts);
ts.setDuration(5000);
TextView tv = new TextView(getApplicationContext());
tv.setText("*bharat sharma*");
tv.setTextSize(30);
ll.addView(tv);
ll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ll.startAnimation(ts);
}
});
}
}
this is xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" >
</LinearLayout>
</RelativeLayout>
it is working for me
if you use a ListView with an adapter, (which you should), you can use the getItem(int position) function to get the specific item.

Categories

Resources