2017-03-02 6 views
0

私は、(XMLからの)書式設定されたボタンをプログラム的に使いたいと思っています。Drawable XMLからボタンを作成する

これは、DrawableフォルダにあるButtonShape.xmlです。

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

これを行う方法上の任意のアイデアのためにこの私のコード。

答えて

0

このコードを試してください。

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

ありがとうございます。 ContextCompat。 と ViewCompat シンボルを解決できません –

+0

com.android.support:support-v4:25.2.0 '"を依存関係に' compile'を追加します。 – betorcs

+0

build.gradle内にありますか? –

関連する問題