This question already has answers here:
How to customize a Spinner in Android
(6 answers)
Closed 5 years ago.
I'm trying to remove the default highlight effect for Spinner item's onClick. I have my own specific spinner background which have radius in its corners. When I applied the new background, it still has its default background under my custom background. I've tried styling like this:
<style name="ExternalPSpinnerTheme" parent="Widget.AppCompat.Spinner.DropDown">
<item name="android:listSelector">#color/transparent</item>
<item name="android:listChoiceBackgroundIndicator">#color/transparent</item>
<item name="android:listChoiceIndicatorSingle">#color/transparent</item>
<item name="android:selectableItemBackground">#color/transparent</item>
<item name="android:background">#drawable/spinner_sortfriend_background</item>
<item name="android:cacheColorHint">#android:color/transparent</item>
<item name="android:popupBackground">#drawable/spinner_sortfriend_background</item>
<item name="android:dropDownSelector">#color/transparent</item>
</style>
I've tried changing the parent to Widget.AppCompat.Spinner but it didn't work.. PopupBackground and background works tho.
The other question is questioning on how to hide dividers and add its own spinner custom implementation, mine is asking about how to remove the default onClick highlight effect on the background. How did I try to achieve it? This is how:
if (position > 0 &&
(position + 1) < mDataset.size()){
divider.setVisibility(View.VISIBLE);
convertView.setBackground(ContextCompat.getDrawable(context, R.drawable.spinner_dropdown_background_middle_white_to_migrey));
} else if (position == 0){
divider.setVisibility(View.VISIBLE);
convertView.setBackground(ContextCompat.getDrawable(context, R.drawable.spinner_dropdown_background_top_white_to_migrey));
} else if (position + 1 == mDataset.size()){
divider.setVisibility(View.GONE);
convertView.setBackground(ContextCompat.getDrawable(context, R.drawable.spinner_dropdown_background_bottom_white_to_migrey));
}
And I still didn't get the right answer, I even tried the solution in the other question. I just realized something tho, only the background on the first item overlaps with my custom background click effect, but the one at the end of the list doesn't get overlapped.. Weird..
Any solution?
Create custom Spinner Layout in your xml as follows
<RelativeLayout
android:id="#+id/relativeLayout_multiChoiceDropDown"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/drawable_border_profile">
<TextView
android:id="#+id/textView_multiChoiceDropDownText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_marginBottom="#dimen/margin_5dp"
android:layout_marginEnd="#dimen/margin_5dp"
android:layout_marginStart="#dimen/margin_5dp"
android:layout_marginTop="#dimen/margin_5dp"
android:layout_toStartOf="#+id/button_multiChoiceDropDownArrow"
android:padding="#dimen/margin_5dp"
android:text="Select Item"
android:textColor="#color/black"
android:textSize="#dimen/text_size_16"/>
<Button
android:id="#+id/button_multiChoiceDropDownArrow"
android:layout_width="#dimen/profile_multi_choice_width"
android:layout_height="#dimen/profile_multi_choice_height"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_margin="#dimen/margin_5dp"
android:background="#drawable/dropdownarrow"/>
</RelativeLayout>
drawable_border_profile.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#80FFFFFF"/>
<stroke
android:width="0.5dp"
android:color="#color/light_gray"/>
<padding
android:bottom="1dp"
android:left="1dp"
android:right="1dp"
android:top="1dp"/>
</shape>
Then Set OnClickListener on RelativeLayout. On that You can open Popup Window
LayoutInflater inflater = (LayoutInflater)parentActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.pop_up_window, null);
RelativeLayout layout1 = holder.relativeLayout_multiChoiceDropDown;
pw = new PopupWindow(layout, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
pw.setBackgroundDrawable(new BitmapDrawable());
pw.setTouchable(true);
pw.setOutsideTouchable(true);
pw.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
pw.setTouchInterceptor(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event)
{
if (event.getAction() == MotionEvent.ACTION_OUTSIDE)
{
pw.dismiss();
return true;
}
return false;
}
});
pw.setContentView(layout);
pw.showAsDropDown(layout1, -5, 0);
final ListView list = (ListView) layout.findViewById(R.id.dropDownList);
Adapter_DropDown adapter = new Adapter_DropDown(parentActivity, items);
list.setAdapter(adapter);
pop_up_window.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="#+id/PopUpView"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/qatool_basic_info_dropdown"
android:orientation="vertical">
<ListView
android:id="#+id/dropDownList"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#000"
android:dividerHeight="0.5dp">
</ListView>
You can use customArray Adapter
public class Adapter_Spinner extends ArrayAdapter
{
Context context;
List<Response_IdDesc> dataArray;
public Adapter_Spinner(Context context, int textViewResourceId, List<Response_IdDesc> dataArray)
{
super(context, textViewResourceId, dataArray);
this.dataArray = dataArray;
this.context = context;
}
#Override public Response_IdDesc getItem(int position)
{
return dataArray.get(position);
}
#Override public int getCount()
{
return dataArray.size();
}
#Override public int getPosition(Object item)
{
return dataArray.indexOf(item);
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
return getCustomView(position, convertView, parent);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.rowitem_spinner_profile, parent, false);
TextView label = (TextView) view.findViewById(R.id.textview_spinner);
label.setText(dataArray.get(position).DESC);
return view;
}
}
Then set your spinner adapter like this
Adapter_Spinner adapter_spinner = new Adapter_Spinner(parentActivity, R.layout.rowitem_spinner, list);
spinner.setAdapter(adapter_spinner);
Related
Okay I'm going absolutely nuts with this. I have a ListView in mode singleChoice, when I click on it I set it to selected. And I set the background to a drawable with a selector (and I tried many states that could correspond to a selected item). However when I select it the background doesn't change and I dont get why. I visited dozens of forums for this but couldn't get an answer. Here's my code:
The ListView in my activity:
<com.gaetanl.aspa.ui.component.ExtensibleListView
android:id="#+id/payment_billing_address_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/item_selectable"
android:choiceMode="singleChoice"></com.gaetanl.aspa.ui.component.ExtensibleListView>
Its class:
public class ExtensibleListView extends ListView {
public ExtensibleListView(Context context) {
this(context, null);
}
public ExtensibleListView(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.listViewStyle);
}
public ExtensibleListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(this, "item " + position + " selected = " + view.isSelected());
view.setSelected(true);
Log.d(this, "selected = " + view.isSelected());
}
});
}
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
The selector:
<?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/colorPrimary" />
<item
android:state_active="true"
android:drawable="#color/colorPrimary" />
<item
android:state_checked="true"
android:drawable="#color/colorPrimary" />
<item
android:state_selected="true"
android:drawable="#color/colorPrimary" />
<item
android:drawable="#android:color/transparent" />
</selector>
Method I:
In your list adapter,create getter and setter methods for position.Then in getView method, compare the position as in below:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item.xml, null);
holder = new ViewHolder(); holder.itemLayout(LinearLyout)convertView.findViewById(R.id.item_layout);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if(position==getPosition()){
holder.itemLayout.setBackgroundColor(ContextCompat.getColor(context,R.color.back_ground_color));
}else{
holder.itemLayout.setBackgroundColor(ContextCompat.getColor(context,R.color.background_unselect));
}
return convertView;
}
public void setPosition(int posit) {
this.position = posit;
}
private int getPosition() {
return this.position;
}
Then in the activity , inside listView's onItemSelected() method: call the adapter's setPositionMethod:
list_view.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
mAdapter.setPosition(i);
mAdapter.notifyDataSetChanged();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Just set the list selector to transparent ..that should do the job.
Method II:
Or may be ,You need a selector like below:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:drawable="#color/color_primary" >
</item>
<item
android:state_focused="true"
android:drawable="#color/color_primary" >
</item>
<item
android:state_selected="true"
android:drawablecolor="#color/color_primary" >
</item>
<item android:color="#color/#color/transparent" >
</item>
</selector>
then put list selector as #drawable/list_selector
But, if that doesn't work then I think you can set the background of item xml layout as
android:background="#drawable/list_selector"
Okay I found the answer. I was stupidly trying to set the ListView background (see code above). What I needed to do was, when creating adapter, to select a view for the items that incorporates variation for selected items. Android has one by default: simple_list_item_single_choice.
So here's the working code:
myListView = ((ListView) findViewById(R.id.listview_id));
ArrayAdapter<String> myAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_single_choice, myList);
myListView.setAdapter(myAdapter);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setSelected(true);
}
});
And then you have it, a list view with radio buttons on the right that check themselves when you click on em.
And here's the ListView in my layout.xml:
<ListView
android:id="#+id/listview_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:choiceMode="singleChoice">
</ListView>
I am new to android and I have just started programming a simple app to try different things out.
I was programming a ListView (and, in the same way a GridView) but there is something I got wrong. Each item is a couple of an image and a text field.
| img | __text__ |
I want to be able to choose any number of list items, keeping them enlightened for all the selection process, before passing the selected items to the next activity. If I want to
de-select one of them, I simply have to re-click on the item to have the selection disappear. For this purpose I use a custom selector so that when the item is pressed it changes colours.
If the items are all contained in a screen, everything is ok. But as soon as they grow in number and recycling kicks in, the enlightening of selected items which get out of the screen is lost. I have debugged the state of items and those whose enlightening is lost are still correctly selected, so I think it’s just a problem on how the graphic reloads when an item is restored after it went out of the device screen.
Here’s the code of the activity layout:
<!-- items_selection.xml -->
<?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="match_parent"
android:orientation="vertical"
android:background="#color/Background">
<ListView
android:id="#+id/item_list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#color/divider"
android:dividerHeight="3dp"
android:choiceMode="multipleChoice"
android:listSelector="#drawable/list_selector">
</ListView>
</LinearLayout>
This is the Row Item layout:
<!-- list_row.xml -->
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/list_selector"
android:orientation="horizontal"
android:padding="5dip" >
<LinearLayout
android:id="#+id/item_list_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip"
android:padding="3dip" >
<ImageView
android:id="#+id/item_image"
android:layout_width="#dimen/img_side"
android:layout_height="#dimen/img_side" />
</LinearLayout>
<TextView
android:id="#+id/item_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/item_list_item"
android:layout_centerVertical="true"
android:textColor="#color/black"
android:textSize="#dimen/textnorm"
/>
</RelativeLayout>
This is the selector I used:
<!-- list_selector.xml -->
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="false"
android:state_pressed="false"
android:drawable="#drawable/rect" />
<item
android:state_pressed="true"
android:drawable="#drawable/rect_sel" />
<item
android:state_selected="true"
android:state_pressed="false"
android:drawable="#drawable/rect_sel" />
</selector>
<!-- rect.xml -->
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#D5DDE0"
android:centerColor="#e7e7e8"
android:endColor="#CFCFCF"
android:angle="270" />
</shape>
<!-- rect_sel.xml -->
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#78DDFF"
android:centerColor="#16cedb"
android:endColor="#09adb9"
android:angle="270" />
</shape>
This is the code of the Activity:
public class ItemSelection extends AppCompatActivity {
private int numitems;
private ListView listview;
private ArrayList<Item> items = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.items_selection);
numitems = 15;
build_list();
listview = (ListView) findViewById(R.id.item_list);
listview.setAdapter(new ListAdapter(this, items));
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.next_btn, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch(id){
case R.id.next_btn:
Intent intent = new Intent (this, nextActivity.class);
intent.putStringArrayListExtra("items", Chosen_Items());
startActivity(intent);
return true;
default:
Toast.makeText(getApplicationContext(), "ERROR", Toast.LENGTH_SHORT).show();
return super.onOptionsItemSelected(item);
}
}
private void build_list() {
//Populates the item list with more items than the screen can support.
}
private ArrayList<String> Chosen_Items(){
ArrayList<String> selitems = new ArrayList<>();
for (int i=0; i<numitems; i++){
if (items.get(i).isSelected()){
selitems.add(items.get(i).getName());
}
}
return selitems;
}
This is the code of the listAdapter:
public class ListAdapter extends BaseAdapter {
private ArrayList <Item> items;
private Activity sActivity;
public ListAdapter(Activity sActivity, ArrayList<Item> items) {
this.sActivity = sActivity;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder;
if(view == null) {
LayoutInflater li = sActivity.getLayoutInflater();
view = li.inflate(R.layout.list_row, null);
holder = new ViewHolder();
holder.text = (TextView)view.findViewById(R.id.item_name);
holder.img = (ImageView)view.findViewById(R.id.item_image);
view.setTag(holder);
}
else {
holder = (ViewHolder)view.getTag();
}
holder.text.setText(items.get(position).getName());
holder.img.setImageResource(items.get(position).getImage());
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View viewitem) {
if (!viewitem.isSelected() && !items.get(position).isSelected()) {
viewitem.setSelected(true);
items.get(position).setSelected(true);
}
else {
viewitem.setSelected(false);
items.get(position).setSelected(false);
}
}
});
return view;
}
private static class ViewHolder{
public TextView text;
public ImageView img;
}
}
I have already tried to manually set the background color of the items re-entering the screen (by using
view.setBackgroundResource(R.drawable.rect_sel)
in the adapter, before the click handler) but the problem remains. Can anyone help me solving the problem?
~~~~~~~~~~~~~~~~~~~ SOLUTION ~~~~~~~~~~~~~~~~~~
It seems the selector doesn't follow the recycle of the items and their views.There has to be a better and more elegant solution taking advantage of a selector in this situation. But out of all the attempts i made, none has worked. This solution is the best workaround and does not use the selector.
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder;
if(view == null) {
LayoutInflater li = sActivity.getLayoutInflater();
view = li.inflate(R.layout.list_row, null);
holder = new ViewHolder();
holder.text = (TextView)view.findViewById(R.id.item_name);
holder.img = (ImageView)view.findViewById(R.id.item_image);
view.setTag(holder);
}
else {
holder = (ViewHolder)view.getTag();
}
holder.text.setText(items.get(position).getName());
holder.img.setImageResource(items.get(position).getImage());
if(items.get(position).isSelected()){
view.setBackgroundResource(R.drawable.rect_sel);
}else{
view.setBackgroundResource(R.drawable.rect);
}
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View viewitem) {
if (!viewitem.isSelected() && !items.get(position).isSelected()) {
viewitem.setBackgroundResource(R.drawable.rect_sel);
viewitem.setSelected(true);
items.get(position).setSelected(true);
}
else {
viewitem.setBackgroundResource(R.drawable.rect);
viewitem.setSelected(false);
items.get(position).setSelected(false);
}
}
});
return view;
}
private static class ViewHolder{
public TextView text;
public ImageView img;
}
While in the list_row.xml file, the following line can be just deleted:
android:background="#drawable/list_selector"
In your getView() method just add this test:
if (items.get(position).isSelected()){
view.setBackgroundResource(R.drawable.rect_sel);
} else {
view.setBackgroundResource(R.drawable.rect);
}
Or just view.setSelected(items.get(position).isSelected());. While you already have a selector for your list item.
You must define the current selection state of view inside getView method.
Add this line:
viewitem.setSelected(items.get(position).isSelected());
after viewholder has been created like:
holder.img.setImageResource(items.get(position).getImage());
viewitem.setSelected(items.get(position).isSelected());
I think you should set the id for your RelativeLayout then add it to ViewHolder
private static class ViewHolder{
public TextView text;
public ImageView img;
RelativeLayout rl;
}
After that you handle event when click RelativeLayout then change background for RelativeLayout
public View getView(...)
...
...
// you should update the state of relative layout first
if (items.get(position).isSelected()) {
holder.setBackgroundColor(Color.parseColor("#ffff00"));
}else{
holder.setBackgroundColor(Color.parseColor("#ff0000"));
}
holder.rl.setOnClickListener(new View.OnClickListener(){ //remmember it is rl.setOnClick... not view.setOnClick...
public void onClick(View v) {
if (!items.get(position).isSelected()) {
items.get(position).setSelected(true);
holder.setBackgroundColor(Color.parseColor("#ffff00"));
}else {
items.get(position).setSelected(false);
holder.setBackgroundColor(Color.parseColor("#ff0000"));
}
}
});
}
Suggestion
You should modify your row layout like this (I have removed LinearLayout but the new layout still good)
<!-- list_row.xml -->
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/list_selector"
android:orientation="horizontal"
android:padding="5dip" >
<ImageView
android:id="#+id/item_image"
android:layout_marginRight="5dip"
android:padding="3dip"
android:layout_alignParentLeft="true"
android:layout_width="#dimen/img_side"
android:layout_height="#dimen/img_side" />
<TextView
android:id="#+id/item_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/item_image"
android:layout_centerVertical="true"
android:textColor="#color/black"
android:textSize="#dimen/textnorm"
/>
</RelativeLayout>
Remember that your list row layout is more simple then your listview will scroll faster, smooth and prevent some annoying bug.
Hope this help
I am using a custom single choice listview. I want to call ItemOnClickListener programmatically. I am using android:listSelector="#47D149" property in my xml. I saw this post. performItemClick function is working but doesn't change the background of list item.
What should I do?
Any suggestions. Thanks!
SAMPLE
ListView
<ListView
android:id="#+id/navigation_menu_container"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_below="#id/rlBanner"
android:layout_gravity="start"
android:background="#color/nyc_black"
android:choiceMode="singleChoice"
android:divider="#color/border_black"
android:dividerHeight="#dimen/divider_height"
android:listSelector="#drawable/item_selector" >
drawables/item_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_activated="false" android:drawable="#drawable/item_normal"></item>
<item android:state_pressed="true" android:drawable="#drawable/item_pressed"></item>
<item android:state_activated="true" android:drawable="#drawable/item_pressed"></item>
</selector>
drawables/item_normal.xml
<?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"
/>
</shape>
drawables/item_pressed.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<solid
android:color="#color/red"
/>
</shape>
Try the above sample. :) tell me if it works
Ok. I have found the solution. :) #Shifar Shifz answer, dont use
android:listSelector="#drawable/item_selector"
Instead of it, add this drawable xml to your row.xml layout as background
android:background="#drawable/item_selector"
Maybe you could just take care of it in your adapter itself?
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
if (null == convertView) {
LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item, parent, false);
}
if(this.getItem(position).isChecked()){
convertView.setBackgroundResource(android.R.color.holo_blue_bright);
}else{
convertView.setBackgroundResource(android.R.color.white);
}
final View tempFinalView = convertView;
tempFinalView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (getItem(position).isChecked()) {
getItem(position).setChecked(false);
tempFinalView.setBackgroundResource(R.color.white);
} else {
getItem(position).setChecked(true);
tempFinalView.setBackgroundResource(R.color.pressed);
}
}
}
);
return convertView;
}
EDIT:
If you dont want to add another variable to the item.You could use the tag feature instead.
Just set and get the tag.
private static int VIEW_TAG=99;
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
if (null == convertView) {
LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item, parent, false);
}
if((Boolean)convertView.getTag(VIEW_TAG)){
convertView.setBackgroundResource(android.R.color.holo_blue_bright);
}else{
convertView.setBackgroundResource(android.R.color.white);
}
final View tempFinalView = convertView;
tempFinalView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (getItem(position).isChecked()) {
convertView.setTag(VIEW_TAG,new Boolean(false));
tempFinalView.setBackgroundResource(R.color.white);
} else {
convertView.setTag(VIEW_TAG,new Boolean(true));
tempFinalView.setBackgroundResource(R.color.pressed);
}
}
}
);
return convertView;
}
I have a spinner with several options, each displaying a simple string. Initially, the text is all white. However, if the user selects an option (causing it to become what is displayed on top), I would like that text to become red.
How can I do this?
EDIT : solved
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
((TextView) arg1).setTextColor(Color.parseColor("#E3170D"));
}
if the user selects an option (causing it to become what is displayed
on top), I would like that text to become red.
So you most likely created OnItemSelectedListener() for your Spinner. So in onItemSelected() method you can simply change text color.
Pseudocode:
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
TextView selectedText = (TextView) parent.getChildAt(0);
if (selectedText != null) {
selectedText.setTextColor(Color.RED);
}
}
Hope it helps.
see this answer here and i will copy and paste it
Create custom View layout (e.g. from TextView)
Create Selector and set it as a background of that view
Set Spinner with custom view
Selector: custom_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true"
android:state_pressed="false"
android:drawable="#color/light_grey" />
<item android:state_focused="true"
android:state_pressed="true"
android:drawable="#color/light_grey" />
<item android:state_focused="false"
android:state_pressed="true"
android:drawable="#color/light_grey" />
<item android:state_selected="true" android:drawable="#color/light_grey"/>
<item android:drawable="#color/white" />
</selector>
Custom View layout: my_simple_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:lines="1"
android:padding="5dip"
android:background="#drawable/custom_selector"/>
Initialise Spinner:
String[] items = new String[] {"One", "Two", "Three"};
Spinner spinner = (Spinner) findViewById(R.id.mySpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.my_simple_item, items);
Hope this helps
some of you that using MaterialBetterSpinner and Binding your Layouts,
all the above won't help, try this, hope it helps you:
public class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, int textViewResourceId, List<String> objects) {
super(context, textViewResourceId, objects);
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final YourXMLBinding rowBinding = DataBindingUtil.inflate(inflater, R.layout.yourXML, parent,false);
rowBinding.tv1.setText(mMy.getValues().get(position));
if(position == mMy.getCurrentIndex()) {
rowBinding.tv1.setTypeface(Typer.set(getContext()).getFont(Font.ROBOTO_BOLD));//change font
rowBinding.tv1.setTextColor(ContextCompat.getColor(getContext(), R.color.yourColor));//change color
}
return rowBinding.getRoot();
}
}
yourXML is something like this:
<?xml version="1.0" encoding="utf-8"?>
<layout>
<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="#color/colorBackgroundStart">
<TextView
android:id="#+id/tv1"
android:layout_width="0dp"
android:layout_weight="0.7"
android:layout_height="30dp"
android:textColor="#fff"
android:textSize="16dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="8dp"/>
</layout>
create a spinner with this adapter and yourXML :
final MyAdapter adapter = new MyAdapter(getContext(), R.layout.yourXML, s.getValues());
final MaterialBetterSpinner spinner = new MaterialBetterSpinner(getContext());
spinner.setAdapter(adapter);
use this to change the text of selected Text
YOUR_SPINNER.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
TextView selectedText= view.findViewById(R.id.text_view_name_in_Adapter);
selectedText.setTextColor(getResources().getColor(R.color.YOUR_COLOR));
}
}
create 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/red" />
<item android:drawable="#android:color/transparent" />
</selector>
and in your activity xml:
<Spinner...............
android:drawSelectorOnTop="true"
android:background="#drawable/sample"/>
Just add the OnItemSelectedListener to your spinner.
qtySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
((TextView) view).setTextColor(Color.BLACK); //Change selected text color
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
I'm creating a Spinner dynamically like the code below:
private void createCoordinationSpinner() {
TextView tvwCoordination = new TextView(this);
this.spinnerCoordination = new Spinner(this);
//Some code to setup textview...
LinearLayout.LayoutParams paramsSpinnerCoordination = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
paramsSpinnerCoordination.setMargins(10, 0, 10, 0);
this.spinnerCoordination.setLayoutParams(paramsSpinnerCoordination);
this.spinnerCoordination.setBackgroundResource(R.drawable.rounded_border);
this.spinnerCoordination.setPrompt("Coordination");
this.spinnerCoordination.setOnItemSelectedListener(spinnerItemClickListener);
//Adding both views to an existing LinearLayout, that is possible to have another views, instead of spinner
linearSchoolCoordination.addView(tvwCoordination, 0);
linearSchoolCoordination.addView(spinnerCoordination, 1);
linearSchoolCoordination.setGravity(Gravity.BOTTOM);
}
//Thats the line that sets the adapter:
adapterCoordination = new ItemSpinnerAdapter(context, R.layout.coordinationspinnerlayout, arrayCoordination);
rounded_border.xml:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#color/gray_dialog" />
<padding android:left="8dp"
android:top="8dp"
android:right="8dp"
android:bottom="8dp" />
<corners android:radius="20dp" />
</shape>
coordinationspinnerlayout.xml:
<LinearLayout android:orientation="vertical"
android:background="#color/transparent2"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/transparent2"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/transparent2"
android:gravity="center_vertical" >
<ImageView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/imageSpinnerItem"
android:src="#drawable/itemlistviewicon_nochildren"
android:layout_marginTop="5dp"
android:layout_marginLeft="8dp"
android:layout_marginBottom="5dp"/>
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/tvwSpinnerCoordination"
android:layout_marginLeft="10dp"
android:textSize="16dip"
android:textColor="#color/black"
android:text="TextView"
android:layout_weight="1"/>
<ImageView android:layout_height="20dp"
android:layout_width="20dp"
android:id="#+id/imageSpinnerDownArrow"
android:src="#drawable/spinnerdownarrow"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:layout_marginRight="10dp"/>
</LinearLayout>
<View android:background="#color/silver"
android:layout_height="1dp"
android:layout_width="fill_parent"
android:id="#+id/linearSpinnerSeparator"/>
</LinearLayout>
</LinearLayout>
And finally, the adapter, ItemSpinnerAdapter.java:
public class ItemSpinnerAdapter extends ArrayAdapter<CoordinationData>
{
private int tvwID;
private List<CoordinationData> coordinationList;
public ItemSpinnerAdapter(Context context, int textViewResourceId, List<CoordinationData> coordinationList)
{
super(context, textViewResourceId, coordinationList);
this.tvwID = textViewResourceId;
this.coordinationList = coordinationList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
View view = convertView;
if (view == null)
{
LayoutInflater layInf = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layInf.inflate(tvwID, null);
holder = new ViewHolder();
holder.tvwDescription = (TextView) view.findViewById(R.id.tvwSpinnerCoordination);
holder.description = coordinationList.get(position).getCoordinationName();
view.findViewById(R.id.linearSpinnerSeparator).setVisibility(View.GONE);
view.setTag(holder);
}
else
{
holder = (ViewHolder) view.getTag();
holder.description = coordinationList.get(position).getCoordinationName();
}
if (holder.tvwDescription != null)
holder.tvwDescription.setText(holder.description);
return view;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
View view = convertView;
if (view == null)
{
LayoutInflater layInf = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layInf.inflate(tvwID, null);
holder = new ViewHolder();
holder.tvwDescription = (TextView) view.findViewById(R.id.tvwSpinnerCoordination);
holder.tvwDescription.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
holder.description = coordinationList.get(position).getCoordinationName();
view.findViewById(R.id.imageSpinnerDownArrow).setVisibility(View.GONE);
view.setTag(holder);
}
else
{
holder = (ViewHolder) view.getTag();
holder.description = coordinationList.get(position).getCoordinationName();
}
if (holder.tvwDescription != null)
holder.tvwDescription.setText(holder.description);
return view;
}
public class ViewHolder
{
TextView tvwDescription;
String description;
}
}
adding it to a LinearLayout that already exists in my activity's XML layout file.
Along with my CustomSpinnerAdapter, it works pretty well.
But I still need to change some properties and I'm stucked...
Since my app is using blue texts and backgrounds, I'd like to set the selection of a spinner item highlight color. Its default is orange.
Since I'm developing for API 10, I'm using limited Spinner methods.
Any suggestions?
Thanks in advance!
EDIT: is that possible to change prompt header background color?
EDIT2: adding further code.
EDIT:
You're using a spinner, so you need to implement [getDropDownView][1].
If you want to change the selected color of your View you need to create a Color List Drawable like so
In Colors/list_color.xml
<selector>
<item android:state_selected="true">SomeColor</item>
</selector>
in your view
<YourView
android:background="#color/list_color" />
See this resource for more info
take the custum adapter
mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View arg1,
int position, long arg3) {
_position = position;
LinearLayout linear_ayout = (LinearLayout)parent.getChildAt(0);
linear_ayout.setBackgroundColor(Color.TRANSPARENT);
TextView tv = (TextView) linear_ayout.getChildAt(0);
tv.setTextColor(Color.WHITE);
gname_spinner=mySpinner.getSelectedItem().toString();
if (mySpinner.getSelectedItem().toString().equalsIgnoreCase("All Groups"))
filItemAdapter("A", "");
else
filItemAdapter("G", mySpinner.getSelectedItem().toString());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Logger.d("******", "not selected");
filItemAdapter("A", "");
}
});
MyCustomAdapter custom_adapter = new MyCustomAdapter(
getApplicationContext(), R.layout.custum_spinner_group,
group_list);
mySpinner.setAdapter(custom_adapter);
public class MyCustomAdapter extends ArrayAdapter<String> {
List<String> group_list;
public MyCustomAdapter(Context context, int textViewResourceId,
List<String> group_list) {
super(context, textViewResourceId, group_list);
this.group_list = group_list;
}
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView,
ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.custum_spinner_group, parent, false);
TextView text_group = (TextView) row.findViewById(R.id.text_group_name);
LinearLayout layout = (LinearLayout) row
.findViewById(R.id.layout_group_name);
text_group.setText(group_list.get(position));
if (position == _position) {
layout.setBackgroundColor(getResources().getColor(R.color.spinner_background));
text_group.setTextColor(getResources().getColor(R.color.white));
} else {
layout.setBackgroundColor(Color.TRANSPARENT);
text_group.setTextColor(getResources().getColor(R.color.spinner_background));
}
Log.d("selected group", ":"+text_group.getText());
return row;
}
}
After long time searching for a solution,
I found out that I can't set style or change its selection color dynamically 'cause of the API version that I'm developing.