Android从可绘制XML创建按钮

时间:2017-03-02 16:23:22

标签: android xml button

我想以编程方式使用格式化按钮(来自XML)。

这是我的ButtonShape.xml,它位于drawable文件夹中。

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_focused="true"
        android:state_pressed="true"
        android:drawable="@drawable/button" />

    <item
        android:state_focused="false"
        android:state_pressed="true"
        android:drawable="@drawable/button" />

    <item android:drawable="@drawable/buttonpressed" />
</selector>

这是我的代码

Button newBut;
newBut = new Button(this);  

                newBut.setText("("+breakJobup[0]+") "+breakJobup[1]+" "+breakJobup[2]+" - "+breakJobup[3]+"99999999999999999992");
                newBut.setTextColor(Color.parseColor("#404040"));

                newBut.setTag(breakJobup[0]); //hide job id within the button.
                newBut.setEllipsize(TruncateAt.MARQUEE);
                newBut.setSingleLine();
                newBut.setMarqueeRepeatLimit(50);
                newBut.setSelected(true);

关于如何做到这一点的任何想法。

1 个答案:

答案 0 :(得分:0)

试试这段代码。

Drawable drawable = ContextCompat.getDrawable(newBut.getContext(), R.drawable.ButtonShape);
ViewCompat.setBackground(newBut, drawable);