RelativeLayout按钮创建
问题描述:
我试图创建按钮后,我按下按钮(这是一个预先制作的XML)。 事情是,我可以在LinearLayout中执行此操作,但是当我每次切换到RelativeLayout时,我的buttoncreator方法都会运行它,删除以前创建的按钮并创建一个新的按钮。RelativeLayout按钮创建
更具特色; 我buttoncreator方法
public void buttoncreator(String name,RelativeLayout.LayoutParams position,RelativeLayout layout){
positionrandomer(position);
final Button dummybutton = new Button(this);
dummybutton.setText(name);
//these are here for test,it works but still i have the same problem
position.addRule(RelativeLayout.BELOW,R.id.button1);
position.addRule(RelativeLayout.BELOW,R.id.button2);
dummybutton.setLayoutParams(position);
layout.addView(dummybutton);
return;
}
(位置randomer是它设置随机边距的方法)。
其中i调用创建器方法的地方
Button luckbutton = (Button) findViewById(R.id.button1);
luckbutton.setOnClickListener(new Button.OnClickListener(){
public void onClick(View arg0) {
name="Blue";
buttoncreator(name,position,layout);
name="Blu4e";
buttoncreator(name,position,layout);
}
});
所以,我打算在1个buttonclick创建2个按钮,但是它仅创建1.(实际上,它创建的第一个然后将其删除,并创建第二个 )。
Appereantly有一些我不明白RelativeLayouts, 我做错了什么?
THX提前
答
我可以建议你一种解决方法做你想要的东西。为什么不在xml文件中创建按钮并在onCreate()
至View.GONE
之间设置其可见性,并在按钮的onClick
中将其可见性设置为View.VISIBLE
。我认为这会做你想做的事情,我认为你不会遇到RelativeLayout
的问题。
感谢您的快速回答,但是由于代码的目的,这些按钮必须是非预定义的:/。 这在LinearLayout中非常有用,为什么它在Relativelayout中以这种方式运行? – Ozan
其实我很确定这是创建两个按钮。与RelativeLayout的事情是,你必须设置'layout_below/layout_above' params来对齐视图。如果你不这样做,他们将被卡在相同的位置,这就是为什么你认为它只创建第二个按钮。尝试将您的第一个文本设置为更长的文本,例如:'gdvasjdhaskdhajdhasj',您将看到它将保留在第二个按钮下。 –
完成,是的,我已经尝试过,你说得对。当我修复代码时,我会回来。非常感谢。 – Ozan