[英]Adding buttons dynamically to linearView
I'm trying to write an application that's adding buttons dynamically. 我正在尝试编写一个动态添加按钮的应用程序。 The application receives an image from the server and adding a button (no functionality for now).
该应用程序从服务器接收图像并添加一个按钮(目前没有任何功能)。
The main activity is holding linear layout which will contain the buttons and a surface view that would receive the images and would create the buttons in the main activity. 主要活动保持线性布局,其中将包含按钮和一个表面视图,该表面视图将接收图像并在主要活动中创建按钮。
The problem is that after the first image has been received the application crash while trying to add a new button to the view. 问题是,在收到第一个图像后,应用程序崩溃,同时尝试向视图添加新按钮。
This is the surface view code: 这是表面视图代码:
public void run() {
while ( isRunning){
if ( !ourHolder.getSurface().isValid()){
continue;
}
Canvas canvas = ourHolder.lockCanvas(); // Semafor for the canvas
canvas.drawRGB(20,20,80);
if (getNumOfBoards() > 0){
canvas.drawBitmap(getCurrentBoard(), 0, 0, null);
}
ourHolder.unlockCanvasAndPost(canvas);
}
}
This is the Main Activity add button code 这是主要活动添加按钮的代码
public void addButtons(int numOfButton) {
// create patameter
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
// create new button
Button newbutton = new Button(this);
// set background color
newbutton.setBackgroundColor(Color.BLUE);
// set width and height
newbutton.setWidth(30);
newbutton.setHeight(20);
// set position
newbutton.setY((float)numOfButton*20);
newbutton.setX(0);
// set text
newbutton.setText("new button");
// add button to the layout
buttons.addView(newbutton,p);// **the application crash here**
}
Due to the way android handles the Activities, the constructor onCreate
is not guaranteed to have been called every time the addButtons
method is executed (See the Activity Lifecycle Section
at developer.android.com) 由于android处理活动的方式,不能保证每次执行
addButtons
方法时都会调用构造函数onCreate
(请参阅developer.android.com的“ Activity Lifecycle Section
)
You had better find the buttons
LinearLayout 您最好找到
buttons
LinearLayout
LinearLayout buttons = (LinearLayout) findViewById(R.id.LayoutButtons);
in addButtons
and add the new button. 在
addButtons
并添加新按钮。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.