![](/img/trans.png)
[英]Failed to find style 'My_Button' in current theme when I set style attribute programmatically
[英]Set button style programmatically
所以我是以編程方式創建新按鈕並將它們添加到LinearLayout,但是我想用預定義的樣式初始化這些按鈕。 我花了一些時間尋找解決方案並嘗試答案,但我似乎仍然無法讓它發揮作用。
當我向布局添加一個新按鈕時,它應該看起來像這張圖片中的按鈕(靠近頂部)。
我嘗試在res / values /中創建一個xml文件,並使用new Button(context, null, R.style.ChoiceButton)
初始化一個按鈕,但是它不起作用導致這種情況發生 。
我也嘗試了為按鈕創建一個新的布局xml並使用(Button)getLayoutInflater().inflate(R.layout.choice_buttton_layout, null)
,但這也沒有用, 導致這個(兩個按鈕)顯示缺乏保證金) 。
RES /值/ choice_button.xml
<resources>
<style name="ChoiceButton">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_gravity">center_horizontal</item>
<item name="android:layout_marginBottom">7dp</item>
<item name="android:minWidth">250dp</item>
<item name="android:background">#ff27ae60</item>
<item name="android:textColor">#ffffffff</item>
<item name="android:enabled">true</item>
</style>
</resources>
來自Main.java的片段
public void btnAdd_click(View view) {
Button newBtn = new Button(getApplicationContext(), null, R.style.ChoiceButton);
newBtn.setText("new button");
newBtn.setId(Util.generateViewId());
LinearLayout layout = (LinearLayout)findViewById(R.id.layoutTop);
layout.addView(newBtn);
}
activity_main.xml中
有什么我想念的嗎? 這甚至可能嗎?
好的@ kin3tik,我找到了一個用自定義按鈕制作的舊應用程序..看看它的樣子:
我的xml是一個按鈕:
<Button
android:id="@+id/num1"
android:layout_width="110dp"
android:layout_height="100dp"
android:layout_marginRight="5dp"
android:layout_weight="1"
android:text="@string/num1"
android:textSize="20sp" />
我在drawable文件夾custombutton.xml中創建了文件.xml:
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/bleuperso"/> // you can put #XXXXXX for the color you want
<corners android:radius="4dp"/>
我只是把風格放在java中:
Bfrancois.setBackgroundResource(R.drawable.custombutton);
有了這個,你應該能夠找到自己;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.