android - Android上的渐变按钮颜色变化

标签 android button background-color

我想在点击之后逐渐改变按钮颜色。我的意思是,按钮必须有,例如下一组颜色:默认情况下 - 深蓝色,然后是深蓝色,然后是蓝色,然后是浅蓝色,最后 - 最浅的蓝色。这只是示例,我真的想循环更改按钮颜色,就像在下一个代码中一样。但是,我不明白,为什么它不显示中间色。它只显示第一种颜色和最后一种颜色。

如何改进?

public class ActivityExample extends Activity {
private changeColorBtn;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_animations);

    changeColorBtn = (Button) findViewById(R.id.btn_change_color);

    changeColorBtn.setBackgroundColor(Color.BLACK);
    changeColorBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            changeButtonColor(v);

        }
    });

}

private void changeButtonColor(View v) {
    // How many intermediate color will be, and delay in millisecond between them
    int count = 20, delay = 100;
    for (int i = 0; i < count; i++) {
        try {

            int color = ((ColorDrawable) changeColorBtn.getBackground())
                    .getColor();
            int blue = Color.blue(color), red = Color.red(color), green = Color.green(color);
            changeColorBtn.setBackgroundColor(Color.rgb(red+10, green+5, blue+3));

            Thread.sleep(delay);
        } catch (InterruptedException inE) {
        }
    }

}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

最佳答案

我使用 TransitionDrawable 解决了这个问题.您可以按照下一步操作:

  • 在 drawable 文件夹中创建一个 xml 文件,并在其中写入如下内容:

`

<?xml version="1.0" encoding="UTF-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/color1" />
    <item android:drawable="@color/color2" />
</transition>

`

  • 然后,在这个按钮(或另一个元素/ View )的 xml 中,您应该引用这个 TransitionDrawableandroid:background 属性中。
  • 您还应该将颜色存储为资源:为此,您必须创建如下所示的 xml:

`

<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <color name="color1">#990000</color>
    <color name="color2">#cc3311</color>
</resources>

`

并将此 xml 文件保存在/res/values/文件夹中,将 xml 命名为 color.xml。

  • 并在代码中启动转换:

`

int durationMillis = 2000;
TransitionDrawable transition = (TransitionDrawable) changeColorBtn.getBackground();
transition.startTransition(durationMillis);

`

这对我有帮助,希望对其他人有用。

关于android - Android上的渐变按钮颜色变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16354271/

相关文章:

Android WebClient,通过WebResourceResponse 返回图像资源 - 不显示图像

Android JWPlayer 全屏显示方向更改并保留视频

java - GWT 中的拖动和切换按钮类似于 Ubuntu 12.04 切换按钮

android - 在 Android 的 textview [ Html.fromhtml() ] 中使用多种文本颜色

android - 多个 ACTION_DOWN 事件做同样的事情

甲骨文顶点按钮

html - CSS 背景渐变,图像

emacs - 如何更改 emacs 中行号模式的背景颜色?

Javascript:根据单词更改单词颜色?

java - Android:对 EditText 中的字母进行排序