set background color generically to elements - java

I have two Text views in my xml file.
<TextView
android:layout_width="#dimen/margin_0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="Trainings"
android:gravity="center"
android:background="#drawable/rounded_corner"
android:onClick="changeColor"
/>
<TextView
android:id="#+id/learning_programs"
android:layout_width="#dimen/margin_0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="Learning Programs"
android:background="#drawable/rounded_corner"
android:gravity="center"
android:onClick="changeColor"/>
By default the background color of both of these is grey as set by the drawable rounded_corner.xml file, and when any of these is clicked I want it to change to white.
In my Java file I have
public void changeColor(){
this.setBackground(getResources().getColor((R.color.dark_grey_color)));
}
I know that I can use setOnclickListener and run a switch-case between the ids of the buttons based on View.
But the requirement is to it this way.
So, how can I implement it this way?
Thanks.

Just change your function. Replace Color.BLUE with whatever color or drawable you want. Because when you set onClick from xml it passes its view to the activity which you can get using view,getId to identify which click performed. In your case you are passing textview so cast that to textview.
public void changeColor(View view) {
//((TextView) view).setBackgroundColor(Color.BLUE);
GradientDrawable bgShape = (GradientDrawable)((TextView) view).getBackground();
bgShape.setColor(Color.BLUE);
}

If you want the view to maintain its background once it is clicked then you can keep the TextView and simply change the background color on the changeColor method. If you want it to toggle the background color according to click then it's a checkbox behaviour. If you want this last behaviour then implement it as follows:
Checkbox:
<CheckBox
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="Trainings"
android:button="#null"
android:gravity="center"
android:background="#drawable/view_state"/>
<CheckBox
android:id="#+id/learning_programs"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="Learning Programs"
android:button="#null"
android:background="#drawable/view_state"
android:gravity="center"/>
Then add a drawable to define those states (drawable/view_state):
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true">
<shape android:shape="rectangle">
<solid android:color="#000" /> <!-- clicked color -->
</shape>
</item>
<item android:state_checked="false">
<shape android:shape="rectangle">
<solid android:color="#FFF" /> <!-- default color -->
</shape>
</item>
</selector>

Just add the below code snipet onclick of your textview
your_textview.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.white));

Related

Button color from drawable doesn't change

I have some issue with styling of my buttons. I use drawable to change shape and style my app buttons. When I add background in activity xml my buttons change shape but doesn't change background color but when I add background programmatically with "setBackgroundResource" method everything is ok.
There is my piece of code:
activity xml:
`<Button
android:id="#+id/button_traditional"
android:background="#drawable/button_default_main_app"
android:textColor="#color/mustard"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="75dp"
android:layout_marginEnd="32dp"
android:onClick="newGame"
android:text="#string/standard_game"
app:layout_constraintEnd_toStartOf="#+id/button_extended"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/text_gameChose" />
`
res/drawable:
<solid
android:color="#color/black"
/>
<corners
android:topLeftRadius="10dp"
android:topRightRadius="100dp"
android:bottomLeftRadius="100dp"
android:bottomRightRadius="10dp"
/>
Thanks in advance for your help.
Edit:
Whole drawable code:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid
android:color="#color/black"
/>
<corners
android:topLeftRadius="10dp"
android:topRightRadius="100dp"
android:bottomLeftRadius="100dp"
android:bottomRightRadius="10dp"
/>
</shape>
By default the button tint is the primary color. You need to set it to null for the drawable to take effect by setting.
app:backgroundTint="#null"
So your whole button would look like this:
<Button
android:id="#+id/button_traditional"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="75dp"
android:layout_marginEnd="32dp"
android:background="#drawable/button_default_main_app"
android:onClick="newGame"
android:text="Standard game"
android:textColor="#a00"
app:backgroundTint="#null" />
The result:

I need a design like that but I'm facing two problems

I need a template for my list view with the following item design
I've tried some code I found but I did not get the result I need.
<item
android:bottom="-32dp"
android:left="-3dp"
android:right="-2dp"
android:top="2dp">
<shape android:shape="rectangle" >
<corners android:radius="32dp"/>
<stroke
android:width="2dp"
android:color="#fff" />
<solid android:color="#android:color/transparent" />
<padding
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="0dp" />
</shape>
</item>
this is my linearlayout background.
Though we can use png for this or or image to get this .
but if you really want to do this this drawable then here the code .
I tried and result was pretty same .
I have created a drawable using two layer list , that contains two different rectangle .
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:bottom="10dip">
<shape
android:shape="rectangle"
android:useLevel="false">
<corners android:radius="12dp" />
<stroke
android:width="2dp"
android:color="#ffffff" />
<size
android:width="60dp"
android:height="60dp" />
<solid android:color="#android:color/transparent" />
</shape>
</item>
<item android:top="20dip">
<shape android:shape="rectangle">
<solid android:color="#800080" />
</shape>
</item>
You can use this in your view as background . I have used this in mine , so i am adding code of my item view .
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#800080">
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/text_18"
android:background="#drawable/sample">
<TextView
android:id="#+id/crime_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:text="Crime Title"
android:textColor="#color/colorAccent"
android:textSize="18sp"
app:layout_constraintEnd_toStartOf="#+id/crime_solved"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/crime_date"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:paddingBottom="8dp"
android:text="Crime Date"
android:textColor="#color/colorAccent"
app:layout_constraintEnd_toEndOf="#id/crime_title"
app:layout_constraintStart_toStartOf="#id/crime_title"
app:layout_constraintTop_toBottomOf="#+id/crime_title" />
<ImageView
android:id="#+id/crime_solved"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
app:layout_constraintBottom_toBottomOf="#+id/crime_date"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/crime_title"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_solved" />
</android.support.constraint.ConstraintLayout>
Hope this will be helpful .
Instead of using xml drawable, you can Create a 9-patch image for that shape, that might help.
Create that shape in your favourite image-editor and copy that to drawable directory of your project.
In Android Studio, right-click the PNG image you'd like to create a NinePatch image from, then click Create 9-patch file.
Type a file name for your NinePatch image, and click OK. Your image will be created with the .9.png file extension.
Double-click your new NinePatch file to open it in Android Studio. Your workspace will now open.
The left pane is your drawing area, in which you can edit the lines for the stretchable patches and content area. The right pane is the preview area, where you can preview your graphic when stretched.
Click within the 1-pixel perimeter to draw the lines that define the stretchable patches and (optional) content area. Right-click (or hold Shift and click, on Mac) to erase previously drawn lines.
When done, click File > Save to save your changes.

How to create custom button view that can accept corner radius and color dynamically and change accordingly

How to create custom button view that can accept corner radius and background color dynamically rather than making shape file for every button.
I know that i can extend to the Button class and also create attribute set to accept the values, but just dont know how to change corner radius of the button.
You can use MaterialButton
<com.google.android.material.button.MaterialButton
android:id="#+id/btnWithdraw"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="center"
android:padding="15dp"
android:text="#string/withdraw"
android:textAllCaps="false"
android:textColor="#android:color/white"
android:textSize="15sp"
android:textStyle="bold"
app:backgroundTint="#color/colorLightRed"
app:cornerRadius="10dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/edtAgentPin" />
To change background color use this
btnWithdraw.backgroundTintList = ColorStateList.valueOf(Color.BLUE)
To change cornerRadius use this
rootView.btnWithdraw.cornerRadius = 20
NOTE : make sure you have added below dependencies in your Build.Gradle file
implementation 'com.google.android.material:material:1.0.0'
1.Create a xml file in your drawable folder like mybutton.xml and paste the following markup:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" >
<shape android:shape="rectangle" >
<corners android:radius="3dip" />
<stroke android:width="1dip" android:color="#5e7974" />
<gradient android:angle="-90" android:startColor="#345953" android:endColor="#689a92" />
</shape>
</item>
<item android:state_focused="true">
<shape android:shape="rectangle" >
<corners android:radius="3dip" />
<stroke android:width="1dip" android:color="#5e7974" />
<solid android:color="#58857e"/>
</shape>
</item>
<item >
<shape android:shape="rectangle" >
<corners android:radius="3dip" />
<stroke android:width="1dip" android:color="#5e7974" />
<gradient android:angle="-90" android:startColor="#8dbab3" android:endColor="#58857e" />
</shape>
</item>
</selector>
here button code below
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textColor="#ffffff"
android:background="#drawable/mybutton"
android:text="Buttons" />
Please try this
val shape = GradientDrawable()
shape.cornerRadius = 18f
// add some color
// You can add your random color generator here
// and set color
shape.setColor(Color.RED);
// now find your view and add background to it
view.btn.background = shape
You can use the CardView to create custom button with corner radius and color dynamically.
XML Code:
<android.support.v7.widget.CardView
android:id="#+id/main_card"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:cardCornerRadius="20dp"
app:cardElevation="5dp"
app:cardUseCompatPadding="true"
app:cardBackgroundColor="#color/orange"
android:layout_centerInParent="true">
<LinearLayout
android:layout_width="100dp"
android:layout_height="50dp"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text"
android:textColor="#000"/>
</LinearLayout>
</android.support.v7.widget.CardView>
Change Color dynamically :
CardView main_card=findViewById(R.id.main_card);
main_card.setCardBackgroundColor(getResources().getColor(R.color.colorAccent));
I hope it works for you.
Button btn = new Button(this);
btn.setText("Submit");
final int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
btn.setBackgroundDrawable(ContextCompat.getDrawable(context,R.drawable.ready) );
} else {
btn.setBackground(ContextCompat.getDrawable(context, R.drawable.ready));
}
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams buttonlayout = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
linearLayout.addView(btn, buttonlayout);
add drwaable R.drawable.library_cirecle
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="#+id/outerRectangle">
<shape android:shape="oval" >
<solid android:color="#FCD366" />
<stroke
android:width="1dp"
android:color="#android:color/darker_gray" />
</shape>
</item>
Change color in code
Drawable tempDrawable = getResources().getDrawable(R.drawable.library_cirecle);
LayerDrawable bubble = (LayerDrawable) tempDrawable; (cast to root element in xml)
GradientDrawable solidColor = (GradientDrawable) bubble.findDrawableByLayerId(R.id.outerRectangle);
solidColor.setColor(colorToPaint);
imageView.setImageDrawable(tempDrawable);

Change <Button> color onClick?

<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Add"
android:id="#+id/btnAdd"
android:background="#ff6347"
android:textColor="#f8f8f8"
android:layout_marginTop="36dp"
android:clickable="true"
android:layout_below="#+id/txtAddress"
android:layout_centerHorizontal="true"
android:focusable="true" />
This is my XML Button element and it's fine and dandy...but I want it to be known when it's pressed. How can I go about making it have different styling when pressed vs when not pressed?
You can use a selector and use a drawables for different states.
http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList
You can also use OnTouchListener and on ACTION_DOWN and ACTION_UP set the color to the buttons
You want to use a selector as the background for the button. Basically you can define the the different shape you want for each state of the button and the shape consists of color, corner radius, and other cool things.
XML file saved at res/drawable/button.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"> <!-- pressed -->
<shape android:shape="rectangle" >
<solid android:color="#color/blue" />
</shape>
</item>
<item> <!-- default -->
<shape android:shape="rectangle" >
<solid android:color="#color/red" />
</shape>
</item>
</selector>
This layout XML applies the state list drawable to a Button:
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:background="#drawable/button" />

Inflating drawable from XML

I'm trying to do a bottom-level menu like this:
I've defined the layout this way:
<LinearLayout
android:id="#+id/bottomBar"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_marginTop="4dp"
android:orientation="horizontal"
android:layout_alignParentBottom="true" >
<HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fillViewport="true"
android:scrollbars="none">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<!-- First item of the menu -->
<ImageButton
android:id="#+id/BConex1"
android:contentDescription="#string/desc_gen_image"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.2"
android:layout_gravity="left"
android:background="#drawable/menu_bottom"
android:layout_marginLeft="4dp" />
<!-- Second item of the menu -->
<ImageButton
android:id="#+id/BConex2"
android:contentDescription="#string/desc_gen_image"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.2"
android:layout_gravity="left"
android:background="#drawable/menu_bottom"
android:layout_marginLeft="4dp" />
<!-- ... Some additional items in the menu -->
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
The #drawable/menu_bottom is a layer-list, defined this way:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="1px"
android:color="#55ffffff" />
<padding
android:left="16px"
android:top="6px"
android:right="16px"
android:bottom="6px" />
<solid
android:color="#cc000000" />
<gradient
android:startColor="#222222"
android:centerColor="#111111"
android:endColor="#000000"
android:angle="-90" />
<corners
android:bottomRightRadius="10dp"
android:bottomLeftRadius="10dp"
android:topLeftRadius="10dp"
android:topRightRadius="10dp" />
</shape>
</item>
<item>
<bitmap
android:src="#+drawable/bitmap_to_change"
android:tileMode="disabled"
android:width="30dp"
android:height="15dp"
android:gravity="center" />
</item>
</layer-list>
Now the thing is: I want to use exactly the same background for each button in the menu, in exception of the src field of the bitmap. I've tried to use LayoutInflater on one of the buttons and tried to change it programatically, like this:
View first = LayoutInflater.from(this).inflate(R.drawable.menu_bottom, null);
first.findViewById(R.drawable.bitmap_to_change).setBackground(this.getResources().getDrawable(R.drawable.another_resource));
But this returns an exception:
12-11 11:35:53.556: E/AndroidRuntime(897): java.lang.RuntimeException:
Unable to start activity ComponentInfo{XXX.MainActivity}:
android.view.InflateException: Binary XML file line #2: Error
inflating class layer-list
So I assume that's not the correct way. Is there a way to accomplish this instead of defining one XML file per menu item?
Thanks!
----------- EDIT -----------
I've found a "dirty" workaround to achieve my goal: getting the background of one of the buttons as a LayerDrawable and substituting the Bitmap with the correct. This is not the way I want to do it (as I want it entirely programatically) nor it's the original question, so I'm not going to answer myself letting the question opened in the hope someone can help, but here's what I'm doing now:
I assigned an id to the corresponding "item" in the XML file:
<item android:id="#+id:bitmap_layer">
And programatically:
ImageButton firstButton = (ImageButton) findViewById(R.id.BConex1);
LayerDrawable bg = (LayerDrawable) firstButton.getBackground();
bg.setDrawableByLayerId(R.id.bitmap_layer, getResources().getDrawable(R.drawable.the_new_drawable));
You donĀ“t need to use the iflater, getting the Drawable resurse is enough:
android.graphics.drawable.Drawable shape = getResources().getDrawable(R.drawable.item_panel_borde);
with your workaroud you can get trouble if you use this drawable resource in other views, you can create your LayerList programatically using the android.graphics.drawable.LayerDrawable(Drawable[]) constructor.

Categories