如何创建自定义按钮并以编程方式添加它?
我需要创建一个自定义按钮并以编程方式添加它。
我已经找到了几个例子,我尝试了它们,但是当我将它添加到我的活动中时,我什么都看不到。如何创建自定义按钮并以编程方式添加它?
这是我的代码:
活动:
Button btn = new Button(Einstellungen.this, null, R.attr.CustomButton);
在attrs.xml:
<resources>
<attr name="CustomButton" format="reference"/>
在styles.xml
<style name="AppTheme2" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="CustomButton">@style/someStyle</item>
</style>
<style name="someStyle">
<item name="android:layout_width">2px</item>
<item name="android:layout_height">fill_parent</item>
<item name="android:background">#000</item>
</style>
当我启动我的应用程序时,没有按钮。
我该如何解决这个问题?
您还应该定义按钮的布局参数(如果未在样式中定义)并将该按钮放入活动的布局中。假设你有LinearLayout
一个ID activity_layout
,那么它可能是这样的:
LinearLayout layout = (LinearLayout) findViewById(R.id.activity_layout);
Button button = new Button(Einstellungen.this, null, R.attr.CustomButton);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
button.setLayoutParams(layoutParams);
layout.addView(button);
注意你应该使用match_parent
代替fill_parent
是在你定义的样式。从docs:
fill_parent
意味着视图想要成为大如其父,减去亲的填充物,如果有的话。此值已从API Level 8及以后版本弃用,并由match_parent
取代。
我试了一下,但仍然没有任何东西可以在我的Activity中设置:( – peter12395
尝试使用'Button button = new Button(this);'来移除样式并定义按钮。另外 - 您应该在'OnCreate ()'你的活动的方法 – Micer
Ok so button button = new Button(this); is working。很明显,我在style.xml中有一个错误吗? – peter12395
您需要声明按钮后,要做到这一点:
layout = (LinearLayout) findViewById(R.id.linear_layout_of_your_xml);
btn.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
layout.addView(buyButton);
如果你的XML有不同的布局,你甚至可以初始化并分配代替的LinearLayout
我试过了,但仍然没有什么可以设置在我的活动:( – peter12395
请发布你的j ava文件以及xml,以便我们可以进一步了解它 –
不要接受帮助的答案你达到解决你的问题。 –