如何在线程

时间:2016-06-26 14:10:27

标签: android multithreading

我有一个按钮btnSwitch,我想让闪光灯闪烁,背景颜色会持续改变,只要我按住按钮并在我释放手指时停止这样做的颜色背景是白色和黑色,闪光灯工作正常,但背景只改变一次黑色,永远不会返回白色。

这是代码:

public class MainActivity extends AppCompatActivity {
    public static RelativeLayout relativeLayout;
    public Button btnSwitch;

      btnSwitch.setOnTouchListener(new View.OnTouchListener() {
            private Handler handler;
            @Override
            public boolean onTouch(View v,  MotionEvent event) {

                switch (event.getAction()){

                    case MotionEvent.ACTION_DOWN:
                        if (handler != null) return true;
                        handler = new Handler();
                        handler.postDelayed(thread, 14);
                        break;

                    case MotionEvent.ACTION_UP:
                       if (handler == null) return true;
                        handler.removeCallbacks(thread);
                        handler = null;
                        break;
            }
                return false;
            }
           Runnable thread= new Runnable() {
                @Override
                public void run() {
                    synchronized (this) {
                        try {
                            this.wait(7);
                            relativeLayout.setBackgroundColor(Color.BLACK);
                            turnonflash();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        try {
                            this.wait(7);
                            relativeLayout.setBackgroundColor(Color.WHITE);
                            turnofflash();

                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        handler.postDelayed(this, 14);
                    }}
           };
        });
    }

这是XML文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"

android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="@+id/backv">

<Button

    android:id="@+id/btnSwitch"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="100dip"

    android:text="switch"

    android:contentDescription="@null"
    />

1 个答案:

答案 0 :(得分:3)

您需要在UiThread上调用relativeLayout.setBackgroundColor(color);

 activity.runOnUiThread(new Runnable() {
      @Override
          public void run() {
              relativeLayout.setBackgroundColor(color);
     }
 });