gpt4 book ai didi

Android:如何将自定义元素放在圆圈/目标上

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:21:16 24 4
gpt4 key购买 nike

我需要创建一种目标并向其添加对象,当我直接点击它们时,它们具有不同的颜色并执行不同的操作。

关于如何实现这一点有什么建议吗?也许有我可以使用的图书馆?

circles on phone circles with custom objects selected item

最佳答案

正式的解决方案是

drawable 中创建 roundedshape.xml

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

<shape
android:innerRadiusRatio="4"
android:shape="ring"
android:thicknessRatio="5"
android:useLevel="false">
<solid android:color="#af08d7" />
<size
android:width="25dip"
android:height="25dip"></size>
</shape>
</item>
</layer-list>

添加 RelativeLayout 具有 android:background="@drawable/roundedshape"

<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="300dp"
android:padding="50dp"
android:background="@drawable/roundedshape"
android:id="@+id/myRelativeLayout"
>

</RelativeLayout>

在您的 Activity 中添加这些代码以动态生成 ImageButtons 并添加到 Layout 中。

    RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.myRelativeLayout);

for (int j = 0; j < 4; j++) {
ImageButton myImageButton = new ImageButton(this); //generate ImageButton
myImageButton.setId(j); //Set Id of button
//Generate Random Number to place ImageButtons in random position
int min = 40;
int max = 60;
Random r = new Random();
int randomNum = r.nextInt(max - min + 1) + min;


myImageButton.setBackgroundResource(R.drawable.chatbox); //Set background of ImageButton
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100, 100);
params.leftMargin = randomNum+j*randomNum; //Generate left margin dynamically
params.topMargin = randomNum +j*randomNum; //Generate right margin dynamically
relativeLayout.addView(myImageButton, params); //Add view
myImageButton.setOnClickListener(getButtonAndDoAction(myImageButton)); //Add OnClickListener
}

Activity 中添加此方法来处理图像按钮的点击事件。

View.OnClickListener getButtonAndDoAction(final ImageButton button)  {
return new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(MainActivity.this, "button clicked" +button.getId(), Toast.LENGTH_SHORT).show();
}
};

结果:

enter image description here

注意: 我添加了注释以使代码尽可能清晰

关于Android:如何将自定义元素放在圆圈/目标上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35943638/

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