动态膨胀视图的问题

时间:2014-02-24 14:24:15

标签: android android-layout view layout-inflater

我正在为当前视图动态添加布局。即使问题是即使我在游标中有两​​个以上的值也只有一个视图被夸大了。

这意味着重写了旧数据。但我想在phoneCrsr中为每条记录添加新视图。

我做错了什么???

            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();

1 个答案:

答案 0 :(得分:2)

当您将视图添加到“主”布局时,您会在两个方向上将其告知FILL_PARENT

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

如果你添加一个填满整个LinearLayout的视图,那就是你所见过的全部内容。当你添加另一个时,它在一个方向上“离开边缘”(取决于orientation)。如果您尝试垂直添加它们,请将高度更改为WRAP_CONTENT。对于水平布局,请更改宽度。

您也可能希望简化addView来电。对于一件事情,没有必要将它投射到ViewGroup。您也可以完全跳过LayoutParams构造函数,只需将宽度和高度直接传递给父simpler call即可。这样的事情应该有效:

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

总而言之,Raghunandan的评论是最好的“答案”。你可能应该使用ListView,因为它正是它的设计目的。

相关问题