微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在自定义创建的视图上显示简单的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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。