如何在自定义创建的视图上显示简单的ImageButton?

问题描述

我一直在浏览整个互联网,但找不到该问题的任何答案。我想创建一个背景,一些图像按钮以及一堆运动图形(圆圈)。由于我不知道如何用移动图形覆盖xml布局,因此我选择自定义创建视图,绘制背景,imageButton和圆形(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); ???

解决方法

ImageButton需要一个父视图托管在其中。父视图可以是RelativeLayout,linearlayout或ConstraintLayout。

在您的情况下,实例relativeLayout始终为null,因为未指定在其中查找findById的视图父级。

您应该做出类似的事情:

RelativeLayout relativeLayout = view.findViewById(R.id.in_game_layout);

,

您还需要在父相对布局中添加布局参数,以正确显示“图像”按钮。

示例

 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);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...