我尝试将样式设置为活动中动态添加的按钮,但按钮仍然使用默认的stlye。
这是我的活动
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>
它们显示如下:
我希望他们这样:
答案 0 :(得分:1)
试试这个
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);
}
答案 1 :(得分:1)
您是否尝试使用另一个同时采用int defStyleAttr的Button constructor?如果你将R.style.button_learn作为defStyleAttr传递,那么它应该可以工作。