[英]Setting style for dynamically added buttons
我正在嘗試將樣式設置為活動中動態添加的按鈕,但這些按鈕仍具有默認樣式。
這是我的活動
package com.sample.Learn_German_Quiz;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v4.view.ViewPropertyAnimatorCompat;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import static android.R.interpolator.linear;
public class LessonChooserActivity extends AppCompatActivity {
private GrammarBank grammarBank = new GrammarBank();
public String getSelectedLesson() {
return selectedLesson;
}
public void setSelectedLesson(String selectedLesson) {
this.selectedLesson = selectedLesson;
}
private String selectedLesson;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lesson_chooser);
grammarBank.initLessons(getApplicationContext());
setupButton();
}
private void setupButton() {
Context newContext = new ContextThemeWrapper(getBaseContext(), R.style.button_learn);
for (int i = 0; i <= 5; i++) {
LinearLayout layout = (LinearLayout) findViewById(R.id.linearTest);
layout.setOrientation(LinearLayout.VERTICAL);
Button btn = new Button(newContext);
//Button btn = new Button(this);
btn.setText(grammarBank.getLessonTitle(i));
layout.addView(btn);
}
}
}
並為活動的布局文件
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:padding="@dimen/fab_margin"
android:id="@+id/linearTest">
<Button
style="@style/button_learn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/ButtonTest"
android:ems="10"
android:text="Test"
android:textColor="#ffff"
android:padding="16dp"
android:onClick="onClick"
/>
</LinearLayout>
以及我想給按鈕的樣式 :
<style name="button_learn" parent="Theme.AppCompat.DayNight.NoActionBar">
<item name="android:background">@drawable/button_rounded</item>
<item name="android:layout_margin">20dp</item>
</style>
button_rounded.xml文件
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<corners android:radius="50dp"></corners>
<solid android:color="#4F535F"></solid>
</shape>
</item>
</selector>
他們顯示如下:
我想要他們像這樣:
試試這個
LinearLayout layout = (LinearLayout) findViewById(R.id.linearTest);
layout.setOrientation(LinearLayout.VERTICAL);
for (int i = 0; i <= 5; i++) {
Button btn= new Button(this, null,R.style.button_learn);
btn.setText(grammarBank.getLessonTitle(i));
layout.addView(btn);
}
您是否嘗試過使用另一個也帶有int defStyleAttr的Button構造函數? 如果將R.style.button_learn作為defStyleAttr傳遞,則它應該可以工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.