我看不到我在布局活动中添加的图片?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (76)

我需要你的帮助来弄清楚,当我运行它时,为什么这些代码行不会在我的playSpace(FrameLayout)上添加一个imageView。我只是得到没有图像的playSpace布局。我做错了什么?

// java代码

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代码行//手动工作正常

<?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>
提问于
用户回答回答于

你在哪里调用showAFly()?

尝试之后调用它

playSpace= (ViewGroup)findViewById(R.id.playSpace);
用户回答回答于

您需要ImageView在将视图添加到之前设置布局参数Viewgroup

fly.setLayoutParams(params);

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励