首页 > 解决方案 > 如何在自定义创建的视图上显示一个简单的 ImageButton?

问题描述

我一直在浏览整个互联网,但我找不到这个问题的任何答案。我想创建一个背景,一些图像按钮,以及一堆移动图形(圆圈)。由于我不知道如何用移动图形覆盖 xml 布局,我选择自定义创建视图、绘制背景、imageButtons 和圆圈(2D 图形)。

public class GameView extends View implements UtilConstants  

由于我扩展了 View 类,我不得不在我的构造函数中调用超类构造函数

GameView(Context context) {
    super(context);
    this.context = context;
    this.paint = new Paint();
}

并实现 onDraw 方法,其作用类似于 java paintComponent

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas); // necessary for some reason

    setGridBackground(); // sets the background

    paint.setColor(Color.parseColor("#FF0000"));
    canvas.drawCircle(this.x += 10, 300, 20, paint); //moves my graphics (ball) within the screen

    drawScoreInLeftUpperCorner(canvas, 20); // paints a string text on the screen

    setAbilitiesImages(); // places some imageButtons

    try {
        Thread.sleep(THREAD_REFRESH_RATE_MS);
    } catch (InterruptedException ex) {
        System.out.println(ex);
    }

    invalidate();
}

现在,解决我的问题:我不知道如何设置那些 ImageButtons !!!我在尝试

 private void setAbilititesImages() {
     ImageButton imageButton = new ImageButton(this.context); // is this ok to put the argument this.context??

    imageButton.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    imageButton.setImageResource(R.drawable.monster); // set my resource

    RelativeLayout relativeLayout = findViewById(R.id.in_game_layout); // what is the purpose of this???

    if (relativeLayout != null) { // it never enters this if, relativeLayout is always null
        relativeLayout.addView(imageButton);
    }
 }

Aaaa 和图像按钮永远不会出现...为什么需要使用相对/线性布局?我创建的那个 R.id.in_game_layout 只是一个空的 RelativeLayout xml。我不能只使用类似的东西

imageButton.setImageResource(R.drawable.monster); // set my resource
imageButton.setBounds(.....);
(View)this.add(imageButton); ???

标签: javaandroidimagebutton

解决方案


您还需要将布局参数添加到您的父相对布局,以适当地显示您的图像按钮。

例子

 RelativeLayout relativeLayout = findViewById(R.id.relativeLayout);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    ImageButton imageButton = new ImageButton(this);
    imageButton.setImageDrawable(getResources().getDrawable(R.drawable.ic_launcher_background,null));
    relativeLayout.addView(imageButton,params);

推荐阅读