2017-08-06 48 views
-1

我需要創建一個自定義按鈕並以編程方式添加它。
我已經找到了幾個例子,我嘗試了它們,但是當我將它添加到我的活動中時,我什麼都看不到。如何創建自定義按鈕並以編程方式添加它?

這是我的代碼:

活動:

 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> 

當我啓動我的應用程序時,沒有按鈕。
我該如何解決這個問題?

+0

不要接受幫助的答案你達到解決你的問題。 –

回答

0

您還應該定義按鈕的佈局參數(如果未在樣式中定義)並將該按鈕放入活動的佈局中。假設你有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取代。

+0

我試了一下,但仍然沒有任何東西可以在我的Activity中設置:( – peter12395

+0

嘗試使用'Button button = new Button(this);'來移除樣式並定義按鈕。另外 - 您應該在'OnCreate ()'你的活動的方法 – Micer

+0

Ok so button button = new Button(this); is working。很明顯,我在style.xml中有一個錯誤嗎? – peter12395

0

您需要聲明按鈕後,要做到這一點:

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

+0

我試過了,但仍然沒有什麼可以設置在我的活動:( – peter12395

+0

請發佈你的j ava文件以及xml,以便我們可以進一步瞭解它 –

相關問題