gpt4 book ai didi

Android 自定义形状按钮

转载 作者:IT王子 更新时间:2023-10-28 23:59:53 24 4
gpt4 key购买 nike

如何在 Android 中制作自定义形状的可点击 View 或按钮?

当我点击时,我想避免触摸空白区域。

enter image description here

请帮忙。谢谢你。

最佳答案

有趣的问题。我尝试了一些解决方案,这就是我发现的与您想要实现的结果相同的结果。以下解决方案解决了 2 个问题:

  1. 按照您展示的方式自定义形状
  2. 按钮的右上角不应是可点击的

所以这是分三步解决的方法:

步骤 1

创建两个形状。

  • 按钮的第一个简单矩形形状:shape_button_beer.xml

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <gradient
    android:angle="90"
    android:endColor="#C5D9F4"
    android:startColor="#DCE5FD" />

    <corners
    android:bottomLeftRadius="5dp"
    android:bottomRightRadius="5dp"
    android:topLeftRadius="5dp" >
    </corners>

    </shape>
  • 第二个形状用作按钮右上角的掩码:shape_button_beer_mask.xml。这是一个简单的黑色纯色圆圈。

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval" >

    <solid android:color="#000000" />

    </shape>

第二步

在您的主布局中,通过下一种方法添加按钮:

  • RelativeLayout 是这个自定义按钮的容器
  • 第一个 LinearLayout 是蓝色按钮,里面有啤酒图标和文字
  • 第二个 ImageView 是蓝色按钮上方的掩码。这是肮脏的把戏:
    1. 边距为负数以将掩码设置在正确的位置
    2. 我们将 id 定义为能够在点击时覆盖(参见第 3 步)
    3. android:soundEffectsEnabled="false" - 这样用户就不会觉得他按下了什么东西。

XML:

    <!-- Custom Button -->
<RelativeLayout
android:layout_width="120dp"
android:layout_height="80dp" >

<LinearLayout
android:id="@+id/custom_buttom"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@drawable/shape_button_beer" >

<!-- Beer icon and all other stuff -->

<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="15dp"
android:src="@drawable/beer_icon" />
</LinearLayout>

<ImageView
android:id="@+id/do_nothing"
android:layout_width="120dp"
android:layout_height="100dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="-50dp"
android:layout_marginTop="-50dp"
android:background="@drawable/shape_button_beer_mask"
android:soundEffectsEnabled="false" >
</ImageView>
</RelativeLayout>
<!-- End Custom Button -->

第三步

在您的主要 Activity 中,您为两个按钮和掩码定义点击事件,如下所示:

LinearLayout customButton = (LinearLayout) findViewById(R.id.custom_buttom);
customButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View arg0)
{
Toast.makeText(getApplicationContext(), "Clicked", Toast.LENGTH_SHORT).show();
}
});

// Mask on click will do nothing
ImageView doNothing = (ImageView) findViewById(R.id.do_nothing);
doNothing.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View arg0)
{
// DO NOTHING
}
});

就是这样。我知道这不是一个完美的解决方案,但在您描述的用例中它可能会有所帮助。我已经在我的手机上测试过了,当你点击蓝色区域时它是这样的,其他区域什么都不会发生:

  • enter image description here

希望它以某种方式有所帮助:)

关于Android 自定义形状按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13861416/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com