Populating very long linear layout with custom views, extremely slow - android

i'm trying to populate a linear layout with a list of custom views like in the picture:
To achieve this i'm inflating the foo.xml in a new View object, then i change the textviews using .setText and then i add the new View to the linear layout.
The problem is: it is extremely slow, even outside the emulator, taking more than 10 seconds to display in my S9.
LinearLayout layout = findViewById(R.id.layout);
while(a<500){
Person person = new Person();
View personData = inflater.inflate(R.layout.person, layout, false);
layout.addView(personData);
((TextView) coinData.findViewById(R.id.textView_text_name)).setText(person.name);
a=a+1
}
EDIT: Thank you guys! I'm gonna try RecyclerView right now

For creating a list use RecyclerView which is just advanced version of traditional ListView
You can Follow tutorial for Recycler View Here.

Related

How to dynamic insert elements of a string array into textview and position it?

I get the list of elements from the HTTP response, then I want to dynamically insert that list into the textview inside the "box" that you can see, currently it just inserts a string and overlaps them one over the other. I tried changing the layout (all three constraint, relative and linear) and it didn't help. Does anyone know how to position them dynamicly inside the boxes and not overlap but have margins like in the second picture? Otherwise, inside the project, I use a constrain layout.
Here is my code:
RelativeLayout parentLayout = (RelativeLayout) findViewById(R.id.layout);
int size = response.toArray().length;
final TextView[] tv = new TextView[size];
TextView temp;
for (int i = 0; i < size; i++)
{
temp = new TextView(Activity.this);
temp.setText(response.get(i).getName());
parentLayout.addView(temp);
tv[i] = temp;
}
Here is the picture how it looks right now:
And here is the picture how I want it to looks like:
This sounds like a typical ListView use case.
Firstly, I'd suggest you go through the documentation -
https://developer.android.com/reference/android/widget/ListView
You can see an implementation example of a list view with an array of strings here -
https://androidexample.com/Create_A_Simple_Listview_-_Android_Example/index.php?view=article_discription&aid=65
In general, you choose the UI of your item and the listView populates the view to each item in your list (each string in your case).
In the adapter, you give each item the data it needs for the UI.
I would suggest you to use RecyclerView for this type of task. You may use ListView as well.
But RecyclerView is more flexible and advanced than ListView.
Create a simple layout or xml file for your row item to be shown in RecyclerView.
Add that row xml file in onCreateViewHolder method. And inside method onBindViewHolder do necessary task like for example, showing name in the list for each position.
Go to this link for your reference : https://developer.android.com/guide/topics/ui/layout/recyclerview
Instead of Array<String> you can use Array<CustomModel> as well depending on your requirement.
Simple example of RecyclerView with model objects as list : https://www.javatpoint.com/android-recyclerview-list-example
Well, the proper way to do what you need is use ListView or RecyclerView.
Anyway, if you want to use your current solution, you need to specify the position of each TextView.
For example, assign an ID to each textview you create and then set the position of it under the previous one. Here you can find how to do that.

Adding a custom view multiple times in a layout

I have a custom XML file. I want to repeat this in a layout (say Relative) n number of times, dynamically (obviously).
I have seen many posts, but none helped. I am not looking for a ListView or Adapters or so. It's as simple as - A RelativeLayout. Inside it, adding the custom XML one above another. Any number of times.
With a static LinearLayout (Vertical orientation), adding the view dynamically results in rendering it once, not one below another. Don't know why. Although a TextView or so do repeat one below the other in a loop inside a LinearLayout (Vertical).
Then I dynamically created the layout (Relative), and inflated the custom XML. Displayed one. When I tried for another below the first it told me to remove child's parent first (Exception). If I do that and add again, its as good as removing the first rendered view and adding it again.
So how can I get multiple views in same layout?
A rough presentation of what I've attempted:
mainLayout = (RelativeLayout)findViewById(R.id.mainlay); //Mainlayout containing some views already
params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW,R.id.sideLayout); //sideLayout is an existing LinearLayout within the main layout.
View child = getLayoutInflater().inflate(R.layout.dynamiccustomlayout,null);
RelativeLayout r1 = new RelativeLayout(this);
r1.setLayoutParams(params);
r1.addView(child);
mainLayout.addView(r1);
mainLayout.setLayoutParams(params);
mainLayout.addView( child);
/* r2 = new RelativeLayout(this);
r2.setLayoutParams(params);
r2.addView(contentLayout); [Gives exception] */
This is how it worked out for me...
Before that, the issue with android is:
If you add dynamic views inside a LinearLayout (Horizontal), they will appear horizontally with new created instances, added to the view.
However, shockingly, it's not the same in case of LinearLayout (Vertical orientation). Hence the whole mess.
Solution:
The RelativeLayout layout file was binded with the variable, somewhat like this:
customLay = (RelativeLayout) mainLay.findViewById(R.id.dynamicCustomLayout);
Then, a Dynamic RelativeLayout was created within which the former variable is added/wrapped.
customLayout = new RelativeLayout(this);
customLayout.addView(customLay);
Every layout is assigned an id:
customLayout.setId(i);
And then a loop is run (2 if conditions for i=0 and i>0)
for i>0 (indicates the 2nd dynamic layout, to be added below the first), LayoutParameter is created:
params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
And then for i>0, using the ids of dynamic views, they are added one below the other:
//Following code below used id to place these views below each other to attain list type arrangement of views//
// i==0 for first view on top//
if (i == 0) {
params.addRule(RelativeLayout.BELOW, R.id.sideLayout);
customLayout.setLayoutParams(params);
}
// i>0 for views that will follow the first top//
else {
params.addRule(RelativeLayout.BELOW, i - 1);
customLayout.setLayoutParams(params);
}
Then added to main root layout, where all these views or cards need to be displayed:
includeLayout.addView(customLayout);
Ofcourse, the code is not just this. I have written the essential points that helped me achieve the target and that may help others in future.
So the main essence was ---
using a Dynamic RelativeLayout, to
bind the static RelativeLayout, and
assigning ids to the Dynamic RelativeLayout wrappers, and
on basis of ids use RelativeLayoutParameters to place the following
ids below the previous ones.
You have to instanciate every child by itself
View child = getLayoutInflater().inflate(R.layout.dynamiccustomlayout,null);
r1.addView(child);
View child2 = getLayoutInflater().inflate(R.layout.dynamiccustomlayout,null);
r1.addView(child2);
//ok, i do a analog thing in obne of my apps. here is the code:
public class FlxForm extends LinearLayout {
public FlxForm(Context context) {
super(context);
inflater = LayoutInflater.from(context);
inflater.inflate(R.layout.flxform, this);
this.setPadding(0, 0, 0, 0);
container = (LinearLayout) this.findViewById(R.id.flxform);
this.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
//here is my funtion to calculate the items i want to add, its a little bit too complicated, but in the end it works like:
for(int i=0;i<10;i++){
View x = inflater.inflate(R.layout.dynamiccustomlayout,null);
container.addview(x);
}
}
}
XML for the Form
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/flxform"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:focusable="false"
android:background="#android:color/transparent"
android:orientation="vertical" >
</LinearLayout>
Then you can instantiate a "Form" Objekt and add it into a ScrollView
For doing this You would have to nest your RelativeLayout inside a ScrollView and Manage all the Scrolling, items adding, memory management, etc manually.
So the simple solution for adding n Number of Custom Views is to use a RecyclerView, ListView, GridView, etc with a neat CustomAdapter and Your Custom View.
Here is a nice example of using RecyclerView with custom Adapter :
http://code.tutsplus.com/tutorials/getting-started-with-recyclerview-and-cardview-on-android--cms-23465
I hope this Helps.

Android Overlapping Image Views

I want to create this sort of a view where the cross should be separate image view as I want it to be clickable. How can I achieve this ?
It would be great If I can create this view programatically as I am a dynamic list of images and I am programatically creating the image Views. All I need now is to add the overlapping imageview as well.
Thanks in advance
Use FrameLayout and you can overlay views on top of each other
Ex:
FrameLayout frame = (FrameLayout) findViewById(R.id.frame);
ImageView image = new ImageView(this);
iv.setImageResource(R.drawable.image);
ImageView cross = new ImageView(this);
i.setImageResource(R.drawable.cross);
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.RIGHT | Gravity.TOP;
i.setLayoutParams(layoutParams);
frame.addView(image);
frame.addView(cross);
Create a RelativeLayout programmatically, which contains two ImageViews. Place your image in the first one, and your second image in the second one. Adjust the margins accordingly to place it in the top right corner.
First create a completely new layout to use as an placeholder for example "partial_layout.xml". Then in your code first make a LayoutInflater with something like this:
LayoutInflater mInflater = (LayoutInflater) this.getSystemService(this.LAYOUT_INFLATER_SERVICE);
then try to get a fresh copy of this layout with something like this:
View convertView = mInflater.inflate(R.layout.partial_layout, null);
now put your current data to this view, and finally add this view to your content view.
If you create a list of views, you can still use XML by inflating it only when needed - just watch the lecture "the world of listView" in order to do it correctly. Using ListView is much more efficient than creating as many views as the number of items to show (for example, if there are 100 images to show, only those that are on screen need to be created).
Anyway, the xml can contain either FrameLayout or RelativeLayout as the root view, and you just put the 2 imageViews according to the right position you wish to have. You can use the UI designer for this, or edit the XML itself by adding margin-top for the larger image. also, make sure the larger image is written there before the small one.
as for the clicking, you can use setOnClickListener on the small imaveView.
BTW, if it's just images, you should probably use GridView instead of ListView.

How to add blocks of linearLayouts and is there a better way?

This is the main idea of what I am trying to do.
I would like to ask you what is the best way to make such a design. the problem is that these gray/black blocks might not show up (user will choose which should show up). So I would like to find out do I need to make these 3 text views inside linearLayout programatically? Is there anyway to create some sort of template which I would only have to edit by setting new texts for textViews and add them to some sort of layout?
Another option is to just have a LinearLayout and an xml for the row entry. Then you can do:
LinearLayout layout = (LinearLayout) this.findViewById(R.id.your_layout_id);
List<Blocks> userBlocks = getMyUserBlocks();
for(Block b : userBlocks) {
View blockView = LayoutInflater.from(getBaseContext())
.inflate(R.layout.your_row_layout, layout, false);
TextView someData = (TextView) blockView.findViewById(R.id.your_text_view_id);
someData.setText(b.someAttribute.toString());
layout.addView(blockView);
}
You will need a separate xml layout for the block row.
You can use a ListView with large dividers. Your dark gray blocks are the row views, and you can just append them to a dataset and update the adapter for the ListView. For the dividers, see setDivider() and setDividerHeight().

Dynamically add UI content in android

I have an android app which asks a question followed by x number of options.
Each option contains a textview, ImageView and a radio button.
The value of x (i.e. the number of options) is not constant. I want to dynamically add UI content to satisfy this requirement.
At the moment I have written the code in the layout's xml to display a maximum of 4 options. If number of options is 2 I hide the options 3 and 4 using something like
tvoption1.setVisibility(View.GONE);
tvoption2.setVisibility(View.GONE);
However this is not very scalable. Can anyone tell me how to add options for java dynamically. Or is there a better approach?
A View can be added at runtime by using the inflater like this:
LinearLayout linearLayout = (LinearLayout)inflater.inflate(R.layout.news_categories_item, null);
TextView categoryValueTextView = (TextView)linearLayout.findViewById(R.id.news_category_item_value);
mMainLinearLayout.addView(categoryValueTextView);
In this example, a LinearLayout containing a TextView is inflated. A reference to the constituent TextView is then obtained, and the TextView is dynamically added (at runtime) to the main linear layout (mMainLinearLayout).
The inflater object may be obtained in an Activity by using getLayoutInflater().
create your row layout separately, from the main xml
Get LayoutInflater service from context:
LayoutInflater inflater=(LayoutInflater)getSystemService(LAYOUT_INFLATE_SERVICE);
use following method to addview to main xml, I assume you have parent layout llParent in xml and you want to add items in this llPaent, from list list.
for(int i=0;i<list.size();i++)
{
LinearLayout llView=(LinearLayout)inflater.inflate(R.layout.row);
//get view id and set values
TextView txt=(TextView)llView.findViewById(R.id.text);
}
A ListView is a good view for displaying several similar items. Here is a tutorial (Other views with adapters are good too, such as GridView or Gallery).
You will probably want to create your own adapter for the list, so you can display all three views (checkbox, image and text) as one item, but there are lots of examples on that available on the net as well as here on SO.

Categories

Resources