Android:从数组中挑选随机字符串并在setImageResource命令中使用它

时间:2015-09-11 18:09:01

标签: android android-studio

嗨:我是java的新手,我需要通过按下按钮将随机图像设置为图像视图:我已经尝试了很多不同的方式(示例中的一个不起作用)我不知道真的知道该做什么 JAVA代码:

package comad.exampleaaaa.vittoriodaadntico.dadi;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.lang.reflect.Array;
import java.util.Random;

public class DADI extends AppCompatActivity {
private ImageView dado;
public Button azione;
public String[] immagini=    {"dice2","dice3","dice4","dice5","dice6","dice7"};

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dadi);
    dado=(ImageView)findViewById(R.id.dice);
    azione=(Button)findViewById(R.id.roll);

        azione.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                int random; // or create a static random field...
                random = new Random().nextInt(new Random(immagini.length));

                dado.setImageResource(Integer.parseInt(immagini[random]));

        }});
}


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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

XML代码:     

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".DADI"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

如果您需要更多解释,请发表评论和谢谢

0 个答案:

没有答案