How to make an irregular shape component clickable? Android

一世执手 提交于 2021-02-11 12:01:27

问题


I want to make a clickable component with this irregular shape, but I have no idea how I could do it, I have been looking for a couple of days but I have not seen any solution. There should be text and images inside the component.

Any suggestion?

Thank you


回答1:


With the Material Components Library you can define CornerTreatment to apply to the components.
There are some built-in CornerTreatment like CutCornerTreatment or RoundedCornerTreatment but you can built your own CornerTreatment.

Something like:

class ConcaveRoundedCornerTreatment : CornerTreatment() {

  override fun getCornerPath(
      shapePath: ShapePath,
      angle: Float,
      interpolation: Float,
      radius: Float
  ) {
    val interpolatedRadius = radius * interpolation
    shapePath.reset(0f, interpolatedRadius, ANGLE_LEFT, ANGLE_LEFT - angle)
    shapePath.addArc(
        -interpolatedRadius,
        -interpolatedRadius,
        interpolatedRadius,
        interpolatedRadius,
        ANGLE_BOTTOM,
        -angle
    )
  }

  companion object {
    const val ANGLE_LEFT = 180f
    const val ANGLE_BOTTOM = 90f
  }
}

And just apply it to the Button:

<com.google.android.material.button.MaterialButton
    android:id="@+id/concave"
    app:cornerRadius="16dp"
    ..>

with:

    val materialButton = findViewById<MaterialButton>(R.id....)
    val concaveRoundedCornerTreatment = ConcaveRoundedCornerTreatment()

    materialButton.shapeAppearanceModel = materialButton.shapeAppearanceModel.toBuilder()
            .setTopRightCorner(concaveRoundedCornerTreatment)
            .build()




回答2:


create a shape drawable like this:

 <?xml version="1.0" encoding="utf-8"?>
 <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
        <solid android:color="@color/colorPrimary" />
        <stroke
            android:width=".05dp"
            android:color="#d2d2d2" />
        <corners
            android:bottomLeftRadius="10dp"
            android:bottomRightRadius="10dp"
            android:topLeftRadius="10dp"
            android:topRightRadius="10dp" />
    </shape>
</item>
<item
    android:bottom="410dp"
    android:left="100dp"
    android:right="-100dp"
    android:top="-300dp">
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="oval">

        <solid android:color="#ffffff" />
    </shape>
</item>

then set this drawable as background for your view(eg:linearlayout) Note:please adjust the dimensions according to your need



来源:https://stackoverflow.com/questions/62237512/how-to-make-an-irregular-shape-component-clickable-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!