ANDROID: Delete textviews which are created dynamically - android

I have added multiple TextViews dynamically in a layout,
for(int x=4;x<result.length();x++)
{
JSONObject collegeData = result.getJSONObject(x);
Log.i("Classlist",""+x);
TextView tv = new TextView(this);
Animation animation = AnimationUtils.loadAnimation(student_profile.this, android.R.anim.slide_in_left);
tv.startAnimation(animation);
tv.setTag(tag);
tv.setLayoutParams(lparams);
tv.setText(collegeData.getString("date") + " " + collegeData.getString("day_name"));
tv.setTextSize(17);
this.linearLayout_top5classes.addView(tv);
}
This loop adds textViews according to the data received by the url,Now i want to remove the textviews which were created in this loop and i cant find a proper method to do so....I only want to remove these textviews and not all the textviews
UPDATE
First i used
int prv=0;
then
String tag ="textView_"+x;
prv++;
in the first loop to generate multiple tags
then i removed them with
for(int x=4;x<prv;x++)
{
View view = this.linearLayout_top5classes.findViewWithTag("textView_"+x);
this.linearLayout_top5classes.removeView(view);
Log.i("prv value",prv+"");
}

Of course there is a way. Just look for child views with tag:
View view = this.linearLayout_top5classes.findViewWithTag(tag);
this.linearLayout_top5classes.removeView(view);
If you add ID's to child views, then:
View view = this.linearLayout_top5classes.findViewById(id);
this.linearLayout_top5classes.removeView(view);

If possible try using different layout for the dynamically added textviews. and then remove views from second layout only. By using,:
linearLayout_top5classes.removeAllViews();

To remove particular view with tag
View view = this.linearLayout_top5classes.findViewWithTag(tag);
this.linearLayout_top5classes.removeView(view)
To remove view from particular position
this.linearLayout_top5classes.removeViewAt(position);
Use following logic to remove any view from layout.
this.linearLayout_top5classes..post(new Runnable() {
public void run() {
this.linearLayout_top5classes..removeView(view);
}
});

Related

Why TextView variable needs to be inside a loop

LinearLayout x=(LinearLayout)findViewById(R.id.english_no);
Why this code is wrong-
TextView wordview=new TextView(this);
for(int i=0;i<english.size();i++)
{
wordview.setText(english.get(i));
x.addView(wordview);
}
and this one is correct-
for(int i=0;i<english.size();i++)
{
TextView wordview=new TextView(this);
wordview.setText(english.get(i));
x.addView(wordview);
}
I couldn't understand the difference.
here in the first example you are just referring to the first TextView that you created and changing its value and adding it to the view, eventually the x (hoping a Linearlayout) will have english.size() number of views where the content of every view would be same and that is the last content of english

Auto-scrolling textview in Android

I've tried a lot of different ways, most of the suggestions found here, but none of them seems to work. What I'm trying to achieve is at chat area below my game area, a SurfaceView. It is supposed to scroll upwards as new lines are added to the textview.
At first, it looks like a really simple task, but having tried all kinds of suggestions, like a TextView in a ScrollView, like a TextView in a TableRow in a TableLayout in a ScrollView, and so on...I've still not made it happen. Of course this must be something easily achieved in Android, right??
The task is to display like 6 lines of text in the bottom of the screen, and as a new message is added last it should scroll the rest upwards, like a terminal window. The important thing is that it should add the latest message after the other and, when reached the bottom line, scroll the text upwards and add the new line(s) at the end.
Any kind of help or suggestions would be highly appreciated!!
I needed the same behavior in one of my apps and I achieved in just with one command:
view.setGravity(Gravity.BOTTOM);
Or, analogously, setting this attribute in your layout:
android:gravity="bottom"
Then simply add your lines using:
your_text_view.append(newLine);
Suppose, you declared your ScrollView as follows...
private ScrollView mScrollView;
you initialized it as...
mScrollView = (ScrollView) findViewById(R.id.scroll_view_chat_window);
Now, create a method to perform scroll down when you call the method. Inside the method implement a thread which will do the scroll down independently. And call the method after every chat message update thats will do the auto-srcoll functionality.
private void scrollDown() {
mScrollView.post(new Runnable() {
#Override
public void run() {
mScrollView.smoothScrollTo(mScrollView.getScrollY(), mScrollView.getScrollY()
+ mScrollView.getHeight());
}
});
}
I've achieved this (crudely!) by maintaining my own list, deleting the lowest element then adding at the end each time. Here i've just got a 3 line window:
public class MessageWindow {
private ArrayList <String> msgs;
private Activity parentActivity;
public MessageWindow(Activity act, int allMsgsMax) {
this.parentActivity = act;
msgs = new ArrayList <String> ();
// create empty list elements for initial display
for (int i = 0; i < allMsgsMax; i++){
msgs.add("");
}
}
//
public void put (String msg){
msgs.remove(0);
msgs.add(msg);
// get a handle to the textview 'messages', a 3-line box
TextView t2v = (TextView) parentActivity.findViewById(R.id.messages);
// crappy but you get the idea:
t2v.setText(msgs.get(0) + "\n" + msgs.get(1) + "\n" + msgs.get(2) );
}
then in the activity:
protected MessageWindow messageWindow;
// setup splash screen
messageWindow = new MessageWindow(this, 3);
// write some stuff - row1 will disappear off the top of the box
messageWindow.put ("row1")
messageWindow.put ("row2")
messageWindow.put ("row3")
messageWindow.put ("row4")

dynamically name textview after inflating android

I m inflating 4 linear layouts multiple times in a scroll view. Each layout has a title in its header. The code snippet is given below.
for(int j=0;j<qType.length;j++)
{
LinearLayout.LayoutParams siz = new LinearLayout.LayoutParams(width, height);;
if(qType[j]==0)
{
view1 = getLayoutInflater().inflate(R.layout.layout1, main_layout,false);
siz = new LinearLayout.LayoutParams(width, height/3);
}
else if(qType[j]==1)
{
view1 = getLayoutInflater().inflate(R.layout.layout3, main_layout,false);
siz = new LinearLayout.LayoutParams(width, height/3);
}
else if(qType[j]==2)
{
view1 = getLayoutInflater().inflate(R.layout.layout4, main_layout,false);
siz = new LinearLayout.LayoutParams(width, height/3);
}
else if(qType[j]==3)
{
view1 = getLayoutInflater().inflate(R.layout.layout5, main_layout,false);
siz = new LinearLayout.LayoutParams(width, height/2);
}
siz.topMargin = 25;
main_layout.addView(view1, siz);
}
scroll_layout.addView(main_layout);
scroll_layout.setBackgroundResource(R.drawable.options_background);
setContentView(scroll_layout);
Now there is textview in each layout and i want to change the text of it. If i access them by findviewbyid and give settext, only the first instance is being changed, i want to change the textview on all occasions.
for(int k=0;k<NumberQuestions.length;k++)
{
TextView number_title = (TextView)main_layout.findViewById(R.id.number_title);
TextView mcq_title = (TextView)main_layout.findViewById(R.id.mcq_title);
TextView comment_title = (TextView)main_layout.findViewById(R.id.comment_title);
TextView cam_title = (TextView)main_layout.findViewById(R.id.cam_title);
if(qType[k]==0)
{
number_title.setTypeface(myriadpro_bold);
number_title.setText(NumberQuestions[k]);
}
if(qType[k]==1)
{
comment_title.setTypeface(myriadpro_bold);
comment_title.setText(NumberQuestions[k]);
}
else if(qType[k]==2)
{
mcq_title.setTypeface(myriadpro_bold);
mcq_title.setText(NumberQuestions[k]);
}
else if(qType[k]==3)
{
cam_title.setTypeface(myriadpro_bold);
cam_title.setText(NumberQuestions[k]);
}
Please help.
probably the TextView android: id in all layouts are the same, thus explaining the behavior of the method findViewById always returns the first occurrence
Disclaimer: I feel like you are trying to work against the Android Framework, as opposed to working with it. My suggestion is a tad bit of an overhaul, but I do feel like it is the correct way to go about things.
I would recommend using a ListView, since you are repeating the same format many times. A listview will typically have a container of objects of objects, and an adapter responsible for mapping an object to a particular row within the listview. When you change the data in the underlying container, you will call the callback notifyDataSetChanged() for your adapter to notify it that you changed the underlying data and alert it to update your listview.
2 great resources/tutorials from the android developer site:
ListView: http://developer.android.com/guide/topics/ui/layout/listview.html
Adapters: http://developer.android.com/guide/topics/ui/declaring-layout.html#AdapterViews
If i am right main_layout is a name view in your xml file.So You should use like this
view1 = getLayoutInflater().inflate(R.layout.layout1, main_layout,false);
TextView tv = (TextView)main_layout.findViewById(R.id.tv1);
where tv is texview in layout1.xml

get array of TextViews

I'm making an app that stores results in a multiple textviews,
First, I need to get the views, they are 20 views named result 1, .... result 20.
how can i get them to an array of textview.
I found this method but it's too long
TextView [] results = {(TextView)findViewById (R.id.result1),
(TextView)findViewById (R.id.result2),(TextView)findViewById (R.id.result3),
(TextView)findViewById (R.id.result4),(TextView)findViewById (R.id.result5),
(TextView)findViewById (R.id.result6).....};
thank you for help
How you started is correct, now think about putting that repetitive code in a cycle.
For example design a method that will take as the input an array of your TextView resources, and using a "for" cycle find that view by corresponding id.
private TextView[] initTextViews(int[] ids){
TextView[] collection = new TextView[ids.length];
for(int i=0; i<ids.length; i++){
TextView currentTextView = (TextView)findViewById(ids[i]);
collection[i]=currentTextView;
}
return collection;
}
And then you use it like this:
// Your TextViews ids
int[] ids={R.id.result1, R.id.result2, R.id.result3};
// The resulting array
TextView[] textViews=initTextViews(ids);
if you have a handle to parent the layout that contains the text views, you can recursively discover them with a function like this,
void getTextViews(View view, List<TextView> textViews) {
if (view instanceof TextView) {
textviews.add((TextView)view);
else if (TextView instanceof ViewGroup) {
getTextViews((ViewGroup)view, textViews);
}
}
now call it like this,
ViewGroup topLayout = findViewById(...);
List<TextView> views = new ArrayList<TextView>();
getTextViews(topLayout, views);
TextView[] textViewArray = textViews.toArray(new TextView[0]);
this is quite a bit longer, but it has the advantage of not needing to change the code if you add, remove, or rename a textview.
IMHO, don't focus on writing less code, focus on writing clear code. the speed at which you type is rarely the limiting factor in your productivity.

android: add components dynamically to layout

I have a java app that adds views dynamically to a container panel as follows.
void addBoard(int ID) {
BoardPanel p = new BoardPanel(myManager,ID);
setAutoLayout();
containerPanel.add(p);
containerPanel.repaint();
}
When I try to convert this to an android app it hangs when addView is called. What is the problem? Note that the user could add a 1000 views (BoardPanels) if he likes so I can not use XML layouts.
void addBoard(int ID) {
BoardPanel p = new BoardPanel(context,myManager,ID);
Log.i("Info", "Going to add view");
containerPanel.addView(p);
Log.i("Info", "Added");
containerPanel.postInvalidate();
}
Thanks
Update: Problem seems to be due to threaded code as Aegonis pointed out.
Try ViewGroup.addView() (FrameLayout, GridLayout, LinearLayout, ... are all extensions of ViewGroup).
For example, if you want a View to be inserted after the first already existing View:
LinearLayout layout = (LinearLayout) findViewById(R.id.layoutID);
layout.addView(viewToBeAdded, 1);

Categories

Resources