java - 如何在自定义创建的视图上显示一个简单的 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); ???
解决方案
您还需要将布局参数添加到您的父相对布局,以适当地显示您的图像按钮。
例子
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);
推荐阅读
- algorithm - 矩形的最大子集,使得没有矩形适合任何其他矩形
- amazon-s3 - Cloudfront createInvalidation 不会被 Lambda 随机触发
- javascript - 如何撤消/重做 javascript 正则表达式 .replace 脚本?
- java - How to add data to spinner dynamically? Keep the spinner data when every time the activity creates. Android
- postgresql - PostgreSQL SELECT query using same structure as a DELETE query
- javascript - Pass Javascript variable to laravel include?
- python - Create a for loop that generates individual emails with html dataframe for each unique recipient
- python - unable to find that exists and not an iframe using selenium
- c - 在 MacOS 上使用 stb_image 库时无法使用 cmake 构建 C 项目
- android - 如何在方法/函数中获取意图并使用其文件