Круглый только верхний угол карты
Я хочу убрать только верх карты.
Я использовал свойство ниже и округляет весь угол.
Я хочу показать перекрытие всех карт
card_view:cardCornerRadius="4dp"
вот мой макет
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
card_view:cardCornerRadius="4dp"
card_view:cardPreventCornerOverlap="false"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="@+id/re1">
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="@color/colorAccent"
android:text="contact det"
android:gravity="center_vertical"
android:textColor="@android:color/white"
android:textSize="14dp"/>
<TextView
android:id="@+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:gravity="center_vertical"
android:textSize="10dp"
android:layout_below="@id/title"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp"/>
<TextView
android:id="@+id/txtSurname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Surname"
android:gravity="center_vertical"
android:textSize="10dp"
android:layout_below="@id/txtName"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp"
/>
<TextView
android:id="@+id/txtEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email"
android:textSize="10dp"
android:layout_marginTop="10dp"
android:layout_alignParentRight="true"
android:layout_marginRight="150dp"
android:layout_alignBaseline="@id/txtName"/>
<TextView
android:id="@+id/txtAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address"
android:textSize="10dp"
android:layout_alignLeft="@id/txtEmail"
android:layout_alignBaseline="@id/txtSurname"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
Ответы
Ответ 1
Мы можем установить marginBottom вида карты в отрицательном значении. Margin должен быть таким же значением, как радиус карты.
Например,
<FrameLayout
android:id="@+id/rootview"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:id="@+id/card_view"
android:layout_marginBottom="-3dp"
project:cardCornerRadius="3dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--The child view inside the cardview should have extra padding,so that negative margin will not affect the bottom padding of its child.Here normally we have 16dp bottom padding for child + margin bottom of the parent is 3dp=19dp comes.-->
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="19dp"/>
</android.support.v7.widget.CardView>
</FrameLayout>
Это работает для меня. Но я сомневаюсь, что это правильный способ делать. Все предложения приветствуются.
Ответ 2
Я пробовал то же самое, но ни одно из предложенных решений не помогло мне.
Единственное, что сработало, было:
1) Создайте собственный фоновый ресурс (например, прямоangularьную форму) с закругленными углами.
2) установить этот пользовательский фон с помощью команды -
cardView = view.findViewById(R.id.card_view2);
cardView.setBackgroundResource(R.drawable.card_view_bg);
отлично сработало для меня! Надеюсь, это поможет вам.
Макет XML, который я сделал с верхним левым и нижним правым радиусом.
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/white" />
<corners android:topLeftRadius="18dp" android:bottomRightRadius="18dp" />
</shape>
В вашем случае вам нужно изменить только topLeftRadius, а также topRightRadius.
Ответ 3
Карт Android, который позволяет настраивать круглую угловую позицию.
ссылка: https://github.com/captain-miao/OptionRoundCardview
![введите описание изображения здесь]()
Ответ 4
Сложная вещь, потому что вы не можете заставить CardView сделать это. Внутренне он использует RoundRectDrawable
(закрытый пакет), который использует roundRect
следующим образом:
// rectf, rx, ry, paint
canvas.drawRoundRect(mBoundsF, mRadius, mRadius, paint);
Поэтому вам нужно другое решение, например, я нашел эту суть Ахмеда-Абдельмедеда, где они используют обрезку холста для каждого угла, используя путь для описания контура.
Так что, хотя я не тот, кто создал этот код, я опубликую его здесь для будущих путешественников.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="RoundedView">
<attr name="topLeftCornerRadius" format="dimension" />
<attr name="topRightCornerRadius" format="dimension" />
<attr name="bottomLeftCornerRadius" format="dimension" />
<attr name="bottomRightCornerRadius" format="dimension" />
</declare-styleable>
</resources>
и
package com.abdelmeged.ahmed.roundedlayout;
/**
* Created by ahmed on 9/17/2017.
*/
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Region;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
/**
* Custom wrapper view to get round corner round view
*/
public class RoundedView extends FrameLayout {
/**
* The corners than can be changed
*/
private float topLeftCornerRadius;
private float topRightCornerRadius;
private float bottomLeftCornerRadius;
private float bottomRightCornerRadius;
public RoundedView(@NonNull Context context) {
super(context);
init(context, null, 0);
}
public RoundedView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0);
}
public RoundedView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
TypedArray typedArray = context.obtainStyledAttributes(attrs,
R.styleable.RoundedView, 0, 0);
//get the default value form the attrs
topLeftCornerRadius = typedArray.getDimension(R.styleable.
RoundedView_topLeftCornerRadius, 0);
topRightCornerRadius = typedArray.getDimension(R.styleable.
RoundedView_topRightCornerRadius, 0);
bottomLeftCornerRadius = typedArray.getDimension(R.styleable.
RoundedView_bottomLeftCornerRadius, 0);
bottomRightCornerRadius = typedArray.getDimension(R.styleable.
RoundedView_bottomRightCornerRadius, 0);
typedArray.recycle();
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
@Override
protected void dispatchDraw(Canvas canvas) {
int count = canvas.save();
final Path path = new Path();
float[] cornerDimensions = {
topLeftCornerRadius, topLeftCornerRadius,
topRightCornerRadius, topRightCornerRadius,
bottomRightCornerRadius, bottomRightCornerRadius,
bottomLeftCornerRadius, bottomLeftCornerRadius};
path.addRoundRect(new RectF(0, 0, canvas.getWidth(), canvas.getHeight())
, cornerDimensions, Path.Direction.CW);
canvas.clipPath(path);
super.dispatchDraw(canvas);
canvas.restoreToCount(count);
}
public void setTopLeftCornerRadius(float topLeftCornerRadius) {
this.topLeftCornerRadius = topLeftCornerRadius;
invalidate();
}
public void setTopRightCornerRadius(float topRightCornerRadius) {
this.topRightCornerRadius = topRightCornerRadius;
invalidate();
}
public void setBottomLeftCornerRadius(float bottomLeftCornerRadius) {
this.bottomLeftCornerRadius = bottomLeftCornerRadius;
invalidate();
}
public void setBottomRightCornerRadius(float bottomRightCornerRadius) {
this.bottomRightCornerRadius = bottomRightCornerRadius;
invalidate();
}
}
Это позволит вам обрезать края изображений и видов до их рендеринга, поэтому он делает именно то, что вы хотите.
Ответ 5
В соответствии с вопросом, я предполагаю, что вы хотите применить свойство углового радиуса только к верхней части карты. Вы можете получить этот эффект, используя два CardView
. Поместите один CardView
внутри другого CardView
и удалите внешний атрибут угла CardView
. Также примените прозрачный фон к внешнему CardView
. Ваш внутренний CardView будет иметь значение cornerRadius 4dp. Затем примените marginTop к вашему внутреннему CardView
, так что его нижняя часть будет скрыта внешним CardView
. Таким образом, нижний угловой радиус вашего внутреннего CardView
будет скрыт.
Вам нужно будет разместить свой xml-контент в Inner CardView
. Внешний CardView
служит только для скрытия нижних закругленных углов внутреннего CardView
.
Ваш xml-макет будет выглядеть так:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view_outer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
card_view:cardBackgroundColor="@android:color/transparent"
card_view:cardCornerRadius="0dp"
card_view:cardElevation="4dp" >
<android.support.v7.widget.CardView
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="3dp"
card_view:cardElevation="0dp"
card_view:cardCornerRadius="4dp"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="@+id/re1">
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="@color/colorAccent"
android:text="contact det"
android:gravity="center_vertical"
android:textColor="@android:color/white"
android:textSize="14dp"/>
<TextView
android:id="@+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:gravity="center_vertical"
android:textSize="10dp"
android:layout_below="@id/title"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp"/>
<TextView
android:id="@+id/txtSurname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Surname"
android:gravity="center_vertical"
android:textSize="10dp"
android:layout_below="@id/txtName"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp"
/>
<TextView
android:id="@+id/txtEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email"
android:textSize="10dp"
android:layout_marginTop="10dp"
android:layout_alignParentRight="true"
android:layout_marginRight="150dp"
android:layout_alignBaseline="@id/txtName"/>
<TextView
android:id="@+id/txtAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address"
android:textSize="10dp"
android:layout_alignLeft="@id/txtEmail"
android:layout_alignBaseline="@id/txtSurname"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</android.support.v7.widget.CardView>
Я взял ссылку на этот вопрос SO: Question.
Я надеюсь, что он решает вашу проблему.