I am using a ListView to display some JSON data and want to display each result according to its type (Artist, Release, Label...).
I will be using an interface implemented by each type of result :
public interface Result {
public Int getId();
public String getThumb();
// ...
}
I would like to know which of these choices is the best solution (I am open to better things, that's just what I had on the top of my head):
creating an enum ResultType in the interace (so inherited class will have to return their own value like ResultType.ARTIST in a getType() method
checking the instance type using isInstance()
I would like to know what would be the best way to perform something equivalent to this C code (array of function pointer) as I would like to avoid using to many if/else statements.
typedef struct s_func {
const char *type_name;
void* (*func_pointer)(void *result_infos);
} t_func;
static t_func type_array[] = {
{"artist", artist_function},
{"label", label_function},
// ....
{NULL, NULL}
}
void check_type(const char *type_string)
{
int i, j = 0;
char *key_value;
// compare string and array key
while (type_array && type_array[i][0]) {
key_value = type_array[i][0];
// if key match
if (type_string && strncmp(type_string, key_value, strlen(type_string)) == 0) {
type_array[i][1](); // call appropriate function;
}
i++;
}
}
I guess it would be using a HashMap but (I might be wrong) it doesn't seem to have a litteral notation. Is there any easy way to build an HashMap of pairs ?
Thank you
I think you can use an ArrayAdapter.
Take a look at this tutorial to see what I mean.
It'll need some twiddling so that it can deal with the different kinds of items.
Make an interface MyListItem
public interface MyListItem {
public int getLayout();
public void bindToView(View v);
}
Make different layouts for the display of Artist, Release, Label.
Make classes Artist, Release, Label that implement MyListItem.
public class Artist implements MyListItem {
private String Name;
public Artist(String name){
this.name = name;
}
public int getLayout() {
return R.layout.artistlayout;
}
public void bindToView(View v) {
TextView textView = (TextView) rowView.findViewById(R.id.artistLabel);
textView.setText(name);
}
}
Now the adapter only has to call the right methods to fill the view for the selected item.
public class MySimpleArrayAdapter extends ArrayAdapter<MyListItem> {
private final Context context;
private final MyListItem[] values;
public MySimpleArrayAdapter(Context context, MyListItem[] values) {
super(context, android.R.layout.simple_list_item_1, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyListItem item = values[position];
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(item.getLayout(), parent, false);
item.bindTo(view);
return view;
}
}
Related
I've written a game where the user inputs the number of player and every player gets an own tab with an empty table.
Therefore I used a PagerAdapterClass (extends FragmentStatePagerAdapter) and a viewpager.
So every player has the same fragmentView.
Now the user can put variables into the table, bu everytime I switch between the tabs, the input gets lost.
Well, i 'fixed' that problem by adding this to my pageradapter:
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
}
But it's more stopping the viewpager from destroying than actually saving the data.
My main goal is to really save that stuff in that table.
I already tried https://stackoverflow.com/a/17135346/11956040 but i cannot get mContent because i cannot get the reference of the fragment, because all fragments are not created on their own but all at the same time (or something like that).
I also don't know how to set a Tag.
This way: https://stackoverflow.com/a/18993042/11956040
doesn't work for me.
MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Toolbar toolbar = findViewById(R.id.toolbar2);
setSupportActionBar(toolbar);
...
//numPlayer = num of tabs
SectionsPagerAdapter adapter = new SectionsPagerAdapter(numPlayer, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(adapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
if(numPlayer >= 5) {
tabs.setTabMode(TabLayout.MODE_SCROLLABLE);
}
}
PagerAdapter:
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
private int tabNum;
public SectionsPagerAdapter(int tabNum, FragmentManager fm) {
super(fm);
this.tabNum = tabNum;
}
#Override
public PlaceholderFragment getItem(int position) {
return PlaceholderFragment.newInstance(position);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
int playerNum = position + 1;
return "Spieler " + playerNum;
}
#Override
public int getCount() {
// Show 2 total pages.
return tabNum;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
}
}
Fragment:
public static PlaceholderFragment newInstance(int index) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle bundle = new Bundle();
bundle.putInt("player", index);
fragment.setArguments(bundle);
return fragment;
}
There must be a solution but I cannot find it or cannot implement it.
Pls help.
Solved my problem this way:
define 2 dimensional ArrayList for rows and columns and counter for columns:
private ArrayList<ArrayList<Integer>> columnArray;
private int column;
onCreateView (for fragments) set column = 0 and add one entry with an empty list to columnArray
and set the first rowList on column index of columnArray:
pointArray.add(column, new ArrayList<Integer>());
final ArrayList<Integer> rowList = pointArray.get(column);
fill the empty rowListwith 0 (maybe it also works in an other way, but I made it this way to have on empty EditTexts a 0 and can easily replace them)
define View.OnFocusChangeListener for all EditTexts like this:
/*I dont know if I could set column final in general,
but you need to set a final int because you call this value in an inner class*/
final int pos = column
for (int i = 0; i <= getEditTexts(pos).size() - 1; i++) {
EditText editTexts = getEditTexts(pos).get(i);
final String editTextsTag = editTexts.getTag().toString();
View.OnFocusChangeListener listener = new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, final boolean b) {
if (view.getTag().toString().equals(editTextsTag) && !b) {
//fills rowList
addEntries(pos, rowList);
//adds rowList to columnArray
columnArray.set(pos, rowList);
//save the columnsArray or use it
saveData(columnArray);
}
}
};
editTexts.setOnFocusChangeListener(listener);
define method which collects data from each cell, depending on column position (pos), add it to rowList
for example:
private void addEntries(int pos, ArrayList<Integer> rowList) {
for(int i = 0; i <= 16; i++) {
//this requires EditText_label, i made them dynamically
String edit_label = "edit_" + pos + i;
EditText editText = table.findViewWithTag(edit_label);
String mEditTextString = editText.getText().toString();
try {
int thisValue = Integer.parseInt(mEditString);
rowList.set(j, thisValue);
} catch (NumberFormatException e) {
//maybe you do not need this, but I need it for something else
int thisValue = 0;
rowList.set(j, thisValue);
}
}
}
define a method for saving the columnArray. I used an interface to give it to parent Activity: Here you can find how I made it
Otherwise you can convert the columnArray to a String and save it in a database.
NOTE
I made it with column value set beacuse I increase the value for every column I add during runtime using a method. If you just have one column, you dont need to set it. Just use 0 instead of pos, column
I am using a Custom ArrayAdapter to store User information for example sammy, robert, lizie are each one User objects and i am using a User type ArrayList to store all the User objects to ArrayList.
And because it is not a string or int (The ArrayList) the default getFilter does not work, and i have done my research but it is really confusing how the getFilter method works so i can modify myself.
I want to implement the searching based on the name property form the User class
I know i have to implement the Filterable interface in my CustomAdapter class, but the getFilter is really unintuitive.
Here is my CustomAdapter
class CustomArrayAdapter extends ArrayAdapter<User> implements Filterable {
CustomArrayAdapter(#NonNull Context context, ArrayList<User> users) {
super(context, 0, users);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
User innserUser = getItem(position);
if (convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_layout, parent, false);
}
TextView username = (TextView) convertView.findViewById(R.id.userNameContact);
TextView userNumber = (TextView) convertView.findViewById(R.id.userNumberContact);
ImageView userImage = (ImageView) convertView.findViewById(R.id.userImageContact);
try {
if(innserUser != null) {
username.setText(innserUser.name);
userNumber.setText(innserUser.number);
userImage.setImageBitmap(innserUser.imageBitmap);
}
}catch (Exception e){
e.printStackTrace();
}
return convertView;
}
}
and here is the user class nothing special here
import android.graphics.Bitmap;
public class User {
String id, name, number;
Bitmap imageBitmap;
User(String id, String name, String number, Bitmap imageBitmap){
this.id = id;
this.name = name;
this.number = number;
this.imageBitmap = imageBitmap;
}
}
I tied alot of variations of the getFilter from many threads but none of them work for me ,and the one's with good explanations are for BaseAdapter not for ArrayAdapter
I have tried this question and i have tried this question but does not work for me.
I am new to android development field, and this seems particularly unintuitive.
Any suggestions would be really appreciated, thank you.
EDIT 1: After the answer of jitesh mohite, Thanks for the replay jitesh mohite
class CustomArrayAdapter extends ArrayAdapter<User> implements Filterable {
ArrayList<User> users;
CustomArrayAdapter(#NonNull Context context, ArrayList<User> users) {
super(context, 0, users);
this.users = users;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
User innserUser = getItem(position);
if (convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_layout, parent, false);
}
TextView username = (TextView) convertView.findViewById(R.id.userNameContact);
TextView userNumber = (TextView) convertView.findViewById(R.id.userNumberContact);
ImageView userImage = (ImageView) convertView.findViewById(R.id.userImageContact);
try {
if(innserUser != null) {
username.setText(innserUser.name);
userNumber.setText(innserUser.number);
userImage.setImageBitmap(innserUser.imageBitmap);
}
}catch (Exception e){
e.printStackTrace();
}
return convertView;
}
Filter myFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
ArrayList<User> tempList=new ArrayList<User>();
// Add the filter code here
if(constraint != null && users != null) {
int length= users.size();
int i=0;
while(i<length){
User item= users.get(i);
//do whatever you wanna do here
//adding result set output array
//item.name is user.name cause i want to search on name
if(item.name.toLowerCase().contains(constraint.toString().toLowerCase()) ) { // Add check here, and fill the tempList which shows as a result
tempList.add(item);
}
i++;
}
//following two lines is very important
//as publish result can only take FilterResults users
filterResults.values = tempList;
filterResults.count = tempList.size();
}
return filterResults;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence contraint, FilterResults results) {
users = (ArrayList<User>) results.values;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
#Override
public Filter getFilter() {
return myFilter;
}
}
the search is not working on the customadapter still i think i am doing something wrong.
here i am typing something in the search bar but no filtering happens
and if you want to see the searchbar code its nothing special just the usual
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.search_box, menu);
MenuItem item = menu.findItem(R.id.app_bar_search);
SearchView searchView = (SearchView)item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
customArrayAdapter.getFilter().filter(newText);
return false;
}
});
return true;
}
ArrayAdapter's built-in Filter uses the toString() return from the model class (i.e., its type parameter) to perform its filtering comparisons. You don't necessarily need a custom Filter implementation if you're able to override User's toString() method to return what you want to compare (provided its filtering algorithm is suitable to your situation). In this case:
#Override
public String toString() {
return name;
}
To be clear on exactly what that algorithm is, ArrayAdapter's default filtering goes as follows:
The filter String is first converted to lowercase. Then, looping over the dataset, each value's toString() return is converted to lowercase, and checked to see if it startsWith() the filter String. If so, it's added to the result set. If not, a second check is performed, whereby the value's lowercase String is split on a space (" "), and each value from that is compared to the filter, again using startsWith(). Basically, it first checks if the whole thing starts with the filter text, and then checks each word, if necessary.
If that's a suitable filter, then this solution is by far the simplest.
If that does not meet your needs, and you do actually need a custom Filter implementation, then you should just not use ArrayAdapter to begin with. ArrayAdapter maintains internal, private Lists for the original and filtered collections – initially populated from the collection passed in the constructor call – and you do not have access to those. This is why the custom Filter attempt shown does not work, as the displayed item count and the item returned from getItem(position) are coming from that internal filter List, not the one built in the custom Filter.
In that case, you should directly subclass BaseAdapter instead, maintaining your own Lists for the original and filtered collections. You can use ArrayAdapter's source as a guide.
Indeed, ArrayAdapter is often the wrong choice when choosing an Adapter to extend. ArrayAdapter is designed for a singular, somewhat simplistic goal: setting a flat String on a single TextView in each list item. There are several cases in which subclassing ArrayAdapter instead of BaseAdapter is rather pointless and/or redundant. For example:
Overriding getView() and not using the View returned from a call to super.getView().
Manually setting the text on the TextView yourself, for whatever reason.
Maintaining and using your own collections; i.e., the arrays, or Lists, or what have you.
In these and certain other cases, it's arguably better to use BaseAdapter from the start. Using ArrayAdapter for anything much more complex than single text items with basic functionality can quickly become cumbersome and error-prone, and is often more trouble than it's worth.
Lastly, I would mention that ListView is basically deprecated, at this point, though not yet officially, at the time of this writing. Current recommendations are to use RecyclerView instead. However, for those brand new to Android programming, ListView can still be useful as a beginning step in understanding the overall design of this type of recycling adapter View. RecyclerView can be a little overwhelming to start with.
Filter myFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
ArrayList<User> tempList=new ArrayList<User>();
// Add the filter code here
if(constraint != null && users!=null) {
int length= users.size();
int i=0;
while(i<length){
User item= users.get(i);
//do whatever you wanna do here
//adding result set output array
if() { // Add check here, and fill the tempList which shows as a result
tempList.add(item);
}
i++;
}
//following two lines is very important
//as publish result can only take FilterResults users
filterResults.values = tempList;
filterResults.count = tempList.size();
}
return filterResults;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence contraint, FilterResults results) {
users = (ArrayList<User>) results.values;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
Lastly, Override this method and return filter instance.
#Override
public Filter getFilter() {
return myFilter;
}
For more reference see https://gist.github.com/tobiasschuerg/3554252
I'm trying to pass the int pub_or_priv from my Activity1 to Myadapter.
I've looked at posts here and I think I've followed them correctly but it's still not working. The value in my adapter is always 0 whereas it should be 0,1 or 2, as is the case with the value in my Activity1.
Here's what I've done.
In my Activity1 I get "publicorprivate" from my server and convert it to an int with:
//convert public_or_private to an integer
pub_or_priv = Integer.parseInt(obj.getString("publicorprivate"));
For different cells in my recyclerView it will be 0,1 or 2.
Now I want to pass this to my adapter so in my adapter contructor I have:
public MyAdapter(List<Review> reviewUsers, Activity activity, int pub_or_priv) {
this.activity = activity;
the_reviews = reviewUsers;
this.mPub_or_priv = pub_or_priv;
}
And in my Activity1:
pAdapter = new MyAdapter(reviewList, this, pub_or_priv);
Then in MyAdapter:
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {
Review r = the_reviews.get(position);
//shared_status will be Just U, Private or Public
String shared_status ="";
if(mPub_or_priv==0){
//change colour depending on value
((ReviewHolder) viewHolder).phone_user_name.setTextColor(Color.parseColor("#DA850B"));
shared_status = "Just U";
}
if(mPub_or_priv==1){
((ReviewHolder) viewHolder).phone_user_name.setTextColor(Color.parseColor("#0A7FDA"));
shared_status = "Private";
}
if(mPub_or_priv==2){
((ReviewHolder) viewHolder).phone_user_name.setTextColor(Color.parseColor("#2AB40E"));
shared_status = "Public";
}
((ReviewHolder) viewHolder).phone_user_name.setText(shared_status);
etc..etc..
However in the recyclerView in all cells the phone_user_name textbox is always "Just U", in the #DA850B colour, whereas in fact it is supposed to be Private and Public in some cells, as per the pub_or_priv value in Activity1.
How can I get pub_or_priv correctly into my adapter?, thanks.
It looks like you're using one value in the activity/adapter, so of course all rows show the same value.
In the adapter, use the value in the Review instance that corresponds to the current cell:
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {
Review review = the_reviews.get(position);
int pubOrPriv = review.getPublicOrPrivate();
//shared_status will be Just U, Private or Public
String shared_status = "";
if (pubOrPriv == 0) {
//change colour depending on value
((ReviewHolder) viewHolder).phone_user_name.setTextColor(Color.parseColor("#DA850B"));
shared_status = "Just U";
}
if (pubOrPriv == 1) {
((ReviewHolder) viewHolder).phone_user_name.setTextColor(Color.parseColor("#0A7FDA"));
shared_status = "Private";
}
if (pubOrPriv == 2) {
((ReviewHolder) viewHolder).phone_user_name.setTextColor(Color.parseColor("#2AB40E"));
shared_status = "Public";
}
//.............
}
I'm using ParseQueryAdapter to display a ListView including the set of elements given by the Parse query:
ParseQueryAdapter.QueryFactory<AlertObject> factory =
new ParseQueryAdapter.QueryFactory<AlertObject>() {
public ParseQuery<AlertObject> create() {
ParseQuery<AlertObject> query = AlertObject.getQuery();
query.orderByDescending(AlertObject.TIMESTAMP_KEY);
query.fromLocalDatastore();
return query;
}
};
alertsListAdapter = new AlertListItemAdapter(activity, factory, thisFragment);
ListView alertsListView = (ListView) rootView.findViewById(R.id.alerts_list_view);
alertsListView.setAdapter(alertsListAdapter);
Now, I'd like to know the number of items in the ListView, but if I call alertsListView.getCount(), it returns 0. What am I doing wrong?
EDIT: someone gave this post a negative vote, but without leaving a comment or a request for clarification. So, I ask for some explanation about the reason of that in order to improve the readability of my question.
UPDATE: below my adapter
public class AlertListItemAdapter extends ParseQueryAdapter<AlertObject> {
private Context context;
private Fragment listAlertsFragment;
public AlertListItemAdapter(Context context,
ParseQueryAdapter.QueryFactory<AlertObject> queryFactory,
Fragment fragment) {
super(context, queryFactory);
this.context = context;
this.listAlertsFragment = fragment;
}
#Override
public View getItemView(final AlertObject alertObject, View view, final ViewGroup parent) {
[...]
}
#Override
public int getCount() {
return super.getCount();
}
}
I suspect (cannot be sure without seeing the Parse code/docs) that the adapter is not immediately populated with items, and when the query is executed, it'll call notifyDataSetChanged() on itself so that the ListView requeries it for item Views.
This would explain why your getCount() returns 0 immediately after setAdapter(ListAdapter) but why you can also see 33 items.
You can verify this logging adapter.getCount() as you do, and in addition, overriding notifyDataSetChanged to then observe the order of statements:
public class AlertListItemAdapter extends ParseQueryAdapter<AlertObject> {
public AlertListItemAdapter(
Context context,
ParseQueryAdapter.QueryFactory<AlertObject> queryFactory,
Fragment fragment) {
super(context, queryFactory);
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
Log.d("FOO", "item count: " + getCount());
}
#Override
public View getItemView(AlertObject alertObject, View view, ViewGroup parent) {
Log.d("FOO", "getItemView()");
...
}
...
}
If you need to know when the data changes, you can register a dataset changed listener on the adapter:
adapter.registerDataSetObserver(new DataSetObserver() {
#Override
public void onChanged() {
super.onChanged();
Log.d("Foo", adapter.getCount());
}
});
Are you sure you populated your ListView with parse AlertObjects?
I think you should add something like this to your query:
query.findInBackground(new FindCallback<AlertObject>() {
#Override
public void done(List<AlertObject> alerts, ParseException e) {
if (e == null) {
// Success
mAlerts = alerts;
String[] alertObjects = new String[mAlerts.size()];
Log.v(TAG, "There are " + mAlerts.size() + “ on the parse");
}
} else {
Log.e(TAG, e.getMessage());
}
}
});
Log can tell you how many objects you have on Parse.
In this Callback you can populate your ListView and then use
.getCount();
on your alertListAdapter.
Make sure you pass, store, and override the getCount() method correctly.
Please provide the code of adapter class if possible
Simply write following line to get number of items in the list view:
int count = alertsListView.alertsListAdapter().getCount();
After:
alertsListView.setAdapter(alertsListAdapter);
So your code will look like:
alertsListAdapter = new AlertListItemAdapter(activity, factory, thisFragment);
ListView alertsListView = (ListView) rootView.findViewById(R.id.alerts_list_view);
alertsListView.setAdapter(alertsListAdapter);
int count = alertsListView.alertsListAdapter().getCount();
I'm a newcomer on Android and in the Google Guide I'm in this part: http://developer.android.com/training/basics/data-storage/databases.html.
Yes, it's about the dabatase, but to put it in practice, in my dummy studying app I created a simple system for store "profiles" to have something to store in the database. Basically, I've created an Activity for fill some text fields and store it in the database. And a class called ProfileDao that do the CRUD stuff.
I've reached a point where I want to build an activity to show all profiles added, using a LinearLayout. The problems is that I can't stack the views in code as the XML does.
Here is some code:
The ProfileFragment class:
public final class ProfileFragment extends Fragment {
private String _name;
private String _gender;
private int _age;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View retVal = inflater.inflate(R.layout.profile_fragment, container, false);
final TextView _nameField = (TextView) retVal.findViewById(R.id.profile_fragment_name);
final TextView _genderField = (TextView) retVal.findViewById(R.id.profile_fragment_gender);
final TextView _ageField = (TextView) retVal.findViewById(R.id.profile_fragment_age);
_nameField.setText(_name);
_genderField.setText(_gender);
_ageField.setText(String.valueOf(_age));
return retVal;
}
public void setName(String name) { _name = name; }
public void setGender(String gender) { _gender = gender;}
public void setAge(int age) { _age = age; }
public String getName() { return _name; }
public String getGender() { return _gender; }
public int getAge() { return _age; }
}
My intent initially was to use this fragment to dinamically put it in a LinearLayout, but I quickly saw I can't do this and made this class just a util for return a view.
The SeeProfilesActivity:
public class SeeProfilesActivity extends Activity {
private static final String TAG = makeLogTag(SeeProfilesActivity.class);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.see_profiles_activity);
final ProfileDao profDao = new ProfileDao(new ProfileDbHelper(this));
final List<Profile> profiles = profDao.getProfiles();
LOGD(TAG, "PROFILES RETRIEVED");
if(profiles.size() == 0) {
final TextView thereisNotProfiles = new TextView(this);
thereisNotProfiles.setText(getString(R.string.there_is_not_profiles));
thereisNotProfiles.setTextSize(35);
LOGD(TAG, "NO PROFILES, SO JUST DISPLAY THERE IS NOT");
setContentView(thereisNotProfiles);
return;
}
addFragmentProfiles(profiles);
}
private void addFragmentProfiles(List<Profile> profiles) {
final LinearLayout itLayout = (LinearLayout) ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
itLayout.setOrientation(LinearLayout.VERTICAL);
View currView;
for(Profile prof : profiles) {
final ProfileFragment profFrag = new ProfileFragment();
profFrag.setName(prof.getName());
profFrag.setGender(prof.getGender());
profFrag.setAge(prof.getAge());
LOGD(TAG, "WELL, ONE PROFILE WAS RETRIEVED");
currView = profFrag.onCreateView(getLayoutInflater(), itLayout, null);
itLayout.addView(currView);//here is my problem
LOGD(TAG, "SUCCESS IN DISPLAY");
}
}
}
How do I reproduce the behaving of stacking the views present in a LinearLayout XML in code?
Before some objections:
I know some of you will say there's a better way to do it, mainly the experient developers (maybe saying I can use ListView with adapters. Yes, I know it, but I didn't reach this part of the guide yet). But, get the fact I'm a very fresh beginner and really want to do this by hand to enjoy the maximum of what a learn.
Change the fragment layout "profile_fragment" height is wrap_content,not fill or match parent.
My english is not well,I hope you can understand ....
R.Layout.profile_fragment:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" // This is your problem.
android:orientation="vertical" >