Reputation: 481
I have been using a few images for buttons (the XML below) - but a part of my project I have needed to create a button programmatically, which is not formatted like this others (which I would like it to be).
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>
My code that creates a button
Button newBut;
newBut = new Button(this);
newBut.setText("SOME TEXT");
newBut.setTextColor(Color.parseColor("#404040"));
newBut.setEllipsize(TruncateAt.MARQUEE);
newBut.setSingleLine();
newBut.setMarqueeRepeatLimit(50);
newBut.setSelected(true);
This is the code from a Activity with the formatted buttons
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.tabdemo.Tab1Activity"
android:background="#00547d"
>
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="vertical"
android:weightSum="1">
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="60dp"
android:text="Login"
android:textColor="#FFFFFF"
android:textSize="20dp"
android:background="@drawable/buttonshape"
android:shadowColor="#A8A8A8"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="5"
/>
<Button
android:id="@+id/button2"
android:enabled="false"
android:text="Logout"
android:textColor="#FFFFFF"
android:textSize="20dp"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="@drawable/buttonshape"
android:shadowColor="#A8A8A8"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="5"
/>
</LinearLayout>
</RelativeLayout>
Is there any way of using android:background="@drawable/buttonshape" programatically
Upvotes: 0
Views: 138
Reputation: 23881
try this:
button.setBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.buttonshape));
Upvotes: 1