One selected item on a listview - android

I have made a listview. The plan is that when you select an item, it should appear selected (background color changes) and when you select another one, the one that was selected previously is normal again. Is there a way to do this? I've been trying a bunch of things and nothing works...
This is my code so far...
/*Listview testing*/
final ListView listview = (ListView) findViewById(R.id.listView1);
String[] values = new String[] {
"Case White",
"Operation Weser-Exercise",
"Case Yellow",
"April War",
"Operation Barbarossa",
"D-day" };
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < values.length; ++i) {
list.add(values[i]);
}
final StableArrayAdapter adapter = new StableArrayAdapter(this,
android.R.layout.simple_list_item_1, list);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
//This doesn't work:
//listview.findViewById((int) selid).setBackgroundColor(Color.TRANSPARENT);
view.setSelected(true);
view.setBackgroundColor(Color.LTGRAY);
Context context = getApplicationContext();
CharSequence text = "id: " + id;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
selid = id;
}
});
Marking one of them works, but then removing the selection is where I'm stuck. Any suggestions?
EDIT: what I'm looking for is for it to stay selected until I select another item

I think the problem is that your onItemClick method only fires for the list item that gets clicked. Every other item in the list remains unchanged.
What you need is a way to update all the items at once. The easiest way to do this is to write a custom adapter that extends BaseAdapter, then call myAdapter.notifyDataSetChanged(). I can provide an example if you'd like, but I would recommend looking for a tutorial on extending BaseAdapter.

First thing is to configure the ListView to singleChoice because only one item can be selected :
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:choiceMode="singleChoice">
</ListView>
Then, you need to create a selector. This is where you will configure colors for each defined state. The selected file
is in res/drawable directory.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
android:exitFadeDuration="#android:integer/config_mediumAnimTime">
<item android:drawable="#android:color/holo_orange_dark" android:state_pressed="true"/>
<item android:drawable="#android:color/holo_green_light" android:state_selected="true"/>
<item android:drawable="#android:color/holo_green_light" android:state_activated="true"/>
</selector>
Then, on the item layout, add the attribute activatedBackgroundIndicator at top level:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="?android:attr/activatedBackgroundIndicator">
<!-- your item content-->
</LinearLayout>
Finally, you need to link the selector with your ListView. This can be done in method onCreate of a ListActivity or
in method onActivityCreated of a ListFragment.
this.getListView().setSelector(R.drawable.your_selector);
Thats all.
//EDIT
I didnot explain how to change the blue color.
Here is the solution :
Create a file *res/drawable/listitem_background.xml* with the following content :
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_activated="true" android:drawable="#color/purple_dark" />
<item android:drawable="#android:color/transparent" />
</selector>
Replace the *#color/purple_dark* with the color of your choice.
Then, in your theme, add the following line :
<item name="android:activatedBackgroundIndicator">#drawable/listitem_background</item>
video: http://www.youtube.com/watch?v=BlZmE6Fk40M

Related

Change color of a disabled spinner Android

When I disable my spinner it's dispalyed a text with an alpha so texte become a little not visible, my question how I can change this color ?
PS : I don't need to change the color of the spinner's texte.
Create a color folder in res and create a color state my_text_color.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#color/disableColor" android:state_enabled="false"/>
<item android:color="#color/enableColor"/>
</selector>
and your textview
look like
<TextView
android:textColor="#color/my_text_color"
In adapter you need to inflate the layout that contain the Textview.
Inside your adapter constructor, send the id of textview also
public CustomAdapter(Activity context,int resouceId, int textviewId, List<RowItem> list){
super(context,resouceId,textviewId, list);
flater = context.getLayoutInflater();
}
call it by
CustomAdapter adapter = new CustomAdapter(MainActivity.this,
R.layout.listitems_layout, R.id.title, rowItems);
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:color="#color/disabled_color"/>
<item android:color="#color/normal_color"/>
</selector>
<EditText
android:id="#+id/customEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:enabled="false"
android:text="Hello!"
android:textColor="#drawable/edit_text_selector" />
// first code used in drawable/edit_text_selector.xml

Set text color in Android Spinner

I want to change the color of the displayed selected item in my spinner in Android (targeting API level 16 and up). I have tried several solutions posted here on SO, including creating a custom layout for my spinner items and using a ColorStateList as the text color property of the custom layout, but to no avail. The spinner is shown on a semi-transparent background - therefore the custom layout for the items does not work as it adds a color to the spinner. Currently my hack solution is
if (_colorCodeSpinner.getSelectedView() != null) {
((TextView) _colorCodeSpinner.getSelectedView()).setTextColor(0xFFFFFFFF);
}
but this only works if the selected view is not null (which it is on orientation change).
I cannot believe that there isn't a simple solution for setting the text color. It seems like something you would often do. The same with changing the color of the arrow, which I currently do by
_colorCodeSpinner.getBackground().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
Am I missing something? What is the recommended way of changing the colors on a spinner?
As seen in the image, the text color of the displayed selected item in the spinner is black, but I want to change it to be white.
EDIT
To clarify: I'm not looking for some small piece of code that overrides values at runtime (like the two snippets I posted in this question). I'm looking for an actual way to do this properly (like in the XML layout or through themes). To set the text color property once so I don't have to update it every time I e.g. select an item.
Do this :
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
((TextView) parent.getChildAt(0)).setTextColor(Color.WHITE); /* if you want your item to be white */
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
You can achieve this editing styles.xml layout file. For this answer i use a new project in Android Studio, with minSdkVersion 16 and AppCompatSpinner.
styles.xml layout:
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="android:spinnerItemStyle">#style/mySpinnerItemSelectedStyle</item>
</style>
<style name="mySpinnerItemSelectedStyle" parent="#android:style/Widget.Holo.TextView.SpinnerItem">
<item name="android:textColor">#color/spinnerTextColor</item>
</style>
And add this at colors.xml file:
<color name="spinnerTextColor">#ffffff</color>
The solution was taken from the link below. Although it's used for color spinner dropdown items, is mostly the same approach.
https://stackoverflow.com/a/22207394/6514926
This will work for you
public void onItemSelected(AdapterView<?> parent, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
item = (String) parent.getItemAtPosition(arg2);
((TextView) parent.getChildAt(0)).setTextColor(0x00000000);
}
OR
you can use selector for changing color
create one xml named my_selctor.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:color="black" /> <!-- pressed -->
<item android:state_focused="true"
android:color="black" /> <!-- focused -->
<item android:color="white" /> <!-- default -->
</selector>
and in your text view set it like this way
<TextView ...........
android:textColor=""#drawable/my_selctor"/>
try the following code:-
XML:-
<Spinner
android:id="#+id/spinner"
android:layout_width="match_parent"
android:layout_margin="20dp"
android:popupBackground="#ffffff"
android:layout_height="match_parent">
</Spinner>
create a another xml for the textview
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="dshsgv"
android:padding="5dp"
android:textColor="#000000">
</TextView>
then in your activity:-
public class MainActivity extends AppCompatActivity {
Spinner spinner;
String[] cat = {"Automobile", "Automobile"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adpter = new ArrayAdapter<String> (MainActivity.this, R.layout.text, cat);
spinner.setAdapter(adpter);
}
}
declare ArrayAdapter like this and set it to your spinner:
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this,
R.layout.simple_spinner_dropdown_item, your_strings);
adapter_state.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
_colorCodeSpinner.setAdapter(adapter_state);
and layout xml file simple_spinner_dropdown_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:gravity="left"
android:textColor="#AAA"
android:padding="5dp"
/>
this work for me
follow this link
private OnItemSelectedListener OnCatSpinnerCL = new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
((TextView) parent.getChildAt(0)).setTextColor(Color.BLUE);
((TextView) parent.getChildAt(0)).setTextSize(12);
}
public void onNothingSelected(AdapterView<?> parent) {
}
};
You can use like this. This will change your icon of DropDown menu.
spinner.getBackground().setColorFilter(Color.parseColor("#FFFFFF"), PorterDuff.Mode.SRC_ATOP);
then make one TextView layout name with spinner_text.xml like this
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/spinnerText"
style="?android:attr/spinnerDropDownItemStyle"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:ellipsize="marquee"
android:textColor="#fff" />
and write this code in your MainActivity.java class like
List<String> categories = new ArrayList<String>();
categories.add("Automobile");
categories.add("Business Services");
categories.add("Computers");
categories.add("Education");
categories.add("Personal");
categories.add("Travel");
ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.spinner_text, categories);
spinner.setAdapter(adapter);
spinner.getBackground().setColorFilter(ContextCompat.getColor(this,R.color.white), PorterDuff.Mode.SRC_ATOP);
// attaching data adapter to spinner
spinner.setAdapter(adapter);

Change background color of the selected item in Android Spinner

I am working on an android app and using Spinner at many places in my app.
What I want is to change the background color of the selected item of spinner, so that one can easily identify which item is currently selected.
I have already checked this link Setting background color for Spinner Item on selection but doing so will change the selected textview background color but do not change its color in dropdown list and I want to change the background color of the selected textview when I will see the dropdown list.
I want to change the color of selected item in list not on spinner, please see the image below.
How can I do this? Please, can someone help me here?.
Thanks a lot in advanced.
You need to implement below method in your adapter class:
It will help you:
int selectedItem = -1;
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list) {
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
View v = null;
v = super.getDropDownView(position, null, parent);
// If this is the selected item position
if (position == selectedItem) {
v.setBackgroundColor(Color.BLUE);
}
else {
// for other views
v.setBackgroundColor(Color.WHITE);
}
return v;
}
};
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(dataAdapter);
Now on item selected in spinner put below
selectedItem = position;
Here is solution via XML:
Spinner looks like:
<Spinner
android:id="#+id/settingsSleepingTimePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/spinner_main_button"
android:popupBackground="#color/colorPrimary"
android:textColor="#android:color/white"
android:textSize="20sp"/>
While creating spinner set setDropDownViewResource as custom layout:
adapter.setDropDownViewResource(R.layout.spinner_item);
And spinner_item.xml looks like:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/spinner"
android:textColor="#ffffff"
android:textSize="20sp" />
And finally we set #drawable/spinner like this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#color/colorPrimaryLight" android:state_hovered="true" />
<item android:drawable="#color/colorPrimaryLight" android:state_selected="true" />
</selector>
Hope my answer will be helpfull!
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="colorControlNormal">#color/spinner_background</item>
</style>
Define Spinner_background color in color folder..
Try creating a selector in the drawable, something like,
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false" android:drawable="#color/colorPrimary" />
<item android:drawable="#android:color/transparent" />
</selector>
And set the spinner background as
android:background="#drawable/spinner_selector"
I've searched the internet for a proper solution to do this without hardcoding the background behaviour in java code.
You can achieve this (setting the selected item background color) using drawables.
What you need to do it set the dropdownViewResource to a custom layout. That layout should look something like this:
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/spinner_item_background"
android:gravity="left"
android:padding="8dp" />
In spinner_item_background.xml, you can define a background for each item state. For example, if you want to have a ripple effect on press, but a solid effect when selected, you can try this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Activated state is the selected item -->
<item android:state_activated="true" android:drawable="#00ff00"/>
<!-- Pressed state is the one the user is interacting with -->
<item android:state_pressed="true" android:drawable="#00ff00"/>
<!-- The rest of the items -->
<item android:drawable="#ffffff"/>
</selector>
Create an int variable public static int posOfItemSpinnerSelected in your Activity:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
posOfItemSpinnerSelected=position;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
and in your adapter insert this code
if(position== YourActivity.posOfItemSpinnerSelected){
textView.setBackgroundColor(ContextCompat.getColor(mActivity,R.color.item_spinner_selected));
} else {
textView.setBackgroundColor(ContextCompat.getColor(mActivity,R.color.white));
}

Changing the color for selected item in spinner

For some reason the text color of the selected item in my spinner is white. Here's the code for the Activity:
spinner = (Spinner) findViewById(R.id.spinner_categories);
arr_list_categories = manager.get_all_categories();
arr_list_categories_names = new ArrayList<String>();
// Loop through the Categories array
for (int i = 0; i < arr_list_categories.size(); i++)
{
Category curr_category = arr_list_categories.get(i); // Get the Category object at current position
arr_list_categories_names.add(curr_category.getCategory_name()
.toString()); // Add the name of the Category to the Names Array
}
// Setting the Adapter, to display retrieved data in the Spinner
adapter=new ArrayAdapter<String> (this, R.layout.simple_spinner_item, arr_list_categories_names);
// Setting the display source for the Spinner View
adapter.setDropDownViewResource(R.layout.simple_spinner_item);
// Populating the Spinner
spinner.setAdapter(adapter);
// Registering for On Item Selected listener
spinner.setOnItemSelectedListener(spinnerListener);
And here's the XML of simple_spinner_item:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:padding="5dip"
android:textColor="#FF0000"
android:textSize="20sp" />
The dropdown items appear in red, but not the selected item. I tried to change the textColor in XML to selector: android:textColor="#drawable/spinner_text_color_selector" and created this selector:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="#FF0000"/><!-- pressed -->
<item android:state_focused="true" android:color="#FF0000"/><!-- focused -->
<item android:state_selected="true" android:color="#FF0000"/>
<item android:state_activated="true" android:color="#FF0000"/>
<item android:color="#FF0000"/><!-- default -->
</selector>
But the selected item's text color was still white. So I tried to do this in OnItemSelectedListener:
TextView selected_tv = (TextView) parent.getChildAt(0);
selected_tv.setTextColor(Color.BLUE);
Still white...
Why is it happening and how do I fix it? Thank you!
TextView selected_tv = (TextView) parent.getChildAt(0);
selected_tv.setTextColor(Color.BLUE);
In this code, change in first line like this (Use TextView's id):
TextView selected_tv = (TextView) parent.findViewById(R.id.selected_tv);
selected_tv.setTextColor(Color.BLUE);

Navigation Drawer item background colour for selected item

I used Android Studio to implement the Navigation Drawer and I can't get the blue colour that is used to show which section we're currently in to change.
I've tried numerous things, I'm currently using a listSelector which looks like:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_activated="true" android:drawable="#color/selected" />
<item android:state_pressed="true" android:drawable="#color/highlight" />
</selector>
I've also tried state_checked. state_pressed works in this situation but the currently selected item is still blue.
EDIT:
I've been examining this more and when the adapter is created the context that is passed is getActionBar().getThemedContext() so I'm thinking if I can find the right attribute to assign to my actionbar style I can change it from there. I've tried a few different attributes with no luck. Does anyone know the exact attribute?
I've also realised if I put
<item name="android:activatedBackgroundIndicator">#drawable/nav_listview_selector</item>
in the main part of my theme and change getActionBar().getThemedContext() for getActivity.getBaseContext then I can change the color but I don't think this is the correct way. I think the themed context should be used. So if anyone knows where the activatedBackgroundIndicator could be put so that it would be used in getActionBar.getThemedContext()
EDIT2:
So the text view used for the listview is one within the SDK it looks like this:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:paddingStart="?android:attr/listPreferredItemPaddingStart"
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
android:background="?android:attr/activatedBackgroundIndicator"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
/>
So I tried modifying the "?android:attr/activatedBackgroundIndicator" at the theme level but it has no effect for checked/selected/activated but it does for pressed. Does anyone know why this is? And how I can change it?
To solve this problem:
1- You don't need android:listSelector under your ListView.
2- Open (or Create) styles.xml under (res/values).
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="android:activatedBackgroundIndicator">#drawable/drawer_list_selector</item>
</style>
3- Under res/drawable folder create drawer_list_selector.xml file
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="#drawable/light_gray_color" />
<item android:state_activated="true" android:drawable="#drawable/red_color" />
<item android:drawable="#android:color/transparent" />
</selector>
4- Under res/drawable create red_color.xml / light_gray_color.xml (or any other name) and add your desired Hex color:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#C8FF0000"/>
</shape>
5- Open your project AndroidManifest.xml and add android:theme tag (if not exist)
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
Reference / Credit: Changing Navigation Drawer Selected Item Color from default blue
To change the "Navigation Drawer item background colour for selected item" you could do it with the attribut:
colorControlHighlight
In your "styles.xml" it could look like this:
<style name="YourStyleNameFor.NavigationDrawer" parent="ThemeOverlay.AppCompat.Light">
<item name="colorControlHighlight">#color/your_highlight_color</item>
</style>
Don't forget to apply your Style in the tag:
android.support.design.widget.NavigationView
For example in your activity_main.xml it could look like this:
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/navigationdrawer_header"
<!-- the following line referes to your style -->
app:theme="#style/YourThemeNameFor.NavigationDrawer"
<!-- the following two lines are maybe also interesting for you -->
app:itemIconTint="#color/gray3"
app:itemTextColor="#color/gray3"
app:menu="#menu/navigationdrawer_main" />
This is working for me:
First define a drawable item_bg.xml as:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="#drawable/nav_menu_bg" />
</selector>
Then use this drawable in navigation_main_layout.xml as:
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:itemBackground="#drawable/item_bg"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_navigation"
app:menu="#menu/navigation_main_layout_drawer" />
here is how i have done and it is working, the brief concept is maintain the position of selected item in adapter and call notifyDataSetChanged on calling notifyDatasetChanged the getView method is called again and in get view check the position on the selected position change the background view. Here is the code :
Adapter of NavigationDrawer List View
public class MenuAdapter extends BaseAdapter {
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
private Context mContext;
private String name;
private int profile;
private int mIcons[];
private int selectedPosition = 0;
private String mNavTitles[];
private LayoutInflater mInflater;
public MenuAdapter(String titles[], int icon[], String Name, int profile) {
mNavTitles = titles;
mIcons = icon;
name = Name;
this.profile = profile;
}
public MenuAdapter(String Titles[], int Icons[], Context mContext) {
mNavTitles = Titles;
mIcons = Icons;
this.mContext = mContext;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mNavTitles.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mInflater.inflate(R.layout.item_row, parent, false);
TextView textView = (TextView) convertView.findViewById(R.id.rowText);
ImageView imageView = (ImageView) convertView.findViewById(R.id.rowIcon);
final LinearLayout layout = (LinearLayout) convertView.findViewById(R.id.outerLayout);
imageView.setImageResource(mIcons[position]);
textView.setText(mNavTitles[position]);
if (position == selectedPosition)
layout.setBackgroundColor(mContext.getResources().getColor(R.color.app_bg));
else
layout.setBackgroundColor(mContext.getResources().getColor(R.color.normal_bg));
return convertView;
}
public void setSelectedPosition(int position) {
this.selectedPosition = position;
}
}
in your activity do this
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
mMenuAdapter.setSelectedPosition(position - 1);
mMenuAdapter.notifyDataSetChanged();
}
}
if anyone still face any difficulty, feel free to ask.
I have implement drawer menu with custom adapter class. May be it will help someone Drawer List
<ListView
android:id="#+id/listview_drawer"
android:layout_width="260dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/menu_item_color"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:fadingEdge="none"
/>
drawer_list_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/menu_selector"
>
<ImageView
android:id="#+id/imgIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:src="#drawable/ic_menu_home" />
<TextView
android:id="#+id/lblName"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:layout_toRightOf="#+id/imgIcon"
android:minHeight="48dp"
android:textColor="#color/menu_txt_color" />
menu_selector.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android" android:exitFadeDuration="#android:integer/config_mediumAnimTime">
<!-- selected -->
<item android:drawable="#color/menu_item_active_color" android:state_focused="true" android:state_pressed="false"/>
<item android:drawable="#color/menu_item_active_color" android:state_pressed="true"/>
<item android:drawable="#color/menu_item_active_color" android:state_activated="true"/>
<item android:drawable="#color/menu_item_active_color" android:state_checked="true"/>
<item android:drawable="#color/menu_item_active_color" android:state_selected="true"/>
<item android:drawable="#color/menu_item_color" android:state_activated="false"/>
Add this on item click listner of listview
yourlistview.setItemChecked(position, true);
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#color/list_item_back_pressed" android:state_pressed="true" />
<item android:state_activated="true"><color android:color="#color/primary_blue"/></item>
<item android:drawable="#color/list_item_back_normal"/>
</selector>
In addition to providing a custom selector drawable for the listSelector, you should also set the background resource of the list item to a similar selector drawable that has different drawables for the different states.
I usually use my custom adapter that has an int selection field, and a setSelection(int) function. And in the getView function I set the background of the view according to position == selection.
Still not sure why it is that it doesn't work. But the way I found around it is to use my own simple_list_item_activated layout to be passed to the ArrayAdapter which was basically the same except for setting the text colour to white. I then replaced getActionBar().getThemedContext() with getActivity().getBaseContext() and it now has an effect.
This may not be the correct way and may have repercussions in the future, but for now I have it working the way I want it to.
I know its too late but I have solved this issue in my app.
Pls dont think it is silly, just simply change the position of "state_pressed" to top.
<item android:drawable="#drawable/list_item_bg_pressed" android:state_pressed="true"/>
<item android:drawable="#drawable/list_item_bg_normal" android:state_activated="false"/>
<item android:drawable="#drawable/list_item_bg_selected" android:state_activated="true"/>
In Future if anyone comes here using, Navigation Drawer Activity (provided by Studio in Activity Prompt window)
The answer is -
Use this before OnCreate() in MainActivity
int[][] state = new int[][] {
new int[] {android.R.attr.state_checked}, // checked
new int[] {-android.R.attr.state_checked}
};
int[] color = new int[] {
Color.rgb(255,46,84),
(Color.BLACK)
};
ColorStateList csl = new ColorStateList(state, color);
int[][] state2 = new int[][] {
new int[] {android.R.attr.state_checked}, // checked
new int[] {-android.R.attr.state_checked}
};
int[] color2 = new int[] {
Color.rgb(255,46,84),
(Color.GRAY)
};
ColorStateList csl2 = new ColorStateList(state2, color2);
and use this in onNavigationItemSelected() in MainActivity (you dont need to Write this function if you use Navigation Drawer activity, it will be added in MainActivity).
NavigationView nav = (NavigationView) findViewById(R.id.nav_view);
nav.setItemTextColor(csl);
nav.setItemIconTintList(csl2);
nav.setItemBackgroundResource(R.color.white);
Tip - add this code before If else Condition in onNavigationItemSelected()
This worked for me :
implemented menu drawer not by populating the navigation view with list, but with menu items.
created a drawable like this :
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#color/drawer_menu_selector_color" android:state_checked="true"></item>
<item android:drawable="#color/drawer_menu_selector_color" android:state_activated="true"></item>
and in onCreate method , set the id of the menu item which corresponds to selected activity as checked.
and implement the drawable selector file to your navigation drawer like this
app:itemBackground="#drawable/drawer_menu_selector"
fyi : need to define your 'app' namespace.
I searched for solution on this issue, tried everything, and only this solution worked for me.
You can find it on this link https://tuchangwei.github.io/2016/07/18/The-solution-that-the-menu-item-of-Navigation-View-can-t-change-its-background-When-it-is-selected-checked/
All the credit to https://tuchangwei.github.io/

Categories

Resources