2017-03-02 2 views
0

Ich möchte meine formatierte Schaltfläche (From XML) programmatisch verwenden.Android Create Button von Drawable XML

Dies ist meine ButtonShape.xml, die im Drawable-Ordner lebt.

<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> 

Das ist mein Code für

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); 

eine Ahnung, wie dies zu tun.

Antwort

0

Versuchen Sie diesen Code.

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

Danke dafür. ContextCompat. und ViewCompat Symbol kann nicht aufgelöst werden –

+0

Fügt 'compile 'com.android.support:support-v4:25.2.0'" 'zu Ihren Abhängigkeiten hinzu. – betorcs

+0

Innerhalb build.gradle? –