gpt4 book ai didi

android - 我在布局 Activity 中看不到我添加的图片

转载 作者:行者123 更新时间:2023-11-29 23:31:46 27 4
gpt4 key购买 nike

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

//java代码

打包 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>

最佳答案

在将 View 添加到Viewgroup 之前,您需要为ImageView 设置布局参数。

fly.setLayoutParams(params);

关于android - 我在布局 Activity 中看不到我添加的图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52570327/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com