Reputation: 2264
I'm currently writting an android application and I'd like it to be well written/designed.
Right now I have a set of multiples views (2 images views, 3 textviews) in a relative layout that I use pretty often. Is there any way to create a custom view that regroup them all?
I've took this screenshot to explain what I've done right now:
As you can see, right now I've just copied/pasted my framelayout which contain all my views... Is this the proper way to do it or there's a cleaner solution?
Thanks guys
Upvotes: 2
Views: 129
Reputation: 41099
No a better way would be to put all the content you putting in you layouts in a ArrayList
of objects.
and then create an ArrayAdapter
to populate a ListView
from this objects the way you want.
The advantage of this technic is that you gain a Views recycle mechanism that will recycle the Views
inside you ListView
in order to spend less memory.
In Short you would have to:
1. Create an object that represents your data for a single row.
2. Create an ArrayList
of those objects.
3. Create a layout that contains a ListView or add a ListView to you main layout using code.
4. Create a layout of a single row (you already have it).
5. Create a ViewHolder
that will represent the visual aspect of you data row from the stand point of Views
.
6. Create a custom ArrayAdapter
that will populate the rows according to you needs.
7. Finally assign this ArrayAdapter
to your ListView
in onCreate
.
You can get an Idea of how to implement this by reading this blog post I wrote:
Upvotes: 2
Reputation: 1099
If you do it in code instead of the interface builder you can use LayoutInflator to create a view from your xml each time, and then add those views as subviews to your LinearLayout. This would also allow you to vary the number without having to copy paste each new view.
LayoutInflater layoutInflator = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout ll = (LinearLayout) findViewById(R.id.yourLayout);
for(int i=0; i<numOfSubViews; i++){
View view = layoutInflator.inflate(R.layout.yourFrameLayout, null);
ll.add(view);
}
Upvotes: 0