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>