1

Please I would need your help to figure out, why these code lines doesn't add an imageView on my playSpace (FrameLayout) when I run it. I just get the playSpace layout without images. What I'm doing wrong ?

//java code

package com.code123.en.createObj;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;

import java.util.Date;
import java.util.Random;

public class MainActivity extends Activity implements View.OnClickListener {

    private ViewGroup playSpace;
    private float scale;
    private Random randomNumber = new Random();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        playSpace= (ViewGroup)findViewById(R.id.playSpace);
    }

    private void showAFly()
    {
        scale = getResources().getDisplayMetrics().density;

        int width= playSpace.getWidth();
        int height = playSpace.getHeight();

        int fly_width = Math.round(scale*50);
        int fly_height = Math.round(scale*42);

        int left= randomNumber.nextInt(width- fly_width);
        int top= randomNumber.nextInt(height- fly_height);

        ImageView fly = new ImageView(this);
        fly.setImageResource(R.drawable.fly);
        fly.setOnClickListener(this);

        FrameLayout.LayoutParams params = new  FrameLayout.LayoutParams(fly_width,fly_height);
        params.leftMargin = left;
        params.topMargin = top;
        params.gravity = Gravity.TOP + Gravity.LEFT;
        playSpace.addView(fly,params);

    }

    @Override
    public void onClick(View v) {
        doSomething();
    }

//activity_main.xml code lines //It works fine manually

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/playSpace"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorPrimaryDark">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/fly" />
    </FrameLayout>
</LinearLayout>
Kel
  • 41
  • 6

2 Answers2

1

You need to set the layout parameters for the ImageView before adding the view to the Viewgroup.

fly.setLayoutParams(params);
Saikrishna Rajaraman
  • 3,205
  • 2
  • 16
  • 29
  • Thank you for your quick answer. I have now called my method into my onCreate-method but it still doesn't work. The app stops directly when I run it and I also set the layout parameters for the ImageView before adding the view to the Viewgroup just like you suggest it – Kel Sep 29 '18 at 17:02
  • Can u post the crash log? – Saikrishna Rajaraman Sep 29 '18 at 17:11
  • part 1: 09-29 19:20:21.055 23395-23395/? D/AndroidRuntime: Shutting down VM 09-29 19:20:21.055 23395-23395/? E/AndroidRuntime: FATAL EXCEPTION: main Process: com.code123.en.createObj; PID: 23395 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.code123.en.createObj;/com.code123.en.createObj;.MainActivity}: java.lang.IllegalArgumentException: n <= 0: -100 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3160) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3275) – Kel Sep 29 '18 at 17:35
  • part2: at android.app.ActivityThread.access$1000(ActivityThread.java:218) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1744) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:145) at android.app.ActivityThread.main(ActivityThread.java:7007) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) – Kel Sep 29 '18 at 17:37
  • part3:at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) Caused by: java.lang.IllegalArgumentException: n <= 0: -100 at java.util.Random.nextInt(Random.java:182) at com.code123.en.createObj.MainActivity.showAFly(MainActivity.java:39) at com.code123.en.createObj.MainActivity.onCreate(MainActivity.java:26) at android.app.Activity.performCreate(Activity.java:6609) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134) – Kel Sep 29 '18 at 17:38
  • part4: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3113) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3275)  at android.app.ActivityThread.access$1000(ActivityThread.java:218)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1744)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:145) – Kel Sep 29 '18 at 17:38
  • last part: at android.app.ActivityThread.main(ActivityThread.java:7007)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) – Kel Sep 29 '18 at 17:38
  • Sorry, I know that it is not good readable, but I can't post more than 585 characteres by commenting. Is there a better way to post my logcat ? – Kel Sep 29 '18 at 17:50
0

Where are you calling showAFly()?

Try calling it after

playSpace= (ViewGroup)findViewById(R.id.playSpace);
sbso
  • 403
  • 4
  • 8
  • Thank you for your quick answer. I have now called my showAFly()-method into my onCreate()-method but it still doesn't work. The app stops directly when I run it. – Kel Sep 29 '18 at 17:00
  • Can you please post the error logs - just for clarification, you placed showAFly() below the line mentioned, correct? – sbso Sep 29 '18 at 17:23
  • Yes I have done it. onCreate(...) ... playSpace = (ViewGroup)findViewById(R.id.playSpace); showAFly(); } and I have also set the LayoutParams ... playSpace.addView(fly,params); fly.setLayoutParams(params); – Kel Sep 29 '18 at 17:43
  • com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) Caused by: java.lang.IllegalArgumentException: n <= 0: -100 at java.util.Random.nextInt(Random.java:182) at com.code123.en.createObj.MainActivity.showAFly(MainActivity.java:39) at ie: randomNumber.nextInt(width- fly_width); This is what's causing the crash. If it's less than 0, nextInt will throw an exception. And to it, until *after* onResume() is called, your width will be 0. Hence the negative number. – sbso Sep 29 '18 at 18:31
  • Please could you tell me how I can fix it ? – Kel Sep 29 '18 at 18:39
  • https://stackoverflow.com/questions/3591784/views-getwidth-and-getheight-returns-0 - This will do a better job of explaining it than I ever could. – sbso Sep 29 '18 at 18:45
  • Thank you so much sbso, @Saikrishna R, I am going to read it. – Kel Sep 29 '18 at 18:53