我怎样才能移动到android中的下一个数组

时间:2015-02-13 02:02:33

标签: android

我有一些像这样的数组:

static int [] lv1 = {R.drawable.A,R.drawable.C,R.drawable.D};
static int [] lv2 = {R.drawable.A1,R.drawable.C1,R.drawable.D1};
static int [] lv3 = {R.drawable.A2,R.drawable.C2,R.drawable.D2};
static int [] lv4 = {R.drawable.A3,R.drawable.C3,R.drawable.D3};

和一个按钮。 和ImageView在lv1中得到Resoure随机 我想当我点击按钮时,ImageView会在lv2中随机获得Resoure 并点击更多它将lv3 ...怎么能这样做?

2 个答案:

答案 0 :(得分:1)

代码如下:

public class MainActivity extends Activity {
    static int [] lv1 = {R.drawable.A,R.drawable.C,R.drawable.D};
    static int [] lv2 = {R.drawable.A1,R.drawable.C1,R.drawable.D1};
    static int [] lv3 = {R.drawable.A2,R.drawable.C2,R.drawable.D2};
    static int [] lv4 = {R.drawable.A3,R.drawable.C3,R.drawable.D3};

    private int clickTimes = 0;
    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_layout);
        imageView = (ImageView)findViewById(R.id.your_image_view_id);
        findViewById(R.id.your_button_id).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                clickTimes++;
                clickTimes %= 4;
                setRandomImage();
            }
        });
        setRandomImage();
    }

    private void setRandomImage() {
        int index = getRandomIndex();
        int drawableId = -1;
        switch (clickTimes) {
        case 0:
            drawableId = lv1[index];
            break;
        case 1:
            drawableId = lv2[index];
            break;
        case 2:
            drawableId = lv3[index];
            break;
        case 3:
            drawableId = lv4[index];
            break;
        }
        if(drawableId > 0){
            imageView.setImageResource(drawableId);
        }
    }

    /**
     * Get a random int [0, 2]
     * @return
     */
    private int getRandomIndex() {
        Random randow = new Random();
        return Math.abs(randow.nextInt()) % 3;
    }
}

答案 1 :(得分:0)

使用二维数组,第一个索引定义lv,第二个索引定义lv内的资源。

Static int lvs[][] ={
    {R.drawable.A,R.drawable.C,R.drawable.D},
    {R.drawable.A1,R.drawable.C1,R.drawable.D1},
    {R.drawable.A2,R.drawable.C2,R.drawable.D2},
    {R.drawable.A3,R.drawable.C3,R.drawable.D3}
};

每按一次按钮增加索引1,将索引2设置为0到2之间的随机值。