How to remove a TextView that was added dynamically - java

So I have a snippet of code where I create a textView on a user's click on a button. Since it was created after runtime I'm unsure what the ID is. But what I'm trying to do is have the option of deleting the last textView that is added and also clear all of the TextViews that were added. Thank you
private TextView createNewTextView(String text)
{
ArraySize++;
final LinearLayout mLayout=findViewById(R.id.linearLayout);
String newLine=System.getProperty("line.separator");
final LinearLayout.LayoutParams lparams =new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
ViewGroup.LayoutParams params=(RelativeLayout.LayoutParams) mLayout.getLayoutParams();
final TextView textView=new TextView(this);
textView.setLayoutParams(lparams);
textView.setText("New texT:: "+text+newLine);
listOfNames.add(text);
return textView;
}

you could create a XML File in this path res/values/ids.xml;
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="view_1" type="id"/>
</resources>
then in Java you add the id, like this
textView.setId(R.id.view_1);
and when you want to remove it
LinearLayout mLayout=findViewById(R.id.linearLayout);//to find in this specific view
TextView textView = (TextView)mLayout.findViewById(R.id.view_1);
mLayout.removeView(textView);

You use removeViewAt with the index
final LinearLayout mLayout=findViewById(R.id.linearLayout)
mLayout.removeViewAt(mLayout.getChildCount()-1); // get the last view
//or using index counter variable
//mLayout.removeViewAt(ArraySize-1); // adjust the value accordingly
or you can fetch the view and remove it using removeView
final LinearLayout mLayout=findViewById(R.id.linearLayout)
View v = mLayout.getChildAt(mLayout.getChildCount()-1);
mLayout.removeView(v);

As mentioned in this question, you can simply use
((ViewGroup) textView.getParent()).removeView(textView);

To remove all views:
mLayout.removeAllViews();
To remove last TextView:
mLayout.removeView(mLayout.getChildAt(mLayout.getChildCount()-1));

You can give an Id as edgar mentions or use the View.setTag , you can then find views by tag using viewGroup.findViewWithTag.

Related

Registering multiple click events programatically (Android/Java)

So i have this program which create my list of cards which are relative layouts and they look like this.
Here is the code of it creation. Ps its in a for loop
LayoutInflater mInflater = (LayoutInflater) atv.getSystemService(atv.LAYOUT_INFLATER_SERVICE);
LinearLayout relativeLayoutz = (LinearLayout) mInflater.inflate(R.layout.rtl_enterprise, parent);
RelativeLayout rl = (RelativeLayout) relativeLayoutz.findViewById(R.id.rl_empresa);
rl.setId(i);
ImageView img = (ImageView) rl.getChildAt(0);
//
//Performance bottleneck needs fixing/ not loading all images and overloading thread
//
//loadImageByUrl(atv, enterprises.getEnterprises().get(k).getPhoto().toString(), img);
TextView txt = (TextView) rl.getChildAt(1);
txt.setText(enterprises.getEnterprises().get(i).getEnterpriseName());
TextView txt2 = (TextView) rl.getChildAt(2);
txt2.setText(enterprises.getEnterprises().get(i).getEnterpriseType().getEnterpriseTypeName());
TextView txt3 = (TextView) rl.getChildAt(3);
txt3.setText(enterprises.getEnterprises().get(i).getCountry());
LinearLayout relativeLayout = (LinearLayout) mInflater.inflate(R.layout.rtl_enterprise, parent);
relativeLayout.setId(i);
everything there works kinda ok, but i have a problem, i need to create a
onClick listener
Why?
I would call a method which needs some info about the card that has been clicked, and then redirect to a new activity which contains the info about the card that he clicked.
But i would need that onclick listener for each of these relative layouts, and i assume it would need to be initialized when the card is created since it create + 50 cards, but i have no idea of how to setup each listener.
Why do you create it like that?
a better solution to use RecyclerView.
and in the adapter, you can listen for the item click. write the code one time and when any item clicked. you will know the position of the clicked item.
see this tutorial
https://developer.android.com/guide/topics/ui/layout/recyclerview
https://www.androidhive.info/2016/01/android-working-with-recycler-view/

Unable to correctly use .setLayoutParams(...) - Android

I wanted to try using a database on android so I made a small app that allows you to add contacts to the database and then it displays them.
I have been able to display contacts (from the database) if I create the layout on xml and then edit the text fiels in code. But I wanted to build the layouts in code so I can add as many contacts as I want.
The following code is the method I use to create the layout and the app crashes whenever I make it run this code. My guess is that there is a problem with the params. If only type LayoutParams.MatchContent it asks me to import and it gives me many options, that0s why it says LinearLayout.LayoutParams...;
I add the resulting layout to a LinearLayout.
Any help is much apreciated.
private LinearLayout createContactView (Contact contact) {
LinearLayout contactInfoWrapper = new LinearLayout(this);
contactInfoWrapper.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
contactInfoWrapper.setOrientation(LinearLayout.VERTICAL);
TextView nameView = new TextView(this);
nameView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
nameView.setText(contact.getName());
contactInfoWrapper.addView(nameView);
TextView numberView = new TextView(this);
numberView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
numberView.setText(contact.getPhoneNumber());
contactInfoWrapper.addView(numberView);
return contactInfoWrapper;
}
Instead of using setLayoutParams, instead use the LayoutParams in the addView(View v, LayoutParams params) method of your LinearLayout:
TextView nameView = new TextView(this);
nameView.setText(contact.getName());
contactInfoWrapper.addView(nameView, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
can you change the line
numberView.setText(contact.getPhoneNumber());
to this
numberView.setText(String.valueOf(contact.getPhoneNumber()));

Programatically add LinearLayout with Text and Image

I'm trying to add a LinearLayout for each item in a varying Array. I need each item to have an image and text horizontally, but for now I am testing with the text.
Keeping in mind this code is in a Fragment.
I think the error is with the getContext() but not to sure.
The code I currently have is:
List<PaymentOption> paymentOptions = aTradeItem.getPaymentOptions();
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(ImageUtils.dpToPx(16), ImageUtils.dpToPx(4), ImageUtils.dpToPx(16), ImageUtils.dpToPx(4));
LinearLayout.LayoutParams lineparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ImageUtils.dpToPx(1));
lineparams.setMargins(0, ImageUtils.dpToPx(4), 0, ImageUtils.dpToPx(4));
if (paymentOptions != null && paymentOptions.size() > 0) {
for (PaymentOption t : paymentOptions) {
LinearLayout paymentOptionLayout = new LinearLayout(getContext());
paymentOptionLayout.setOrientation(LinearLayout.HORIZONTAL);
paymentOptionLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
TextView heading = new TextView(getContext());
heading.setText(t.getDescription());
heading.setTextColor(getResources().getColor(R.color.light_text));
heading.setLayoutParams(lp);
paymentOptionLayout.addView(heading);
}
}
There are no errors, the data just doesnt populate on the screen. I have tried Hardcoding random text in the setText() but with no success.
Thank you
You're not adding your paymentOptionLayout to the layout which is set as your content View. Basically what you're doing is programatically creating the layout, but then doing nothing with it.
By default your activity_main.xml file will come with some type of layout depending on how you setup your code, for example a blank activity's xml file would be
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity"
android:id="#+id/RelativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
However when you create layouts programmatically the way you did, you must append them to the layout which is the parent layout in your XML file.
So I think what you need to do is the following.
RelativeLayout rl=(RelativeLayout)findViewById(R.id.RelativeLayout); //getting the view from the xml file. Keep in mind that the id is defiend in the xml file by you
List<PaymentOption> paymentOptions = aTradeItem.getPaymentOptions();
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(ImageUtils.dpToPx(16), ImageUtils.dpToPx(4), ImageUtils.dpToPx(16), ImageUtils.dpToPx(4));
LinearLayout.LayoutParams lineparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ImageUtils.dpToPx(1));
lineparams.setMargins(0, ImageUtils.dpToPx(4), 0, ImageUtils.dpToPx(4));
if (paymentOptions != null && paymentOptions.size() > 0) {
for (PaymentOption t : paymentOptions) {
LinearLayout paymentOptionLayout = new LinearLayout(getContext());
paymentOptionLayout.setOrientation(LinearLayout.HORIZONTAL);
paymentOptionLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
TextView heading = new TextView(getContext());
heading.setText(t.getDescription());
heading.setTextColor(getResources().getColor(R.color.light_text));
heading.setLayoutParams(lp);
paymentOptionLayout.addView(heading);
rl.addView(paymentOptionLayout); //adding the view to the parent view
}
}
Please note that from the looks of your code, you're really just reimplementing listView which is an available layout in android. I think you should take a look at that.
getContext() is a method of activity class. It returns the context view only for currently running activity.
For Fragment either pass the instance of current activity class via constructor or use getActivity() method or this instead of getContext()
See here for help
Using context in a fragment
How to add view into LinearLayout of Fragment by onClick?
Also add paymentOptionLayout to the parent layout view right after for loop.

Create ImageView and TextView in HorizontalScrollView

I want to create a TextView over an ImageView in my Android-App. I know I need a RelativeLayout for this, but I don't know how to create this in my main.java (NOT in XML).
It should be dynamic, so I want to create a for-loop which creates many ImageViews with a TextView over it in a HorizontalScrollView.
This is my approach
LinearLayout sv = (LinearLayout) findViewById (R.id.LinearLayout1);
for (int i=1 ; i<=3; i++){
String uri = "drawable/test"; //only one picture several times
int imageResource = getResources().getIdentifier(uri, null, getPackageName());
ImageView iv = new ImageView (this);
iv.setBackgroundResource (imageResource);
sv.addView(iv);
}
This only add ImageViews to my HorizontalScrollView (LinearLayout is located in the HorizontalScrollView), but now I also want to add TextViews over my ImageViews. I tried lot of things but nothing works.. I despair.
Hopefully someone can help me
PS: Sorry for my spelling mistakes, I'm from Germany
If you know it to design in xml, create a XML and inflate it.
Below is the code that explains, How to use it.
Code Snippet
//Parent View
LinearLayout sv = (LinearLayout) findViewById (R.id.LinearLayout1);
//infalter service
LayoutInflater inflater = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Loop to create all the child views
for (int i=0; i<=3; i++) {
//Refrence your layout xml here
LinearLayout childView= inflater. inflates (R. layout. your_xml, null);
//Get refrence to your button and imageview using childView
//add child view
sv.addView(childView);
}
//add sv to horizontal scroll view
Dude try custom views. Create one XML file and create one basic layout . And then inflate that view as many time as u want don't do with for loop. I thnk u r new in android.
http://androidexample.com/Dynamically_Create_View_Elements__-_Android_Example/index.php?view=article_discription&aid=115&aaid=137

android : getting an item from a textview to another textview?

i'm having two layout files. The first layout file containing some data in textview and the another layout containing one empty textview. Now, i want to pass the first layout's textview data to new layout textview when i'm using button in first layout. How can i use this? Thanks in advance.
Basically you can do like this, in button click,get the view of second layout
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.secondlayout, parent, false);
and use below statement to get id of second textview
TextView text2=(TextView)row.findViewById(R.id.SecondTextView)
then get the text in the first textview using id of first one into String:
String s=text1.getText().toString();
then set this String to 2nd textview.
text2.setText(s);
If, textview2 is the textview from second layout. and the
//to get data from text view of first layout use the following code
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View vi = inflater.inflate(R.layout.layout1, null);
TextView tv1 = (TextView) vi.findViewById(R.id.textview1);
// to set of first textview in second textview
textview2.setText(tv1.getText().toString

Categories