有人可以幫我一個代碼從我的圖紙文件夾中隨機顯示圖片嗎?我是新來的Java,所以我不知道如何去做。 任何幫助將不勝感激。 我的要求是: - 1.顯示隨機圖像(圖像應更改每個啓動) 2.that的所有如何在圖像視圖上顯示隨機圖像
import java.util.Random;
import java.util.Random;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class MainMenu extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
}
public void openNewActivity(View view) {
Intent intent = new Intent(this,MainActivity.class);
startActivity(intent);//button to open main
}
public void browser(View view) {
Intent intent = new Intent(this,Browser.class);
startActivity(intent);//button to open browser
}
final Random rnd = new Random();
{
setContentView(R.layout.activity_main_menu);
final ImageView img = (ImageView) findViewById(R.id.imgRandom);
// I have 3 images named img_0 to img_2, so...
final String str = "img_" + rnd.nextInt(9);
img.setImageDrawable
(
getResources().getDrawable(getResourceID(str, "drawable",
getApplicationContext()))
);
}
protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
final int ResourceID =
ctx.getResources().getIdentifier(resName, resType,
ctx.getApplicationInfo().packageName);
if (ResourceID == 0)
{
throw new IllegalArgumentException
(
"No resource string found with name " + resName
);
}
else
{
return ResourceID;
}
}
}
如果我有10張圖片,我應該將它設置爲9嗎? – Anonymous
是的,完美的。第一個是0,最後一個是9 –
你的代碼使我的應用程序的力量接近! – Anonymous