Question

I am adding a layout dynamically to current view. Even if but problem is that even if i had more then two values in cursor Only one view is inflated.

It means old data is overridden. But i want to add new view per record in phoneCrsr.

What I'm doing wrong ???

            Cursor phoneCrsr = database.rawQuery(phoneSql, null);
            while(phoneCrsr.moveToNext()){
                phone_number = new ArrayList<String>();                 
                String number = phoneCrsr.getString(phoneCrsr.getColumnIndex(MySQLiteHelper.COLUMN_PHN_NUMBER));

                if(!number.isEmpty()){
                    phone_number.add(number);                   

                    LayoutInflater inflator = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    View view = inflator.inflate(R.layout.phone_number_textview, null);

                    // fill in any details dynamically here
                    TextView phoneTv = (TextView) view.findViewById(R.id.phone_number);
                    phoneTv.setText(number);

                    // insert into main view
                    LinearLayout phoneLayout = (LinearLayout) findViewById(R.id.phone_info);
                    phoneLayout.setVisibility(View.VISIBLE);
                    ((ViewGroup) phoneLayout).addView(view, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));

                    //phoneLayout.setPadding(20,0,0, 0);
                    //phoneLayout.setBackgroundColor(Color.WHITE);      
                }                   
                Log.e("PHONE DETAIL:",phone_number.toString());
            }
            phoneCrsr.close();
Was it helpful?

Solution

When you add the view to your "main" layout, you're telling it to FILL_PARENT in both directions:

((ViewGroup) phoneLayout).addView(view, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));

If you add a view that fills an entire LinearLayout, that's all you'll ever see. When you add another one, it's "off the edge" in one direction(depending on orientation). If you're trying to add them vertically, change the height to WRAP_CONTENT. For a horizontal layout, change the width.

You also might want to simplify your addView call in general. It shouldn't be necessary to cast it to ViewGroup, for one thing. You can also skip the LayoutParams constructor completely and just pass a width and height directly to the parent with a simpler call. Something like this should work:

phoneLayout.addView(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.FILL_PARENT);

All in all, though, Raghunandan's comment is the best "answer". You should probably be using a ListView for this, since it's exactly what it was designed for.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top