Android中的图像数组问题

时间:2015-07-24 11:05:31

标签: android

我对一系列图像存在这个小问题。我试图在android上做一个动态背景,它将每8秒更换一个新的图片。但是当它初始化时,它只会改变为第一张图片。下面是代码:

public class SecondActivity extends Activity {
int[] p = {R.drawable.android, R.drawable.android2, R.drawable.cool};
RelativeLayout screena;
private static final long GET_DATA_INTERVAL = 8000;
int index = 0;
Handler hand = new Handler();

@Override
protected void onCreate(Bundle saveInstanceState) {
    super.onCreate(saveInstanceState);
    setContentView(R.layout.other_activity);
    screena = (RelativeLayout) findViewById(R.id.screena);
    hand.postDelayed(run, GET_DATA_INTERVAL);

}

Runnable run = new Runnable() {
    @Override
    public void run() {
        screena.setBackgroundResource(p[index++]);
        if (index == p.length)
            hand.postDelayed(run, GET_DATA_INTERVAL);
            index = 0;

    }


};

}

4 个答案:

答案 0 :(得分:0)

Runnable run = new Runnable() {
    @Override
    public void run() {

        if (index == p.length)
            screena.setBackgroundResource(p[index]);
            hand.postDelayed(run, GET_DATA_INTERVAL);
            index = 0;

    }else{
      screena.setBackgroundResource(p[index]);
      index +=1; 
    }    
};

尝试上面的代码并检查

答案 1 :(得分:0)

private index = 0;

Runnable runnable = new Runnable() {

    @Override public void run() {
        screena.setBackgroundResource(p[++index % p.length]);
        hand.postDelayed(run, GET_DATA_INTERVAL);
    }
};

答案 2 :(得分:0)

您的Runnable仅在onCreate中调用一次。 index0开始,在run()中增加到值1index == p.lengthfalse1 != 3)。因此,永远不会在您的Runnable中调用hand.postDelayed(run, GET_DATA_INTERVAL);

Runnable run = new Runnable() {
@Override
public void run() {
    screena.setBackgroundResource(p[index++]);
    if (index == p.length) 
        index = 0;
    hand.postDelayed(run, GET_DATA_INTERVAL);
    }
};

或者你可以安排一个TimerTask,这将是一个更优雅的方式,imho。

Timer durationTimer = new Timer();
durationTimer.schedule(new TimerTask() {
    @Override
    public void run() {
        //code
    }
}, 0, GET_DATA_INTERVAL);

答案 3 :(得分:0)

您已从if条件范围中排除index = 0。因此即使在增量指数重置为零之后也是如此。尝试使用以下代码更新您的runnable

(def c1 (first (transpose test-mat)))
(def c2 (second (transpose test-mat)))

(def data-cov-mat [[(in-stats/covariance c1 c1) (in-stats/covariance c1 c2)] [(in-stats/covariance c2 c1) (in-stats/covariance c2 c2)]])