我有一个 fragment ,它从 rest api 获取项目并在 ScrollView 中的 LinearLayout 中显示项目标题。
下面是我的观点和代码。
fragment _卡片_view.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/scrollView"
android:fillViewport="true">
<LinearLayout
android:id="@+id/linear_card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:background="@color/wallet_holo_blue_light"/>
</ScrollView>
list_item.xml
RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:layout_marginBottom="10dp">
<TextView
android:id="@+id/list_titleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title"
style="@style/item_header"/>
</RelativeLayout>
</RelativeLayout>
标题 fragment .java
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i(TAG, "In onCreateView");
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_cards_view, container, false);
mLinearLayout = (LinearLayout)v.findViewById(R.id.linear_card_view);
return v;
}
private void createUpcomingView() {
int counter = 0;
for (User user : mUsers) {
LayoutInflater inflater = null;
inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mLinearView = inflater.inflate(R.layout.list_item, null);
mLinearView.setId(user.getId());
TextView titleTextView = (TextView)mLinearView.findViewById(R.id.list_titleTextView);
titleTextView.setText("title " + counter);
mLinearLayout.addView(mLinearView);
counter++;
}
}
我遇到的问题是,如果项目数量小于屏幕高度,显示就会不正确。
此屏幕截图有 4 个项目,但它只显示第一个项目并且边距未正确对齐。
这个屏幕截图有很多项目,边距正确对齐。
这个截图是第一种方案:
最佳答案
从 list_item.xml 中删除以下布局,然后它将正常工作。
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:layout_marginBottom="10dp">
</RelativeLayout>
关于如果项目数量小于屏幕高度,Android LinearLayout 无法正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29715265/