I want to create an Activity with a SearchView that is not in the ActionBar (in fact, I'm using the NoActionBar theme). Now I want this SearchView to have rounded corners (not the EditText inside the actual SearchView, but the SearchView itself),
like this: Mockup
All I can manage is this: actual SearchView.
Can somebody hint me to what I have to change?
XML of the Activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipChildren="false">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="150dp"
android:background="#color/theBlue">
<SearchView
android:id="#+id/search_view"
android:layout_width="1000dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:background="#drawable/bg_white_rounded"
android:clickable="true"/>
</RelativeLayout>
Code of drawable/bg_white_rounded.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#ffffff"/>
<corners android:radius="10dp"/>
<padding android:left="0dp"
android:bottom="0dp"
android:right="0dp"
android:top="0dp"/>
</shape>
Code of the Activity:
public class MainActivity extends AppCompatActivity {
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get search view and modify it to our needs
searchView = (SearchView) findViewById(R.id.search_view);
searchView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchView.onActionViewExpanded();
}
});
//int searchPlateId = searchView.getContext().getResources().getIdentifier("android:id/search_plate", null, null);
//int searchPlateId = searchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
int searchPlateId = searchView.getContext().getResources().getIdentifier("android:id/search_badge", null, null);
View searchPlate = searchView.findViewById(searchPlateId);
//View searchPlate = searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
searchPlate.setBackgroundResource(R.drawable.bg_white_rounded);
}
}
The commented lines are things I've already tried but didn't work.
Thanks!
Just give padding = corner radius,because corners are hidden by Actual SearchView Background will set it to back ,so padding makes the trick
drawable/bg_white_rounded.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#ffffff"/>
<corners android:radius="8dp"/>
<padding android:left="8dp"
android:bottom="8dp"
android:right="8dp"
android:top="8dp"/>
</shape>
While rajan ks (Thanks!) answer works, it doesn't resemble the design mockup a 100% (the padding naturally increases the SearchView's size while not increasing the contained EditText's size).
The solution I found is this:
In the MainActivity.java, change search_edit_frame, search_plate and search_bar:
int searchFrameId = searchView.getContext().getResources().getIdentifier("android:id/search_edit_frame", null, null);
View searchFrame = searchView.findViewById(searchFrameId);
searchFrame.setBackgroundResource(R.drawable.bg_white_rounded);
int searchPlateId = searchView.getContext().getResources().getIdentifier("android:id/search_plate", null, null);
View searchPlate = findViewById(searchPlateId);
searchPlate.setBackgroundResource(R.drawable.bg_white_rounded);
int searchBarId = searchView.getContext().getResources().getIdentifier("android:id/search_bar", null, null);
View searchBar = findViewById(searchBarId);
searchBar.setBackgroundResource(R.drawable.bg_white_rounded);
That results in the SearchView looking exactly like the mockup.
I was able to achieve the desired result using only xml with androidx SearchView
<androidx.appcompat.widget.SearchView
...
app:queryBackground="#drawable/bg_white_rounded"
app:submitBackground="#drawable/bg_white_rounded"
android:background="#drawable/bg_white_rounded"/>
drawable/bg_white_rounded.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#ffffff"/>
<corners android:radius="20dp"/>
<padding android:left="15dp"
android:bottom="15dp"
android:right="15dp"
android:top="15dp"/>
</shape>
and in .xml
<SearchView
...
android:submitBackground="#drawable/bg_white_rounded"
android:background="#drawable/bg_white_rounded"
NOTE: in my situation, solution is combined from above answers. Thanks to #rajan.kali and #A.Kazarovets
Related
I want to create loader in android as same as attached gif
Thanks in advance
Without Plane in your Image I prefer to use ProgressBar
but I will Be More Easy to user SeekBar As Progress Bar
so let`s make it in Simplest way
in Layout XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:hardwareAccelerated="false"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<SeekBar
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:background="#32aaef"
android:id="#+id/sbHeight"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:max="100"
android:progress="0"
android:progressDrawable="#drawable/seekbar_as_progress"
android:thumb="#drawable/plane"
/>
</LinearLayout>
And where seekbar_as_progress is
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Define the background properties like color etc -->
<item android:id="#android:id/background">
<shape
android:shape="line"
android:useLevel="true">
<stroke
android:width="3dp"
android:color="#c9c9c9"
android:dashGap="20dp"
android:dashWidth="3dp" />
</shape>
</item>
<!-- Define the progress properties like start color, end color etc -->
<item android:id="#android:id/progress">
<clip>
<shape
android:shape="line"
android:useLevel="true">
<stroke
android:width="6dp"
android:color="#ffffff"
android:dashGap="20dp"
android:dashWidth="4dp" />
</shape>
</clip>
</item>
</layer-list>
and #drawable/plane is plane Icon
And In Your Activity
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// DountChart view = new DountChart(this);
setContentView(R.layout.empty);
final SeekBar sbHeight = findViewById(R.id.sbHeight);
sbHeight.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
sbHeight.setOnTouchListener(new View.OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
final int[] progress = {0};
final Handler ha=new Handler();
ha.postDelayed(new Runnable() {
#Override
public void run() {
//call function
if (progress[0] != 100){
AppLogger.log("Prog",progress[0]+"");
progress[0]= progress[0]+1;
sbHeight.setProgress(progress[0]);
ha.postDelayed(this, 100);
}
}
}, 100);
}
and that`s All
I want to get a reference to item inside of the layer-list for changing some attributes programmatically, But I can't see any difference and seems it does not work.
this is my code:
logo.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/circle">
<shape android:shape="oval">
<solid android:color="#fff"/>
<size android:height="33px" android:width="33px"/>
<stroke android:color="#000" android:width="2px"/>
</shape>
</item>
</layer-list>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.shahin.testing2.MainActivity">
<Button
android:layout_width="33px"
android:id="#+id/button"
android:layout_height="33px"
android:background="#drawable/logo"/>
</LinearLayout>
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LayerDrawable layerDrawable = (LayerDrawable)
ContextCompat.getDrawable(getApplicationContext(),R.drawable.logo);
GradientDrawable gradientDrawable = (GradientDrawable)
layerDrawable.findDrawableByLayerId(R.id.circle);
gradientDrawable.setStroke(10, Color.BLUE);
Button button = (Button)findViewById(R.id.button);
button.setBackgroundResource(R.drawable.logo);
}
in this case, when I changed the stroke color and width, no difference has appeared, what is the problem?
I am using RecyclerView with rounded corner, to make it rounded corner I used below XML:
view_rounded.xml:-
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#008f8471"/>
<stroke android:width="2dp" android:color="#ffffff" />
<corners android:radius="10dp"/>
</shape>
fragment_main.xml:-
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/view_rounded"/>
adapter_main.xml:-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/textTitle"
style="#style/AppTheme.ListTextView"
/>
</LinearLayout>
style.xml:-
<style name="AppTheme.ListTextView" parent="android:Widget.Material.TextView">
<item name="android:gravity">left</item>
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textAllCaps">false</item>
<item name="android:padding">10dp</item>
<item name="android:textAppearance">#android:style/TextAppearance.DeviceDefault.Medium</item>
<item name="android:textColor">#color/tabsScrollColor</item>
<item name="android:textStyle">bold</item>
</style>
Getting (without item separator):
Required (with item separator):
you should try add Divider
mListview.addItemDecoration(new DividerItemDecoration(this.getActivity(), LinearLayout.VERTICAL));
I have done this way:
onCreateView() of Fragment:
RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(getActivity()));
SimpleDividerItemDecoration.java:
public class SimpleDividerItemDecoration extends RecyclerView.ItemDecoration {
private Drawable mDivider;
public SimpleDividerItemDecoration(Context context) {
mDivider = context.getResources().getDrawable(R.drawable.recycler_horizontal_divider);
}
#Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
int left = parent.getPaddingLeft();
int right = parent.getWidth() - parent.getPaddingRight();
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
int top = child.getBottom() + params.bottomMargin;
int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
}
recycler_horizontal_divider.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size
android:width="1dp"
android:height="1dp" />
<solid android:color="#2EC590" />
</shape>
Hope this will help you.
RecyclerView works different from ListViews. You need to add ItemDecorators for the recycler view. As the docs says,
An ItemDecoration allows the application to add a special drawing and layout offset to specific item views from the adapter's data set. This can be useful for drawing dividers between items, highlights, visual grouping boundaries and more.
Take a look into this link : https://developer.android.com/reference/android/support/v7/widget/RecyclerView.ItemDecoration.html
Well what I did to achieve this is, I first created layout for my adapter row as
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<View
android:id="#+id/lineView"
android:layout_width="match_parent"
android:layout_height="2px"
android:background="#android:color/black"/>
<TextView
android:id="#+id/textTitle"
style="#style/AppTheme.ListTextView"
/>
</LinearLayout>
Then in my adapter I checked for first row and changed its viewLine Visibility to invisible
#Override
public void onBindViewHolder(ChildInfoViewHolder holder, final int position) {
if(position == 0){
holder.viewLine.setVisibility(View.INVISIBLE);
}
//...
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
protected View viewLine;
public ChildInfoViewHolder(View view) {
super(view);
viewLine = view.findViewById(R.id.viewLine);
//...
}
}
To add dividers to your recyclerview you need to use decorator - https://gist.github.com/alexfu/0f464fc3742f134ccd1e after you add that to your project add a line
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
This line of code worked for me:
recyclerView.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.HORIZONTAL));
For vertical line, pass second argument as DividerItemDecoration.VERTICAL.
Set the selector at the background of the list item in your layout if you are using custom adapter
Try this one:
A very nice solution by Michel-F. Portzert
public class ClippedListView extends ListView {
public ClippedListView(Context context) {
super(context);
}
public ClippedListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void dispatchDraw(Canvas canvas) {
float radius = 10.0f;
Path clipPath = new Path();
RectF rect = new RectF(0, 0, this.getWidth(), this.getHeight());
clipPath.addRoundRect(rect, radius, radius, Path.Direction.CW);
canvas.clipPath(clipPath);
super.dispatchDraw(canvas);
}
}
Try This From
Reference
Android: ListView with rounded corners
First off, we need the drawables for the backgrounds of the Lists entries:
For the entries in the middle of the list, we don't need rounded corners, so create a xml in your drawable folder "list_entry_middle.xml" with following content:
<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<stroke android:width="1px" android:color="#ffbbbbbb" />
</shape>
</item>
<item android:bottom="1dp" android:left="1dp" android:right="1dp">
<shape >
<solid android:color="#ffffffff" />
</shape>
</item>
</layer-list>
For the rounded corners, create another xml, "rounded_corner_top.xml":
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<stroke android:width="1dp" android:color="#ffbbbbbb" />
<corners android:topLeftRadius="20dp"
android:topRightRadius="20dp"
/>
</shape>
</item>
<item android:top="1dp" android:left="1dp" android:right="1dp" android:bottom="1dp">
<shape >
<solid android:color="#ffffffff" />
<corners android:topLeftRadius="20dp"
android:topRightRadius="20dp"
/>
</shape>
</item>
</layer-list>
Implementing the bottom part is quite the same, just with bottomLeftRadius and bottomRightRadius. (maybe also create one with all corners rounded, if the list only has one entry)
For better usability, also provide drawables with other colors for the different states, that the list item can have and reference them in another xml in the drawable folder ("selector_rounded_corner_top.xml") as followed:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/rounded_corner_top_click"
android:state_pressed="true" />
<item android:drawable="#drawable/rounded_corner_top_click"
android:state_focused="true" />
<item android:drawable="#drawable/rounded_corner_top" />
</selector>
Now do the same for the other backgrounds of the list.
All that is left now, is to assign the right backgrounds in our ListAdapter like following:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//...
//skipping the view reuse stuff
if (position == 0 && entry_list.size() == 1) {
view.setBackgroundResource(R.drawable.selector_rounded_corner);
} else if (position == 0) {
view.setBackgroundResource(R.drawable.selector_rounded_corner_top);
} else if (position == entry_list.size() - 1) {
view.setBackgroundResource(R.drawable.selector_rounded_corner_bottom);
} else {
view.setBackgroundResource(R.drawable.selector_middle);
}
//...
//skipping the filling of the view
}
Modify your ListView like below.Add the list_bg as the background of your ListView Also specify some padding for the top and the bottom of the listView otherwise the 1st and the last item in the list will overlap with the rounded corners showing rectangular corners.
<ListView
android:id="#+id/listView"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="#drawable/list_bg"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:fastScrollEnabled="true"
android:choiceMode="singleChoice" />
Use this drawable xml for curve shape listview and set background to your list view or any layout:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="6dp" />
<padding android:bottom="3dp" android:left="3dp" android:right="3dp" android:top="3dp" />
</shape>
Try this
custom_rounded_list.xml :
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#ff2521"
android:endColor="#2f5511"
android:angle="270"/>
<padding
android:bottom="5dp"
android:left="5dp"
android:right="5dp"
android:top="5dp" />
<corners
android:bottomRightRadius="7dp"
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp" />
</shape>
Your listview:
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/mylst"
android:background="#drawable/custom_rounded_list" />
you are setting list_selector for both textview and listview background. Use list_selector only for listview and if you want hover effect on textview too, then create another list_selector_textview which haven't include the <corners android:radius="10dp" property.
The problem is because you are setting the background with corners not only to the list view, but also to the item. You should make separate backgrounds for item (with selector) and one for list view with corners.
list_bg.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#008f8471"/>
<stroke android:width="1dip" android:color="#ffffff" />
<corners android:radius="10dp"/>
<padding android:left="0dip" android:top="0dip" android:right="0dip" android:bottom="0dip" />
</shape>
Now you can setup this drawable as the background of your list view.
<ListView
android:id="#+id/listView"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="#drawable/list_bg.xml"
android:fastScrollEnabled="true"
android:choiceMode="singleChoice" />
And for list view item you can use selector to have hover functionality:
list_item_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/list_item_selected" android:state_pressed="true"/>
<item android:drawable="#drawable/list_item_selected" android:state_pressed="false" android:state_selected="true"/>
<item android:drawable="#android:color/transparent"/>
Where list_item_selected is :
list_item_selected.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#4d8f8471"/>
<stroke android:width="1dip" android:color="#ffffff" />
</shape>
And after that you can setup this selector to the item in your xml:
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/list_item_selector" />
So your list view will have always same background with corners, and the background of items of list view, will be without corners and will be changed in pressed or selected state.
Just One Line...
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), null));
That's all
Try this
recyclerView.apply {
....
addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
}
what i basically wanna do is this:
When i click on the button i want its Text color to appear in a different color.
What i tried is this:
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:color="#color/red" />
<item
android:state_pressed="false"
android:color="#000" />
</selector>
and then i did use this selector as drawable on the button android:textColor
but this doesn solve it since it only changes its color while i press the button.
I want it like this:
Default: black
on click: blue
on click again: black
any ideas how to do that? :S
this is my shape for the button (if it matters):
<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetBottom="-1dp"
android:insetLeft="-1dp"
android:insetRight="-1dp">
<selector>
<item android:state_pressed="false">
<shape android:shape="rectangle" >
<corners
android:radius="0dp"
/>
<solid
android:color="#color/background_grey"
/>
<padding
android:left="0dp"
android:top="0dp"
android:right="0dp"
android:bottom="0dp"
/>
<size
android:width="100dp"
android:height="30dp"
/>
<stroke
android:width="1dp"
android:color="#ffb4b4b4"
/>
</shape>
</item>
<item android:state_pressed="true">
<shape android:shape="rectangle" >
<corners
android:radius="0dp"
/>
<solid
android:color="#color/pq_blue"
/>
<padding
android:left="0dp"
android:top="0dp"
android:right="0dp"
android:bottom="0dp"
/>
<size
android:width="100dp"
android:height="30dp"
/>
<stroke
android:width="1dp"
android:color="#ffb4b4b4"
/>
</shape>
</item>
</selector>
</inset>
thx in advance
EDIT
so i tried to do it programatically and tied the folowing just to see if it changes color´s ..but yea..it doesn´t (it seems like my onCLick event doesnt work):
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.listview_item, container, false);
final Button likeButton = (Button)rootView.findViewById(R.id.btLike);
likeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String test = "tester";
if(BUTTON_STATE==BUTTON_STATE_ONCE){
likeButton.setTextColor(getResources().getColor(R.color.pq_blue));
BUTTON_STATE = BUTTON_STATE_TWICE;
}else{
likeButton.setTextColor(getResources().getColor(R.color.red));
BUTTON_STATE = BUTTON_STATE_ONCE;
}
}
});
return rootView;
}
}
NOTE: i do all tht stuff in onCreateView since im in a Fragment of my ActionBarActivity(with tabs) if im doing it in the onCreate i get a null pointer exception at findViewById ( since it searches for the ID in my mainActivity, if im right?)
so yea..any ideas?
Your textselector.xml -
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:color="#color/red" /> <!--selected text colour-->
<item
android:state_focused="true"
android:color="#color/red" />
<item
android:color="#color/blue" /> <!--unselected text colour-->
</selector>
Your button in layout.xml -
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Exit"
android:textColor="#drawable/textselector" <!-- SET textselector HERE -->
android:background="#drawable/button_color"/>
You can use this code to do it programmatically:
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
ColorStateList myList=myButton.getTextColors();
int myColor=myList.getDefaultColor();
switch(myColor)
{
case Color.BLACK:
myButton.setTextColor(Color.BLUE);
break;
case Color.BLUE:
myButton.setTextColor(Color.BLACK);
break;
}
}
});
If You want to have a behaviour like:
First Click: Button text black
Second Click: Button text blue
third Click: button text black again
I don´t think it´s possible with the selector, also not with state focused. Because if any other view will be clicked, the button is not focused anymore and will loose the textcolor, goes back to default. You have to do it in a programmatically way:
First, set the default textColor to what You want: black inside Your xml. So than You have the color on no press. make a globa variabel to save the state:
private int BUTTON_STATE = 0;
private final int BUTTON_STATE_ONCE = 0;
private final int BUTTON_STATE_TWICE = 1;
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if(BUTTON_STATE==BUTTON_STATE_ONCE){
button.setTextColor(Color.BLUE);
BUTTON_STATE = BUTTON_STATE_TWICE;
}else if(BUTTON_STATE==BUTTON_STATE_TWICE){
button.setTextColor(Color.BLACK);
BUTTON_STATE = BUTTON_STATE_ONCE;
}
}
});
That´s just a possible solution, there are many ways..
EDIT
for Your code:
Create that global variables like i did in my example above, and use them in the if/else statement:
likeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(BUTTON_STATE==BUTTON_STATE_ONCE){
likeButton.setTextColor(getResources().getColor(R.color.pqBlue));
BUTTON_STATE = BUTTON_STATE_TWICE;
}else if(BUTTON_STATE==BUTTON_STATE_TWICE){
likeButton.setTextColor(getResources().getColor(R.color.pqBlack));
BUTTON_STATE = BUTTON_STATE_ONCE;
}
}
});
Try adding text_effect.xml drawable
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:color="#color/white" /> <!-- pressed -->
<item android:color="#color/black" /> <!-- default -->
</selector>
add this line in button control
android:textColor="#drawable/text_effect"
It will work. Enjoy:)
If you do not mandatorily need a simple Button, you could use a ToggleButton that is made for binary-state handling... With a ToggleButton your selector would look like this :
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:color="#color/red" />
<!-- Default State -->
<item android:color="#000" />
</selector>
It seems like you wanna implement something like toggle button.
Instead of button u can use toggle button.
Though if you wanna use button only then u need to do some changes in your java code as well as xml code also
Create a file def_btn.xml it will look like this..
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<corners
android:radius="0dp"
/>
<solid
android:color="#color/background_grey"
/>
<padding
android:left="0dp"
android:top="0dp"
android:right="0dp"
android:bottom="0dp"
/>
<size
android:width="100dp"
android:height="30dp"
/>
<stroke
android:width="1dp"
android:color="#ffb4b4b4"
/>
</shape>
Create another file press_btn.xml it will look like this..
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<corners
android:radius="0dp"
/>
<solid
android:color="#color/pq_blue"
/>
<padding
android:left="0dp"
android:top="0dp"
android:right="0dp"
android:bottom="0dp"
/>
<size
android:width="100dp"
android:height="30dp"
/>
<stroke
android:width="1dp"
android:color="#ffb4b4b4"
/>
</shape>
Inside your activity declare a private boolean variable(say isPressed) by default isPressed is false. & for default button background will be def_btn.xml
Now write following in button's onClick event.
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isPressed = !isPressed;
if(isPressed){
btn.setBackgroundResource(R.drawable.def_btn);
}else{
btn.setBackgroundResource(R.drawable.press_btn);
}
}
});
That's it..
Is there a android standard badge or method to show action bar notification icon with a count like on Google examples?
If not, then what is the best way to make it?
I'm new to android, please help.
I am not sure if this is the best solution or not, but it is what I need.
Please tell me if you know what is need to be changed for better performance or quality. In my case, I have a button.
Custom item on my menu - main.xml
<item
android:id="#+id/badge"
android:actionLayout="#layout/feed_update_count"
android:icon="#drawable/shape_notification"
android:showAsAction="always">
</item>
Custom shape drawable (background square) - shape_notification.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke android:color="#22000000" android:width="2dp"/>
<corners android:radius="5dp" />
<solid android:color="#CC0001"/>
</shape>
Layout for my view - feed_update_count.xml
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/notif_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="32dp"
android:minHeight="32dp"
android:background="#drawable/shape_notification"
android:text="0"
android:textSize="16sp"
android:textColor="#android:color/white"
android:gravity="center"
android:padding="2dp"
android:singleLine="true">
</Button>
MainActivity - setting and updating my view
static Button notifCount;
static int mNotifCount = 0;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, menu);
View count = menu.findItem(R.id.badge).getActionView();
notifCount = (Button) count.findViewById(R.id.notif_count);
notifCount.setText(String.valueOf(mNotifCount));
return super.onCreateOptionsMenu(menu);
}
private void setNotifCount(int count){
mNotifCount = count;
invalidateOptionsMenu();
}
Edit Since version 26 of the support library (or androidx) you no longer need to implement a custom OnLongClickListener to display the tooltip. Simply call this:
TooltipCompat.setTooltipText(menu_hotlist, getString(R.string.hint_show_hot_message));
I'll just share my code in case someone wants something like this:
layout/menu/menu_actionbar.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
...
<item android:id="#+id/menu_hotlist"
android:actionLayout="#layout/action_bar_notifitcation_icon"
android:showAsAction="always"
android:icon="#drawable/ic_bell"
android:title="#string/hotlist" />
...
</menu>
layout/action_bar_notifitcation_icon.xml
Note style and android:clickable properties. these make the layout the size of a button and make the background gray when touched.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center"
android:layout_gravity="center"
android:clickable="true"
style="#android:style/Widget.ActionButton">
<ImageView
android:id="#+id/hotlist_bell"
android:src="#drawable/ic_bell"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_margin="0dp"
android:contentDescription="bell"
/>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/hotlist_hot"
android:layout_width="wrap_content"
android:minWidth="17sp"
android:textSize="12sp"
android:textColor="#ffffffff"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#null"
android:layout_alignTop="#id/hotlist_bell"
android:layout_alignRight="#id/hotlist_bell"
android:layout_marginRight="0dp"
android:layout_marginTop="3dp"
android:paddingBottom="1dp"
android:paddingRight="4dp"
android:paddingLeft="4dp"
android:background="#drawable/rounded_square"/>
</RelativeLayout>
drawable-xhdpi/ic_bell.png
A 64x64 pixel image with 10 pixel wide paddings from all sides. You are supposed to have 8 pixel wide paddings, but I find most default items being slightly smaller than that. Of course, you'll want to use different sizes for different densities.
drawable/rounded_square.xml
Here, #ff222222 (color #222222 with alpha #ff (fully visible)) is the background color of my Action Bar.
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="2dp" />
<solid android:color="#ffff0000" />
<stroke android:color="#ff222222" android:width="2dp"/>
</shape>
com/ubergeek42/WeechatAndroid/WeechatActivity.java
Here we make it clickable and updatable! I created an abstract listener that provides Toast creation on onLongClick, the code was taken from from the sources of ActionBarSherlock.
private int hot_number = 0;
private TextView ui_hot = null;
#Override public boolean onCreateOptionsMenu(final Menu menu) {
MenuInflater menuInflater = getSupportMenuInflater();
menuInflater.inflate(R.menu.menu_actionbar, menu);
final View menu_hotlist = menu.findItem(R.id.menu_hotlist).getActionView();
ui_hot = (TextView) menu_hotlist.findViewById(R.id.hotlist_hot);
updateHotCount(hot_number);
new MyMenuItemStuffListener(menu_hotlist, "Show hot message") {
#Override
public void onClick(View v) {
onHotlistSelected();
}
};
return super.onCreateOptionsMenu(menu);
}
// call the updating code on the main thread,
// so we can call this asynchronously
public void updateHotCount(final int new_hot_number) {
hot_number = new_hot_number;
if (ui_hot == null) return;
runOnUiThread(new Runnable() {
#Override
public void run() {
if (new_hot_number == 0)
ui_hot.setVisibility(View.INVISIBLE);
else {
ui_hot.setVisibility(View.VISIBLE);
ui_hot.setText(Integer.toString(new_hot_number));
}
}
});
}
static abstract class MyMenuItemStuffListener implements View.OnClickListener, View.OnLongClickListener {
private String hint;
private View view;
MyMenuItemStuffListener(View view, String hint) {
this.view = view;
this.hint = hint;
view.setOnClickListener(this);
view.setOnLongClickListener(this);
}
#Override abstract public void onClick(View v);
#Override public boolean onLongClick(View v) {
final int[] screenPos = new int[2];
final Rect displayFrame = new Rect();
view.getLocationOnScreen(screenPos);
view.getWindowVisibleDisplayFrame(displayFrame);
final Context context = view.getContext();
final int width = view.getWidth();
final int height = view.getHeight();
final int midy = screenPos[1] + height / 2;
final int screenWidth = context.getResources().getDisplayMetrics().widthPixels;
Toast cheatSheet = Toast.makeText(context, hint, Toast.LENGTH_SHORT);
if (midy < displayFrame.height()) {
cheatSheet.setGravity(Gravity.TOP | Gravity.RIGHT,
screenWidth - screenPos[0] - width / 2, height);
} else {
cheatSheet.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, height);
}
cheatSheet.show();
return true;
}
}
Just to add. If someone wants to implement a filled circle bubble, heres the code (name it bage_circle.xml):
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="ring"
android:useLevel="false"
android:thickness="9dp"
android:innerRadius="0dp"
>
<solid
android:color="#F00"
/>
<stroke
android:width="1dip"
android:color="#FFF" />
<padding
android:top="2dp"
android:bottom="2dp"/>
</shape>
You may have to adjust the thickness according to your need.
EDIT:
Here's the layout for button (name it badge_layout.xml):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<com.joanzapata.iconify.widget.IconButton
android:layout_width="44dp"
android:layout_height="44dp"
android:textSize="24sp"
android:textColor="#color/white"
android:background="#drawable/action_bar_icon_bg"
android:id="#+id/badge_icon_button"/>
<TextView
android:id="#+id/badge_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#id/badge_icon_button"
android:layout_alignRight="#id/badge_icon_button"
android:layout_alignEnd="#id/badge_icon_button"
android:text="10"
android:paddingEnd="8dp"
android:paddingRight="8dp"
android:paddingLeft="8dp"
android:gravity="center"
android:textColor="#FFF"
android:textSize="11sp"
android:background="#drawable/badge_circle"/>
</RelativeLayout>
In Menu create item:
<item
android:id="#+id/menu_messages"
android:showAsAction="always"
android:actionLayout="#layout/badge_layout"/>
In onCreateOptionsMenu get reference to the Menu item:
itemMessages = menu.findItem(R.id.menu_messages);
badgeLayout = (RelativeLayout) itemMessages.getActionView();
itemMessagesBadgeTextView = (TextView) badgeLayout.findViewById(R.id.badge_textView);
itemMessagesBadgeTextView.setVisibility(View.GONE); // initially hidden
iconButtonMessages = (IconButton) badgeLayout.findViewById(R.id.badge_icon_button);
iconButtonMessages.setText("{fa-envelope}");
iconButtonMessages.setTextColor(getResources().getColor(R.color.action_bar_icon_color_disabled));
iconButtonMessages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (HJSession.getSession().getSessionId() != null) {
Intent intent = new Intent(getThis(), HJActivityMessagesContexts.class);
startActivityForResult(intent, HJRequestCodes.kHJRequestCodeActivityMessages.ordinal());
} else {
showLoginActivity();
}
}
});
After receiving notification for messages, set the count:
itemMessagesBadgeTextView.setText("" + count);
itemMessagesBadgeTextView.setVisibility(View.VISIBLE);
iconButtonMessages.setTextColor(getResources().getColor(R.color.white));
This code uses Iconify-fontawesome.
compile 'com.joanzapata.iconify:android-iconify-fontawesome:2.1.+'
I don't like ActionView based solutions,
my idea is:
create a layout with TextView, that TextView will be populated by
application
when you need to draw a MenuItem:
2.1. inflate layout
2.2. call measure() & layout() (otherwise view will be 0px x 0px, it's too small for most use cases)
2.3. set the TextView's text
2.4. make "screenshot" of the view
2.6. set MenuItem's icon based on bitmap created on 2.4
profit!
so, result should be something like
create layout
here is a simple example
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/counterPanel"
android:layout_width="32dp"
android:layout_height="32dp"
android:background="#drawable/ic_menu_gallery">
<RelativeLayout
android:id="#+id/counterValuePanel"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/counterBackground"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/unread_background" />
<TextView
android:id="#+id/count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:textSize="8sp"
android:layout_centerInParent="true"
android:textColor="#FFFFFF" />
</RelativeLayout>
</FrameLayout>
#drawable/unread_background is that green TextView's background,
#drawable/ic_menu_gallery is not really required here, it's just to preview layout's result in IDE.
add code into onCreateOptionsMenu/onPrepareOptionsMenu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem menuItem = menu.findItem(R.id.testAction);
menuItem.setIcon(buildCounterDrawable(count, R.drawable.ic_menu_gallery));
return true;
}
Implement build-the-icon method:
private Drawable buildCounterDrawable(int count, int backgroundImageId) {
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.counter_menuitem_layout, null);
view.setBackgroundResource(backgroundImageId);
if (count == 0) {
View counterTextPanel = view.findViewById(R.id.counterValuePanel);
counterTextPanel.setVisibility(View.GONE);
} else {
TextView textView = (TextView) view.findViewById(R.id.count);
textView.setText("" + count);
}
view.measure(
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.setDrawingCacheEnabled(true);
view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
return new BitmapDrawable(getResources(), bitmap);
}
The complete code is here: https://github.com/cvoronin/ActionBarMenuItemCounter
Ok, for #AndrewS solution to work with v7 appCompat library:
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:someNamespace="http://schemas.android.com/apk/res-auto" >
<item
android:id="#+id/saved_badge"
someNamespace:showAsAction="always"
android:icon="#drawable/shape_notification" />
</menu>
.
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.main, menu);
MenuItem item = menu.findItem(R.id.saved_badge);
MenuItemCompat.setActionView(item, R.layout.feed_update_count);
View view = MenuItemCompat.getActionView(item);
notifCount = (Button)view.findViewById(R.id.notif_count);
notifCount.setText(String.valueOf(mNotifCount));
}
private void setNotifCount(int count){
mNotifCount = count;
supportInvalidateOptionsMenu();
}
The rest of the code is the same.
Try looking at the answers to these questions, particularly the second one which has sample code:
How to implement dynamic values on menu item in Android
How to get text on an ActionBar Icon?
From what I see, You'll need to create your own custom ActionView implementation. An alternative might be a custom Drawable. Note that there appears to be no native implementation of a notification count for the Action Bar.
EDIT: The answer you were looking for, with code: Custom Notification View with sample implementation
When you use toolbar:
....
private void InitToolbar() {
toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
toolbartitle = (TextView) findViewById(R.id.titletool);
toolbar.inflateMenu(R.menu.show_post);
toolbar.setOnMenuItemClickListener(this);
Menu menu = toolbar.getMenu();
MenuItem menu_comments = menu.findItem(R.id.action_comments);
MenuItemCompat
.setActionView(menu_comments, R.layout.menu_commentscount);
View v = MenuItemCompat.getActionView(menu_comments);
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Your Action
}
});
comment_count = (TextView) v.findViewById(R.id.count);
}
and in your load data call refreshMenu():
private void refreshMenu() {
comment_count.setVisibility(View.VISIBLE);
comment_count.setText("" + post_data.getComment_count());
}
I found a very good solution here, I'm using it with kotlin.
First, in the drawable folder you have to create item_count.xml:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="8dp" />
<solid android:color="#f20000" />
<stroke
android:width="2dip"
android:color="#FFF" />
<padding
android:bottom="5dp"
android:left="5dp"
android:right="5dp"
android:top="5dp" />
</shape>
In your Activity_Main Layout some like:
<RelativeLayout
android:id="#+id/badgeLayout"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_toRightOf="#+id/badge_layout1"
android:layout_gravity="end|center_vertical"
android:layout_marginEnd="5dp">
<RelativeLayout
android:id="#+id/relative_layout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="#+id/btnBadge"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#mipmap/ic_notification" />
</RelativeLayout>
<TextView
android:id="#+id/txtBadge"
android:layout_width="18dp"
android:layout_height="18dp"
android:layout_alignRight="#id/relative_layout1"
android:background="#drawable/item_count"
android:text="22"
android:textColor="#FFF"
android:textSize="7sp"
android:textStyle="bold"
android:gravity="center"/>
</RelativeLayout>
And you can modify like:
btnBadge.setOnClickListener { view ->
Snackbar.make(view,"badge click", Snackbar.LENGTH_LONG) .setAction("Action", null).show()
txtBadge.text = "0"
}
I found better way to do it.
if you want to use something like this
Use this dependency
compile 'com.nex3z:notification-badge:0.1.0'
create one xml file in drawable and Save it as Badge.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="oval">
<solid android:color="#66000000"/>
<size android:width="30dp" android:height="40dp"/>
</shape>
</item>
<item android:bottom="1dp" android:right="0.6dp">
<shape android:shape="oval">
<solid android:color="#color/Error_color"/>
<size android:width="20dp" android:height="20dp"/>
</shape>
</item>
</layer-list>
Now wherever you want to use that badge use following code in xml.
with the help of this you will be able to see that badge on top-right corner of your image or anything.
<com.nex3z.notificationbadge.NotificationBadge
android:id="#+id/badge"
android:layout_toRightOf="#id/Your_ICON/IMAGE"
android:layout_alignTop="#id/Your_ICON/IMAGE"
android:layout_marginLeft="-16dp"
android:layout_marginTop="-8dp"
android:layout_width="28dp"
android:layout_height="28dp"
app:badgeBackground="#drawable/Badge"
app:maxTextLength="2"
></com.nex3z.notificationbadge.NotificationBadge>
Now finally on yourFile.java use this 2 simple thing..
1) Define
NotificationBadge mBadge;
2) where your loop or anything which is counting this number use this:
mBadge.setNumber(your_LoopCount);
here, mBadge.setNumber(0) will not show anything.
Hope this help.