我正在尝试以编程方式在位于框架布局中的线性布局中添加两个TextView。 xml代码是:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/ll_dynamic"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginStart="20dp"
android:orientation="vertical" >
</LinearLayout>
<com.anheuserbusch.hifive.util.TextViewFiftySeven
android:id="@+id/txt_no_badges"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:visibility="gone"
android:textColor="@color/app_default_font_color"
android:text="@string/no_badges_yet"/>
</FrameLayout>
ll_dynamic 是线性布局,我在其中以编程方式添加视图。
代码:
for (int i = 0; i < 10; i++)
{
TextViewFiftySeven txtIncentiveName = new TextViewFiftySeven(context);
TextViewFiftySeven txtDate = new TextViewFiftySeven(context);
//for Incentive name
LinearLayout.LayoutParams llptextname = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
llptextname.setMargins(0, 10, 0, 0); // llp.setMargins(left, top, right, bottom);
//for date
LinearLayout.LayoutParams llptextdate = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
llptextdate.setMargins(0, 1, 0, 0); // llp.setMargins(left, top, right, bottom);
txtIncentiveName.setLayoutParams(llptextname);
txtIncentiveName.setTextColor(ContextCompat.getColor(context, R.color.app_default_font_color));
txtIncentiveName.setText("Summer Incentive");
txtDate.setLayoutParams(llptextdate);
txtDate.setTextColor(ContextCompat.getColor(context, R.color.app_default_font_color));
txtDate.setText("23.2.2015");
holder.ll_dynamic.addView(txtIncentiveName);
holder.ll_dynamic.addView(txtDate);
System.out.println("Looping-->"+i);
if (i != badgeCount - 1) {
LinearLayout.LayoutParams llhorizontalLine = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 2);
llhorizontalLine.setMargins(0, 20, 0, 0); // llp.setMargins(left, top, right, bottom);
View horizontalLine = new View(context);
horizontalLine.setLayoutParams(llhorizontalLine);
horizontalLine.setBackgroundColor(ContextCompat.getColor(context, R.color.gray_light));
holder.ll_dynamic.addView(horizontalLine);
}
}
问题是,视图没有以编程方式添加。但是,如果我删除框架布局,则会根据需要呈现视图。显然,由于框架布局,这是一个问题。但我需要保持框架布局。
那么,如果视图位于框架布局中,为什么视图不会动态添加到线性布局中?
答案 0 :(得分:0)
正如您在documentation of the FrameLayout中所读到的那样,它只适用于一个子布局。
FrameLayout旨在阻挡屏幕上的某个区域以显示单个项目。通常,FrameLayout应该用于保存单个子视图,因为很难以可扩展到不同屏幕大小而儿童不会相互重叠的方式组织子视图。
但您可以使用layout-gravity
但是,您可以使用android:layout_gravity属性将多个子项添加到FrameLayout并通过为每个子项分配重力来控制它们在FrameLayout中的位置。
因此,在您的情况下,您可以在layout-gravity
下的布局xml中添加TextViewFiftySeven
属性,并且每次以编程方式添加视图。