我有3个不同的视图组需要在LinearLayout中添加。我使用addView()
添加它。
但是,添加是基于我的Web服务返回的响应。如果没有数据,它将向UI回调视图将为空。
基本上,有3种观点是特色,最新和类别。我希望精选在顶部,然后是最新和类别。
我正在调用这样的网络服务,
public void loadFromApis() {
dealsService.getFeaturedDeals(this);
dealsService.getLatestDeals(this);
dealsService.getDealsCategories(this);
}
成功回调(包含数据)和视图添加的示例:
@Override
public void onFeaturedSuccess(List<FeaturedModel> model) {
View view1 = DealsPanel.build(this, model);
linearLayout.addView(view1, 0);
}
@Override
public void onLatestSuccess(List<LatestModel> model) {
View view2 = DealsPanel.build(this, model);
linearLayout.addView(view2, 1);
}
@Override
public void onCategoriesSuccess(List<CategoriesModel> model) {
View view3 = DealsPanel.build(this, model);
linearLayout.addView(view3, 2);
}
我已尝试使用索引参数设置位置,但由于我是根据API响应加载视图,因此布局无法知道哪个视图首先绘制,因此初始化索引会导致IndexOutOfBoundsException
错误。
我的问题是,基于这个要求,我如何静态定义要添加的每个视图的位置等等?有关改进此代码结构的任何建议吗?
提前致谢
答案 0 :(得分:1)
一种方法是在父级LinearLayout中静态定义代码或XML中的3个子布局,然后将新视图添加到子布局中。这将保持他们的秩序。例如:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout android:id="@+id/featuredDealsLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<LinearLayout android:id="@+id/latestDealsLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<LinearLayout android:id="@+id/dealCategoriesLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
然后,假设您初始化包含新布局的变量(即featuresDealsLayout),您可以将代码更改为:
@Override
public void onFeaturedSuccess(List<FeaturedModel> model) {
View view = DealsPanel.build(this, model);
featuredDealsLayout.addView(view);
}
@Override
public void onLatestSuccess(List<LatestModel> model) {
View view = DealsPanel.build(this, model);
latestDealsLayout.addView(view);
}
@Override
public void onCategoriesSuccess(List<CategoriesModel> model) {
View view = DealsPanel.build(this, model);
dealCategoriesLayout.addView(view);
}