我在自定义 SupportMapFragment 布局时遇到了一些问题。我基本上想在地图片段布局的底部添加一个自定义视图。
我设法以编程方式将视图添加到片段中,如下所示:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View mapView = super.onCreateView(inflater, container, savedInstanceState);
View customView = inflater.inflate(R.layout.custom_view, container, false);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) customView.getLayoutParams();
params.gravity = Gravity.BOTTOM;
customView.setLayoutParams(params);
FrameLayout wrapper = new FrameLayout(inflater.getContext());
wrapper.addView(mapView);
wrapper.addView(customView);
return wrapper;
}
custom_view布局是一个简单的CardView,没有复杂的逻辑:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/custom_view_root"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:visibility="gone"
app:cardBackgroundColor="@color/white"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
... some basic content
</LinearLayout>
</android.support.v7.widget.CardView>
问题是我的自定义视图没有显示在底部,而是显示在顶部。似乎我设置的重力属性没有考虑在内。我还尝试使用 RelativeLayout 作为包装器并手动添加规则以在底部对齐自定义视图,但结果是相同的。
LE: 正如@Budius 在他的回答中提到的,我忽略了inflate ()方法的ViewGorup 根参数。
这是使用布局中设置的参数的正确实现:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
FrameLayout wrapper = new FrameLayout(inflater.getContext());
View mapView = super.onCreateView(inflater, container, savedInstanceState);
wrapper.addView(mapView);
customView = inflater.inflate(R.layout.custom_view, wrapper, false);
wrapper.addView(customView);
return wrapper;
}
另一个解决方案是以编程方式创建自定义视图的参数,如下所示:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View mapView = super.onCreateView(inflater, container, savedInstanceState);
customView = inflater.inflate(R.layout.custom_view, container, false);
FrameLayout wrapper = new FrameLayout(inflater.getContext());
wrapper.addView(mapView);
FrameLayout.LayoutParams params =
new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT,
Gravity.BOTTOM);
wrapper.addView(customView, params);
return wrapper;
}