【问题标题】:Changing color of buttons with onclick events使用 onclick 事件更改按钮的颜色
【发布时间】:2018-04-03 01:24:26
【问题描述】:

我正在尝试创建一个包含 100 个按钮和一个自定义颜色选择器的网格。当我单击一个随机按钮时,它应该将其背景更改为选定的颜色。不幸的是,我坚持以下几点:

MainActivity: 我不确定如何分别为每个按钮自动执行 onclick 事件,因为 onclick 函数无法识别在内部类中单击了哪个按钮。

我正在使用带有自定义适配器的 gridview:

Adapter: 在我的 Gridview 中实现的适配器 --> linearlayout.pixel 是我的按钮的 xml 文件。

代码linearlayout.pixel:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp" >


<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=""
    android:background="@drawable/my_button"
    android:id="@+id/grid_button"
    />

代码可绘制 my_button:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="3dp" />
<stroke android:width="5px" android:color="#000000" />

欢迎提出任何建议!

【问题讨论】:

    标签: android button gridview onclick baseadapter


    【解决方案1】:

    试试这个:

      buttons[i]=new Button(this);
        buttons.setId(i);
        buttons[i].setOnClickListener(new View.OnclickListener()
        {
           @Override
           public void onClick(View view){
               buttons[view.getId()].setBackgroundColor(color);
           }
        };
    

    【讨论】:

    • 感谢您的反馈,不幸的是,由于某种原因,这不起作用。虽然问题已解决,但我仍然感谢您抽出宝贵时间回答我。
    【解决方案2】:

    试试这个:

    Button button = (Button)findViewById(R.id.grid_button);
    button.setOnClickListener(new View.OnclickListener()
    {
       @Override
       public void onClick(View view){
           button.setBackgroundColor("#4FC3F7");
       }
    };
    

    【讨论】:

    • 祝你好运兄弟:)
    猜你喜欢
    • 2015-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    相关资源
    最近更新 更多