Spinner (dropdown)item same size as Spinner - android

can i make the size of my item and especially the dropdownitems the same size as the spinner? They are a little bit smaller at the moment. i want them to fill the whole Spinner.
Can anyone help me?
edit:
it looks like this:
http://image-upload.de/image/vjYswg/cbc92fd3e9.jpg
and i want this:
http://image-upload.de/image/JdVZ5z/1f73d79751.jpg
oh and i have to use API 14, so i can't set dropdownwidth
i have set the dropdownviewresource to the following xml:
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape = "rectangle">
<solid
android:color="#666666" />
<corners
android:radius="3dp" />
</shape>
edit: sry, this was my spinner layout, for dropdown_items i use
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="43dp"
android:orientation="horizontal" >
<ImageView
android:layout_height="30dp"
android:layout_width="30dp"
android:layout_marginRight="5dp"
android:layout_gravity="center_vertical"
android:contentDescription="#layout/spinner_item"
android:src="#drawable/circledsync" />
<de.util.FontDropDownTextView
android:id = "#+id/spinner_dropdown_item_textView"
style="?android:attr/spinnerDropDownItemStyle"
android:singleLine="true"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="0.90"
android:gravity="center_vertical"
android:textColor="#color/spinner_text" />
</LinearLayout>
i also use a custom array adapter:
public class MyArrayAdapter extends ArrayAdapter<String> {
private int myTextId = 0;
private int myDropDownResource;
private int myDropDownTextId;
private int myResource;
private LayoutInflater myInflater;
public MyArrayAdapter(Context context, int textViewResourceId, List<String> names) {
super(context, textViewResourceId, names);
myTextId = myDropDownTextId = textViewResourceId;// remember it, so we can find the real TextView
myInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public MyArrayAdapter(Context context, int layoutId, int textViewResourceId, List<String> names) {
super(context, layoutId, textViewResourceId, names);
myTextId = myDropDownTextId = textViewResourceId;// remember it, so we can find the real TextView
myResource = myDropDownResource = layoutId;
myInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setDropDownViewResource(int resource) {
super.setDropDownViewResource(resource);
myDropDownResource = resource;
}
public void setDropDownViewResource(int resource, int textId) {
super.setDropDownViewResource(resource);
myDropDownResource = resource;
myDropDownTextId = textId;
}
public View getView(int position, View convertView, ViewGroup parent) {
View cell = MyGetView(position, convertView, parent, myResource, myTextId);
setFontForChild(cell);
return cell;
}
public View getDropDownView(int position, View convertView, ViewGroup parent) {
View cell = MyGetView(position, convertView, parent, myDropDownResource, myDropDownTextId);
setFontForChild(cell);
return cell;
}
private void setFontForChild(View layoutCell)
{
View realTextView = layoutCell.findViewById(myTextId);
if(realTextView instanceof TextView)
{
Typeface tf = Typeface.createFromAsset(
getContext().getAssets(),"fonts/calibri.otf");
((TextView)realTextView).setTypeface(tf);
}
//else realTextView is null or is not a TextView.
}
private View MyGetView(int position, View convertView, ViewGroup parent,
int resource, int fieldId) {
View view;
TextView text;
if (convertView == null) {
int res = (resource==0)? fieldId : resource;
view = myInflater.inflate(res, parent, false);
} else {
view = convertView;
}
try {
if (fieldId == 0) {
// If no custom field is assigned, assume the whole resource is a TextView
text = (TextView) view;
} else {
// Otherwise, find the TextView field within the layout
text = (TextView) view.findViewById(fieldId);
}
} catch (ClassCastException e) {
Log.e("ArrayAdapter", "You must supply a resource ID for a TextView");
throw new IllegalStateException(
"ArrayAdapter requires the resource ID to be a TextView", e);
}
String item = getItem(position);
if (item instanceof CharSequence) {
text.setText((CharSequence)item);
} else {
text.setText(item);
}
return view;
}

I got same problem. I changed style of my Spinner:
<item name="android:paddingLeft">0dp</item>
<item name="android:paddingRight">0dp</item>
It resolved my problem.

Try this in java code:
spinner.setPopupBackgroundResource(R.drawable.spinner_style);
And in your spinner_style.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="#ffffff" />
</shape>

Add a call like this:
Spinner spinner = (Spinner)findViewById(...);
spinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

Try this in xml file:-
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textSize="14pt"
Use size as per your requirement.

Try with custom Spinner it will solve your problem.
Sample:
Initiate:
spinner.setAdapter(new MyCustomAdapter(AssessmentActivity.this,
R.layout.spinner_test, spinnerData));
In your custom adapter:
public class MyCustomAdapter extends ArrayAdapter<String>{
List<String>draft_filter_array_ = new ArrayList<String>();
public MyCustomAdapter(Context context, int textViewResourceId,
List<String> draft_filter_array) {
super(context, textViewResourceId, draft_filter_array);
draft_filter_array_ = draft_filter_array;
}
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
return getCustomView(position, convertView, parent);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
//return super.getView(position, convertView, parent);
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.spinner_test, parent, false);
TextView label=(TextView)row.findViewById(R.id.weekofday);
label.setText(draft_filter_array_.get(position));
return row;
}
}
And in your spinner_test.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" >
<TextView
android:id="#+id/weekofday"
android:layout_width="match_parent"
android:layout_height="42dp"
android:layout_gravity="center"
android:gravity="center"
android:text="Sunday"
android:textColor="#000000"
android:textSize="18sp"
/>
</LinearLayout>

Related

Spinner setOnItemSelectedListener not working with custom adapter

I have made a custom spinner to populate a list of image and text that comes from mysql DB
when I tried to select an item from the spinner it doesn't work, even when I debug and put a break point inside the listener it doesn't go in.
My Adapter:
public class SpinnerShopAdapter extends ArrayAdapter<supermarketspinnerGS> {
private Context mcontext;
ArrayList<supermarketspinnerGS> SavedListContent;
public SpinnerShopAdapter(Context context, ArrayList<supermarketspinnerGS> SavedListContent) {
super(context, 0, SavedListContent);
this.mcontext = context;
this.SavedListContent = SavedListContent;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
return initView(position, convertView, parent);
}
#Override
public View getDropDownView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
return initView(position, convertView, parent);
}
private View initView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.spinner_supermarket_row, parent, false
);
}
ImageView imvSupermaket = convertView.findViewById(R.id.spinner_supermarket_imageView);
TextView tvSupamrketname = convertView.findViewById(R.id.spinner_supermarket_name);
TextView tvIdShop = convertView.findViewById(R.id.spinner_supermarket_idshop);
supermarketspinnerGS currentItem = getItem(position);
if (currentItem != null) {
Glide.with(context).load(currentItem.getImage()).into(imvSupermaket);
tvSupamrketname.setText(currentItem.getName());
tvIdShop.setText(currentItem.getIdshop());
}
return convertView;
}
}
onCreate code:
spinnerStore = (Spinner) findViewById(R.id.saveditemlist_spinner_storeshead);
adapterHead = new SpinnerShopAdapter(ActivitySavedListItem.this, getListHeadArray);
spinnerStore.setAdapter(adapterHead);
spinnerStore.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
supermarketspinnerGS clickedItem = (supermarketspinnerGS) parent.getItemAtPosition(position);
String clickedshopName = clickedItem.getIdshop();
selectedItemText=getListHeadArray.get(spinnerStore.getSelectedItemPosition()).getIdshop();
Toast.makeText(ActivitySavedListItem.this, clickedshopName + " selected", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
I really don't know what is wrong and looking forward for your help. If you need more details please feel free to ask me I'll be glad to update my post
EDIT :
XML SPINNER
<LinearLayout
android:layout_width="200dp"
android:layout_height="30dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:background="#drawable/spinner_market_shape"
app:layout_constraintStart_toEndOf="#+id/textView13"
app:layout_constraintTop_toBottomOf="#+id/textView10">
<Spinner
android:id="#+id/saveditemlist_spinner_storeshead"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="15dp"
android:paddingRight="15dp" />
</LinearLayout>
spinner_supermarket_row.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/spinner_supermarket_imageView"
android:layout_width="75dp"
android:layout_height="25dp"
android:layout_marginStart="4dp"
android:layout_marginTop="2dp"
android:layout_marginBottom="2dp"
android:clickable="false"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/spinner_supermarket_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:visibility="invisible"
/>
<TextView
android:id="#+id/spinner_supermarket_idshop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:visibility="invisible"
/>
</RelativeLayout >
try to to add clickable=false to all your elements on your xml spinner row
Iam not sure but
I think you must set your spinner item click listener in your spinner custom adapter in initView function
like this:
private View initView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.spinner_supermarket_row, parent, false
);
}
ImageView imvSupermaket = convertView.findViewById(R.id.spinner_supermarket_imageView);
TextView tvSupamrketname = convertView.findViewById(R.id.spinner_supermarket_name);
TextView tvIdShop = convertView.findViewById(R.id.spinner_supermarket_idshop);
supermarketspinnerGS currentItem = getItem(position);
if (currentItem != null) {
Glide.with(context).load(currentItem.getImage()).into(imvSupermaket);
tvSupamrketname.setText(currentItem.getName());
tvIdShop.setText(currentItem.getIdshop());
}
parent.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(position==CUSTOM_POSITION){ /*do something*/}
}
});
return convertView;
}
I hope it works

Styling item Views in Android ListView

I can not figure out what going wrong with my ListView, because it is too small. I want bigger items like default list views on Android.
SelectContactActivity
public class SelectContactActivity extends Activity {
private ArrayList<Contact> listContacts = new ArrayList<Contact>();
private ArrayList<SongInfo> listSong = new ArrayList<SongInfo>();
private ListContactsAdapter adapter;
private Util util = new Util();
private ListView list;
private EditText txt_search;
private ArrayList<Contact> listSearch;
private Handler guiThread;
private Runnable updateTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.setContentView(R.layout.mycontacts);
list = (ListView)findViewById(R.id.list);
txt_search = (EditText)findViewById(R.id.txt_search);
final int position = this.getIntent().getIntExtra("position", 0);
listSong = util.getAllSong(this);
listContacts = util.getAllContact(this);
Log.i("LOG", "Size: " + listContacts.size());
adapter = new ListContactsAdapter(this, android.R.layout.simple_list_item_1, listContacts);
list.setAdapter(adapter);
list.setTextFilterEnabled(true);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
util.assignRingtoneToContact(SelectContactActivity.this,
listSong.get(position), listContacts.get(arg2));
Toast.makeText(
SelectContactActivity.this,
"Ringtone set successfully",
Toast.LENGTH_LONG).show();
finish();
}
});
innitThread();
txt_search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
queueUpdate(500);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private void queueUpdate(long delayMillisecond) {
guiThread.removeCallbacks(updateTask);
// update data if no change in textSearch after time config
// timer by = milliseconds
guiThread.postDelayed(updateTask, delayMillisecond);
}
private void innitThread() {
guiThread = new Handler();
updateTask = new Runnable() {
#Override
public void run() {
String word = txt_search.getText().toString().trim();
if (word.equalsIgnoreCase("")) {
// if not change set listView first
list.setAdapter(new ListContactsAdapter(SelectContactActivity.this,
android.R.layout.simple_list_item_1, listContacts));
} else
// if txtSearch not null
{
// get data from webservice
getDataByKeywords(word);
// Show on list
listSearch = new ArrayList<Contact>();
// get data from webservice
listSearch = getDataByKeywords(word);
list.setAdapter(new ListContactsAdapter(SelectContactActivity.this, android.R.layout.simple_list_item_1, listSearch));
adapter.notifyDataSetChanged();
}
}
};
}
public ArrayList<Contact> getDataByKeywords(String keyword) {
listSearch = new ArrayList<Contact>();
keyword = keyword.toUpperCase();
for (int i = 0; i < listContacts.size(); i++) {
String contain = listContacts.get(i).getName().toUpperCase();
if (contain.contains(keyword)) {
listSearch.add(listContacts.get(i));
}
}
return listSearch;
}
}
ListContactsAdapter
public class ListContactsAdapter extends ArrayAdapter<Contact>{
private ArrayList<Contact> contacts;
private Context context;
public ListContactsAdapter(Context context, int textViewResourceId,
ArrayList<Contact> objects) {
super(context, textViewResourceId, objects);
this.context = context;
this.contacts = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if(convertView!=null){
convertView.setBackgroundResource(R.drawable.list_selector);
}
TextView textView = getGenericView();
textView.setBackgroundResource(R.drawable.list_selector);
textView.setText(contacts.get(position).getName());
return textView;
}
public TextView getGenericView() {
// Layout parameters for the ExpandableListView
AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT, 70);
TextView textView = new TextView(context);
textView.setLayoutParams(lp);
// Center the text vertically
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
// Set the text starting position
textView.setPadding(16, 0, 0, 0);
textView.setTextSize(18);
textView.setShadowLayer(1, 1, 1, Color.BLACK);
textView.setTextColor(0xffeeeeee);
return textView;
}
}
mycontacts.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="fill_parent" >
<RelativeLayout
android:id="#id/relativeLayoutSearch"
android:layout_width="fill_parent"
android:layout_height="55dp"
android:gravity="center_vertical"
android:paddingLeft="12dp"
android:paddingRight="12dp" >
<EditText
android:id="#id/txt_search"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:background="#drawable/search_bar"
android:hint="#string/hint_apps_search"
android:paddingBottom="12dp"
android:paddingLeft="45.0dip"
android:paddingRight="14dp"
android:paddingTop="12dp"
android:singleLine="true"
android:textSize="15.0sp" />
<Button
android:id="#id/button2"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#drawable/zoomicon" />
</RelativeLayout>
<ListView
android:id="#id/list"
style="#style/ContactList"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#id/relativeLayoutSearch"
android:cacheColorHint="#e0000000" />
</RelativeLayout>
styles.xml
<style name="ContactList">
<!-- <item name="android:background">#color/listbg</item> -->
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">fill_parent</item>
<item name="android:cacheColorHint">#e0000000</item>
<item name="android:divider">#color/listdiv</item>
<item name="android:dividerHeight">1.0dip</item>
</style>
This is my code for contact list, and here is a screenshot how this looks, but I want bigger items on list. Any suggestions?
Current listview:
I would start smaller, by revisiting your adapter. The ListView itself is very simple - in your activity layout, you set your ListView to be match_parent for both width and height.
The adapter is the component which creates each row, which in ListAdapter, is initiated by the getView() method.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView != null) {
convertView.setBackgroundResource(R.drawable.list_selector);
}
TextView textView = getGenericView();
textView.setBackgroundResource(R.drawable.list_selector);
textView.setText(contacts.get(position).getName());
return textView;
}
Note what you're doing here is incorrect; you do something to convertView but then you ignore it, and just make a new View. The pattern is more like:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
rowView = // create a new View that represents your row
}
// bind the data to rowView, then return it
return rowView;
}
which in your case might be:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView rowView = (TextView) convertView;
if (rowView == null) {
rowView = getGenericView();
rowView.setBackgroundResource(R.drawable.list_selector);
}
rowView.setText(contacts.get(position).getName());
return rowView;
}
See, you only need to create rowView if it's null. Also, the background only needs to be set once (and this can be done in XML if you want).
With creating the row View, I'd recommend starting by inflating a layout that contains a single TextView as the only element.
view_item_contact.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" />
then your getGenericView() can be renamed to createContactRowView():
private TextView createContactRowView(ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
return ((TextView) layoutInflater.inflate(R.layout.view_item_contact, parent, false));
}
From there, you can start to style your row in view_item_contact.xml by adding padding, setting a minimum height, centering the text vertically by applying gravity, etc.
view_item_contact.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:minHeight="48dp"
android:gravity="center_vertical"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:background="#drawable/list_selector" />
In almost all cases, I would avoid creating Views programmatically - always inflate them from XML, so you can separate styles and layout from your logic.

Change background before creating adapter

I am creating an arrayadapter with this line:
adapter=new ArrayAdapter<String>(getActivity(),R.layout.message_bar,strArr);
And this is my message_bar.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="6dp"
android:layout_marginRight="6dp"
android:layout_marginLeft="4dp"
android:paddingTop="10dp"
android:paddingLeft="15dp"
android:paddingRight="5dp"
android:gravity="left"
android:layout_gravity="left"
android:text="dfgdfgdf"
android:textSize="12dp"
android:background="#drawable/mes4" />
Can I change this xml's background and gravity before creating adapter with java ?
You have to use a custom adapter.
class Myadapter extends ArrayAdapter<String>{
LayoutInflater inflater=null;
public Myadapter(Context context, int resource, int textViewResourceId,
List<String> objects) {
super(context, resource, textViewResourceId, objects);
inflater = (LayoutInflater)getLayoutInflater();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
if(convertView==null)
row= inflater.inflate(R.layout.custom_list_item, null);
// CHANGE COLOR HERE
((TextView)row.findViewById(R.id.txtTitle)).setBackground( Color.Red );
return row;
}
}
or override getview:
new ArrayAdapter<String>(getActivity(),R.layout.message_bar,strArr)
{
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
if(convertView==null)
{
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row =vi.inflate(R.layout.message_bar, null);
}
TextView txt= (TextView)row.findViewById(R.id.message);
//CHANGE COLOR HERE
return row;
}
};

Custom ArrayAdapter for a Spinner: drop down view not working properly

I created a custom ArrayAdapter for a Spinner. The difference is, that it shows images from an ArrayList of a complex class instead of plain text. It works so far. The Images and the radio buttons are displayed as desired. The problem is, that the drop down view doesn't behave correctly: it doesn't close on a click and only the radio buttons are clickable instead of the whole view.
Does anybody has an idea what's wrong? Do I have to implement some kind of listener in the adapter??
Here's the code of the getDropDownView method:
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
LayoutInflater inflater=(LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout view=(LinearLayout)inflater.inflate(R.layout.spinnerimageitem, null);
ImageView iv=(ImageView)view.getChildAt(0);
RadioButton rb=(RadioButton)view.getChildAt(1);
int iImageID=ctx.getResources().getIdentifier(
"f_"+funcs.get(position).getBitmapSetup(),
"drawable", ctx.getPackageName());
if(loco.getFunction(iIndex).equals(funcs.get(position)))
rb.setChecked(true);
iv.setImageResource(iImageID);
return(view);
}
set android:focusable="false" in your layout for Radio button.
I had the same issue. For those who will get this problem later, I found one of solution.
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner)findViewById(R.id.spinner);
ArrayList<String> items = new ArrayList<String>();
for (int i=1; i<6; i++) items.add("Spinner item "+i);
spinner.setAdapter(new SpinnerAdapter(this,R.layout.spinner_item_list,items));
}
public class SpinnerAdapter extends ArrayAdapter<String> {
private ArrayList<Boolean> mChecked;
private ArrayList<String> mValues;
private Context mContext;
public SpinnerAdapter(Context context, int resourceId, ArrayList<String> values) {
super(context, resourceId, values);
mValues = values;
mContext = context;
mChecked = new ArrayList<Boolean>();
for (int i=0; i<mValues.size(); i++){
mChecked.add(false);
}
}
#Override
public View getDropDownView(int position, View convertView,ViewGroup parent) {
View row= View.inflate(mContext,R.layout.spinner_item_list, null);
TextView label=(TextView)row.findViewById(R.id.textView);
label.setText(mValues.get(position));
RadioButton rb = (RadioButton)row.findViewById(R.id.radioButton);
rb.setFocusable(false);
rb.setClickable(false);
rb.setChecked(mChecked.get(position));
return row;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = View.inflate(mContext,R.layout.spinner_item_top, null);
TextView label=(TextView)row.findViewById(R.id.textView);
label.setText(mValues.get(position));
for(int i=0; i<mChecked.size(); i++){
mChecked.set(i,(i==position));
}
return row;
}
}
}
spinner_item_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView" android:layout_centerVertical="true"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/radioButton" android:layout_alignParentRight="true" android:checked="false"/>
</RelativeLayout>
spinner_item_top.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
xmlns:android="http://schemas.android.com/apk/res/android" android:id="#+id/textView"></TextView>
have you tried like this:
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
View view = convertView;
if(view == null){
LayoutInflater inflater=(LayoutInflater)
tx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view=(LinearLayout)inflater.inflate(R.layout.spinnerimageitem, null);
}
/// your code ....
return view;
}

Android Spinner created dynamically change selected item background color

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.

Categories

Resources