gpt4 book ai didi

android - 将按钮添加到 Android 中的 onDraw 调用

转载 作者:行者123 更新时间:2023-11-29 02:12:51 25 4
gpt4 key购买 nike

我正在使用下面的代码来绘制简单的 2D 图形(我在 DroidNova 上找到的——非常有用!),我想添加一个我在 XML 文件中定义的按钮(字符串名称和位置)。我看不到如何将按钮添加到屏幕(同时仍然显示来自 onDraw 调用的图形...

更新

我已经根据答案更新了下面的代码。我可以绘制矩形,但它不显示按钮。

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Drawresult();
}

protected void Drawresult() {
// Create a new linear layout to display out custom graphics and a button.
LinearLayout mainLayout = new LinearLayout(this);
mainLayout.setOrientation(LinearLayout.VERTICAL);

// Add our custom panel.
mainLayout.addView(new Panel(this));

// Create and setup our button.
Button myButton = new Button(this);
myButton.setText("Tap Me");
myButton.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
finish();
}
});

// Add our button to the layout.
mainLayout.addView(myButton);

// Set this activity's content to our layout.
setContentView(mainLayout);
}

class Panel extends View {
public Panel(Context context) {
super(context);
}

@Override
public void onDraw(Canvas canvas) {

Rect r = new Rect();
r.set(60, 60, 260, 77);

Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(3);

canvas.drawRect(r, paint);
}
}
}

最佳答案

将你的构造函数更改为这个(假设你有子类 Activity 。否则发布更多你的代码):

protected void Drawresult() {
// Create a new linear layout to display out custom graphics and a button
LinearLayout mainLayout = new LinearLayout(this);
mainLayout.setOrientation(LinearLayout.VERTICAL);

// Add our custom panel
mainLayout.addView(new Panel(this));

// Create and setup our button
Button myButton = new Button(this);
myButton.setText("Tap Me");
myButton.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// Put your click logic here
}
});

// Add our button to the layout
mainLayout.addView(myButton);

// Set this activity's content to our layout
setContentView(mainLayout);
}

关于android - 将按钮添加到 Android 中的 onDraw 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6239635/

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