如何在运行应用程序时随机更改Imageview位置

时间:2014-10-20 13:33:50

标签: java android

我是Android的新手,我想制作一个Android应用程序,每次运行应用程序时都会有一个随机位置的图像视图。这样,每次运行应用程序时,图像显示在不同的水平位置。我在网上找了一些似乎对我有帮助的问题,但是当我尝试时我无法得到它。这是我的onCreate方法。一切似乎都符合我的要求,除了我评论出来的部分,这是我在网上找到的。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_main);

    sm=(SensorManager)getSystemService(SENSOR_SERVICE);
    rotation = sm.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
    sm.registerListener(this, rotation, SensorManager.SENSOR_DELAY_FASTEST);


    final Random rnd = new Random(System.currentTimeMillis());
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    width = size.y;
    height = size.x;

    //=============This code is from what I have found online====================
    final ImageView zombie1 = (ImageView) findViewById(R.id.zombie1);
    //zombie1.postInvalidate();
    MarginLayoutParams params = (MarginLayoutParams) zombie1.getLayoutParams();
    int rndInt = rnd.nextInt(width);
    params.setMargins(rndInt, 30, rndInt + zombie1.getWidth(), zombie1.getHeight());
    zombie1.setLayoutParams(params);
    //===========================================================================


    ScaleAnimation sa = new ScaleAnimation(1, 7, 1, 7, Animation.RELATIVE_TO_SELF, (float)0.5, Animation.RELATIVE_TO_SELF, (float)0.5);
    sa.setDuration(5000);
    sa.setAnimationListener(new AnimationListener() 
    {
        @Override
        public void onAnimationStart(Animation animation) {}

        @Override
        public void onAnimationRepeat(Animation animation) {}

        @Override
        public void onAnimationEnd(Animation animation) {
            zombie1.setVisibility(View.GONE);
        }
    });

   zombie1.startAnimation(sa);      
}

如果您需要在此处查看我的activity_main.xml,则

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/relative"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background"
    tools:context="${relativePackage}.${activityClass}" >

<ImageView
    android:id = "@+id/zombie1"
    android:layout_width = "75dp"
    android:layout_height = "75dp"
    android:layout_centerVertical = "true"
    android:layout_centerHorizontal = "true"
    android:layout_marginTop = "30dp"
    android:src = "@drawable/finalzombie1" 
    android:visibility = "visible"
    />

</RelativeLayout>

非常感谢任何帮助,并提前感谢您。

0 个答案:

没有答案