android - 动态 inflatedView 的问题

标签 android android-layout view layout-inflater

我正在向当前 View 动态添加布局。即使但问题是即使我在光标中有两个以上的值也只有一个 View 被夸大了。

这意味着旧数据被覆盖。但我想在 phoneCrsr 中为每条记录添加新 View 。

我做错了什么???

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

最佳答案

当您将 View 添加到您的“主”布局时,您是在向两个方向的 FILL_PARENT 发出指令:

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

如果您添加一个填满整个 LinearLayout 的 View ,您将只能看到它。当您添加另一个时,它在一个方向上“偏离边缘”(取决于 orientation)。如果您尝试垂直添加它们,请将高度更改为 WRAP_CONTENT。对于水平布局,更改宽度。

您可能还想简化您的 addView 调用。一方面,不必将其转换为 ViewGroup。您也可以完全跳过 LayoutParams 构造函数,直接将宽度和高度传递给带有 simpler call 的父级。 .这样的事情应该有效:

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

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

关于android - 动态 inflatedView 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21990518/

相关文章:

android - 将值从 Activity 传递到 View 类

asp.net-mvc - 如何强制执行 ASP.NET MVC 中的关注点分离?

android - 如何将 OpenCV 4.0 集成到纯 C++ Android NDK 项目中?

android - 如何为 chrome 设置可调试标志?

带有 LruCache 的 Android BaseAdapter 一些 ui 问题

android - 在 ViewPager 中使用具有相同布局的不同 fragment

android - Gradle找不到kotlin编译器版本

android - 重新排列/重新格式化(命令+ ALT + L)代码时在android studio中设计标签顺序更改

Android studio TextViews 随 android_below 一起消失

wpf - WPF中的条件列表项目模板或数据模板