java setImageResource在Android中不工作
我是java的初学者,我想随机化一些图片,我用这段代码来实现
int[] cards = {R.drawable.i1, R.drawable.i2, R.drawable.i3};
Random n = new Random();
Resources resources = getResources();
imgRandom.setImageResource(cards[n]);
而且它不起作用,因为setImageResource是红色的,Android Studio说:无法解析符号“setImageResource”。有人能帮我吗
所有java代码:
package eduard.alarmamotivationala;
import 安卓.content.res.Resources;
import 安卓.support.v7.app.AppCompatActivity;
import 安卓.os.Bundle;
import 安卓.widget.ImageView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
ImageView m_imgRandom;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public ImageView getM_imgRandom() { int[] cards = {R.drawable.i1, R.drawable.i2, R.drawable.i3};
Random n = new Random();
Resources resources = getResources();
m_imgRandom.setImageResource(cards [3]);
return m_imgRandom; }
}
所有XML代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
xmlns:tools="http://schemas.安卓.com/tools"
安卓:id="@+id/activity_main"
安卓:layout_width="match_parent"
安卓:layout_height="match_parent"
安卓:paddingBottom="@dimen/activity_vertical_margin"
安卓:paddingLeft="@dimen/activity_horizontal_margin"
安卓:paddingRight="@dimen/activity_horizontal_margin"
安卓:paddingTop="@dimen/activity_vertical_margin"
安卓:background="#000000"
tools:context="eduard.alarmamotivationala.MainActivity">
<Button
安卓:text="Porneste alarma"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:layout_alignParentTop="true"
安卓:layout_alignParentStart="true"
安卓:id="@+id/button" />
<Button
安卓:text="Opreste alarma"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:layout_alignParentTop="true"
安卓:layout_alignParentEnd="true"
安卓:id="@+id/button2" />
<TextView
安卓:text="Inca nu ai setat alarma"
安卓:textColor="#FFFFFF"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:layout_below="@+id/button"
安卓:layout_centerHorizontal="true"
安卓:layout_marginTop="11dp"
安卓:id="@+id/textView" />
<TimePicker
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:scaleX="0.7"
安卓:scaleY="0.7"
安卓:headerBackground="@安卓:color/transparent"
安卓:numbersSelectorColor="#027aed"
安卓:id="@+id/timePicker"
安卓:layout_marginTop="36dp"
安卓:layout_alignParentTop="true"
安卓:layout_alignParentStart="true" />
<ImageView
安卓:id="@+id/imgRandom"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:scaleType = "centerCrop" />
</RelativeLayout>
# 1 楼答案
生成从0到2的随机数
从数组中取出随机图像并设置为image
就这些
# 2 楼答案
也试试看
及
感受变化
在java文件中
没有测试。希望它能奏效