i需要在卡片视图中添加边框,而我发现这样做的方式(在Stackoverflow中(正在内部创建Framelayout,并在其上添加形状背景。这种方法效果很好,但是现在我需要将其扩展到自定义布局,以避免每次使用此cardViewWithBorders!
重复此代码!当前代码看起来像这样:
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:elevation="4dp"
app:cardCornerRadius="4dp"
app:cardUseCompatPadding="true">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/shape_border_corner_radius"
android:padding="16dp">
<EditText
android:id="@+id/fieldInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/transparent"
android:lineSpacingMultiplier="1.5"
android:textAppearance="@style/LatoRegular"
android:textSize="16sp"
tools:hint="Type in your E-mail" />
</FrameLayout>
</android.support.v7.widget.CardView>
我想要的就是拥有CardView和Framelayout的组成部分,我可以这样使用:
<com.example.BorderCardView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<content goes here />
</com.example.BorderCardView>
我该怎么做才能实现这种行为?
您很幸运,您的"内部"视图是FrameLayout
,并且CardView
扩展了Framelayout,因为这意味着您不需要担心孩子的确切类型'LayoutParams
对象。
public class BorderCardView extends CardView {
public BorderCardView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
FrameLayout.LayoutParams params =
new FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT);
FrameLayout frame = new FrameLayout(getContext());
frame.setLayoutParams(params);
frame.setBackground(/* your background drawable */);
frame.setPadding(/* your left/top/right/bottom padding */);
while (getChildCount() > 0) {
View child = getChildAt(0);
FrameLayout.LayoutParams childParams =
(FrameLayout.LayoutParams) child.getLayoutParams();
removeView(child);
frame.addView(child);
child.setLayoutParams(childParams);
}
addView(frame);
}
}
您在这里做的是动态创建您的"内部" FrameLayout
,然后从布局中循环绕过所有孩子,将其从CardView
中删除,然后将它们添加到FrameLayout
中,然后最终添加"内部"帧到CardView
。