我正在尝试做一个基本的应用程序,一旦你点击按钮,图像会随机变化为我加载的7个.png
图像之一。我尝试了几种不同的方法,但似乎无法让它发挥作用。这是我现在的代码:
.XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:background="@color/black" >
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="40dp"
android:background="@color/white"
android:text="@string/black"
android:onClick="onClick"/>
<ImageView
android:id="@+id/image1"
android:layout_width="320dp"
android:layout_height="250dp"
android:scaleType="fitXY"
android:contentDescription="@string/black" />
</RelativeLayout>
的.java
public class Black extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.black);
}
public void onClick() {
ImageView imageView = (ImageView)findViewById(R.id.image1);
int[] picture={R.drawable.black,R.drawable.blackairplane,R.drawable.blackbear,R.drawable.blackcircle,R.drawable.blackkite,R.drawable.blacksquare,R.drawable.blacktriangle};
Random r = new Random();
int n=r.nextInt(7);
imageView.setImageResource(picture[n]);
}
}
我在Eclipse中的错误消息说:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo
感谢您的帮助。
答案 0 :(得分:1)
试试吧,
public class Black extends Activity implements onClickListener{
ImageView imageView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.black);
imageView= (ImageView)findViewById(R.id.image1);
imageView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v == imgView){
int[] picture=
{
R.drawable.black,R.drawable.blackairplane,R.drawable.blackbear,R.drawable.blackcircle,R.drawabl e.blackkite,R.drawable.blacksquare,R.drawable.blacktriangle};
Random r = new Random();
int n=r.nextInt(7);
imageView.setImageResource(picture[n]);
}
}
}
答案 1 :(得分:0)
试试这个..
public class Black extends Activity {
ImageView imageView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.black);
imageView= (ImageView)findViewById(R.id.image1);
}
public void onClick() {
int[] picture=
{
R.drawable.black,R.drawable.blackairplane,R.drawable.blackbear,R.drawable.blackcircle,R.drawabl e.blackkite,R.drawable.blacksquare,R.drawable.blacktriangle};
Random r = new Random();
int n=r.nextInt(7);
imageView.setImageResource(picture[n]);
}
}
答案 2 :(得分:0)
试试这个
Random r=new Random();
r=(int)(Math.random()*7);
imageview.setImageResource(picture[r]);