使用 onclick 事件更改按钮的颜色
Changing color of buttons with onclick events
我正在尝试创建一个包含 100 个按钮和自定义颜色选择器的网格。当我单击一个随机按钮时,它应该将其背景更改为选定的颜色。不幸的是,我坚持以下几点:
MainActivity:
我不确定如何分别为每个按钮自动执行 onclick 事件,因为 onclick 函数无法识别在内部 class.
中单击了哪个按钮
我正在使用带有自定义适配器的 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" />
欢迎提出任何建议!
试试这个:
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);
}
};
试试这个:
Button button = (Button)findViewById(R.id.grid_button);
button.setOnClickListener(new View.OnclickListener()
{
@Override
public void onClick(View view){
button.setBackgroundColor("#4FC3F7");
}
};
我正在尝试创建一个包含 100 个按钮和自定义颜色选择器的网格。当我单击一个随机按钮时,它应该将其背景更改为选定的颜色。不幸的是,我坚持以下几点:
MainActivity: 我不确定如何分别为每个按钮自动执行 onclick 事件,因为 onclick 函数无法识别在内部 class.
中单击了哪个按钮我正在使用带有自定义适配器的 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" />
欢迎提出任何建议!
试试这个:
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);
}
};
试试这个:
Button button = (Button)findViewById(R.id.grid_button);
button.setOnClickListener(new View.OnclickListener()
{
@Override
public void onClick(View view){
button.setBackgroundColor("#4FC3F7");
}
};