问题
Is there a way to add a footer inside a spinner drop down list? For instance, say I am populating a spinner from a database, but I want a selection at the bottom of the list regardless of how I arrange the list. The list might be "Database Item 1, 2.., 3..." and at the bottom of the list a footer choice of "Add Item to Database."
So far I have used your CustomSpinner class as follows:
public class CustomSpinner extends Spinner implements OnItemClickListener {
private AlertDialog myDialog = null;
private OnClickListener myButtonClickListener = null;
private GrainSpinnerAdapter adapter = null;
public CustomSpinner(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setButtonClickListener(OnClickListener listener) {
myButtonClickListener = listener;
}
public void setAdapter(GrainSpinnerAdapter adapter){
this.adapter = adapter;
}
@Override
public boolean performClick() {
Context context = getContext();
//Inflate the layout
final LayoutInflater inflater = LayoutInflater.from(getContext());
final View v = inflater.inflate(R.layout.my_custom_spinner, null);
// set up list view
final ListView lv = (ListView) v.findViewById(R.id.list);
lv.setAdapter(adapter);
lv.setSelection(getSelectedItemPosition());
lv.setOnItemClickListener(this);
// set up button
final Button btn = (Button) v.findViewById(R.id.addButton);
btn.setOnClickListener(myButtonClickListener);
// build our dialog
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// show prompt, just as our Spinner parent does
if (getPrompt() != null) {
builder.setTitle(getPrompt());
}
// create and show dialog
myDialog = builder.setView(v).create();
myDialog.show();
return true;
}
@Override
public void onItemClick(AdapterView<?> view, View itemView, int position, long id) {
setSelection(position);
if (myDialog != null) {
myDialog.dismiss();
myDialog = null;
}
}
} I am wanting to use a separate adapter such as this:
public class GrainListAdapter extends SimpleCursorAdapter {
private static final String DEFAULT_UNITS = "American";
private Button upButton;
private Context myContext;
private RecipeGrainActivity parentActivity;
private Button downButton;
private String units;
private double getLbs;
public GrainListAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
myContext = context;
parentActivity = (RecipeGrainActivity) myContext;
//Checks for metric pref.
SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(context);
units = String.valueOf(myPrefs.getString(context.getString(R.string.pref_measurement), DEFAULT_UNITS));
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
int idColumn = cursor.getColumnIndex("_id");
final int getId = cursor.getInt(idColumn);
final double increment = 0.25;
UnitsConversions convert = new UnitsConversions();
int nameColumn = cursor.getColumnIndex("name");
String getName = cursor.getString(nameColumn);
TextView name = (TextView)view.findViewById(R.id.GrainName);
name.setText(getName);
int originColumn = cursor.getColumnIndex("origin");
String getOrigin = cursor.getString(originColumn);
TextView origin = (TextView)view.findViewById(R.id.GrainOrigin);
origin.setText(getOrigin);
if(units.equals("Metric")){
//Sets labels to metric.
String kilos = context.getResources().getString (R.string.kilograms);
TextView weightLabel = (TextView)view.findViewById(R.id.GrainLbsLabel);
weightLabel.setText(kilos);
}
}
@Override
public View newView(Context context, Cursor cursor, final ViewGroup parent) {
View view = View.inflate(context, R.layout.grain_list_item, null);
return view;
}
}
Which allows me to build a custom row for each listitem in the spinner. I was thinking I could set the adapter to the CustomSpinner using the customspinner.setadapter() within my activity. However, the ListView defined in the CustomSpinner class uses an adapter referenced within the class. How do I pass my adapter into the class so it can use it?
Here is how I had to add the custom item to my layout:
<com.bluelightuniverse.android.brewmobile.CustomSpinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/GrainNameSpinner"
android:layout_toRightOf="@id/GrainOriginSpinner"
android:layout_toLeftOf="@+id/AddGrainButton">
</com.bluelightuniverse.android.brewmobile.CustomSpinner>
回答1:
I've been experimenting with making more complex views in Spinners' dialogs.
To do what you've explained, I made a subclass of Spinner
. I examined the source of the Android Spinner and overrided the performClick
to do essentially what you want: populate your own dialog with a custom view.
package me.ribose.example; // you'll have to change this
import android.app.AlertDialog;
import android.content.Context;
import android.database.DataSetObserver;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
public class CustomSpinner extends Spinner implements OnItemClickListener {
private AlertDialog mDialog = null;
private OnClickListener mButtonClickListener = null;
public UnitSelectionSpinner(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setButtonClickListener(OnClickListener listener) {
mButtonClickListener = listener;
}
@Override
public boolean performClick() {
Context context = getContext();
// get the set adapter
final DropDownAdapter adapter = new DropDownAdapter(getAdapter());
// inflate our layout
final LayoutInflater inflater = LayoutInflater.from(getContext());
final View v = inflater.inflate(R.layout.customSpinner, null);
// set up list view
final ListView lv = (ListView) v.findViewById(R.id.list);
lv.setAdapter(adapter);
lv.setSelection(getSelectedItemPosition());
lv.setOnItemClickListener(this);
// set up button
final Button btn = (Button) v.findViewById(R.id.addButton);
btn.setOnClickListener(mButtonClickListener);
// build our dialog
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// show prompt, just as our Spinner parent does
if (getPrompt() != null) {
builder.setTitle(getPrompt());
}
// create and show dialog
mDialog = builder.setView(v).create();
mDialog.show();
return true;
}
@Override
public void onItemClick(AdapterView<?> view,
View itemView, int position, long id) {
setSelection(position);
if (mDialog != null) {
mDialog.dismiss();
mDialog = null;
}
}
/**
* <p>Wrapper class for an Adapter. Transforms the embedded Adapter instance
* into a ListAdapter.</p>
*/
private static class DropDownAdapter implements ListAdapter, SpinnerAdapter {
private SpinnerAdapter mAdapter;
/**
* <p>Creates a new ListAddapter wrapper for the specified adapter.</p>
*
* @param adapter the Adapter to transform into a ListAdapter
*/
public DropDownAdapter(SpinnerAdapter adapter) {
this.mAdapter = adapter;
}
public int getCount() {
return mAdapter == null ? 0 : mAdapter.getCount();
}
public Object getItem(int position) {
return mAdapter == null ? null : mAdapter.getItem(position);
}
public long getItemId(int position) {
return mAdapter == null ? -1 : mAdapter.getItemId(position);
}
public View getView(int position, View convertView, ViewGroup parent) {
return getDropDownView(position, convertView, parent);
}
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return mAdapter == null ? null :
mAdapter.getDropDownView(position, convertView, parent);
}
public boolean hasStableIds() {
return mAdapter != null && mAdapter.hasStableIds();
}
@Override
public void registerDataSetObserver(DataSetObserver observer) {
if (mAdapter != null) {
mAdapter.registerDataSetObserver(observer);
}
}
@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
if (mAdapter != null) {
mAdapter.unregisterDataSetObserver(observer);
}
}
/**
* <p>Always returns false.</p>
*
* @return false
*/
public boolean areAllItemsEnabled() {
return true;
}
/**
* <p>Always returns false.</p>
*
* @return false
*/
public boolean isEnabled(int position) {
return true;
}
public int getItemViewType(int position) {
return 0;
}
public int getViewTypeCount() {
return 1;
}
public boolean isEmpty() {
return getCount() == 0;
}
}
}
You'll need my customSpinner.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:layout_marginTop="5px"
android:cacheColorHint="@null"
android:background="@android:color/background_light"
android:divider="@android:drawable/divider_horizontal_bright"
android:scrollbars="vertical">
</ListView>
<Button
android:id="@+id/addButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Add to Database">
</Button>
</LinearLayout>
Of course, make that android:text
a string resource.
More words on this: Just make a CustomSpinner
in your activity's layout as you need it and call setButtonClickListener
(probably near where you set the adapter) to add a callback for your button, that perhaps prompts the user to add or whatever you need. And of course notifyDataSetChanged()
on your adapter after adding to the database. Everything that works on a Spinner should work exactly the same with this custom spinner.
Side note (UPDATED): You will have to make sure your adapter's list items have black text (ex: android:textColor="@android:color/primary_text_light_nodisable"
)! I changed the XML above so it doesn't require white background on items (which then makes item highlights not work).
Code notes: Since the people who made Android decided to not make an easy way to customize spinner dialogs (hard-coded use of AlertDialog.Builder
using setSingleChoiceItems()
as well as a private class to "convert" SpinnerAdapter
s to ListAdapter
s), I had to copy their entire inner class to get the desired effect. Also note they are bad documenters (see DropDownAdapter
.isEnabled
/areAllItemsEnabled
for the laugh of the day!).
回答2:
in your CursorAdapter , Override the methods getCount() and getDropDownView: By example , if you want to put a button at the end , you can do this:
new SimpleCursorAdapter(...) {
@Override
public int getCount() {
return super.getCount()+1;
}
@Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
View res=null;
if (position == getCount()-1) {
//better not try to reuse our view as it can be requested for the spinner or by the list with different kind of layouts.
View mButton= getActivity().getLayoutInflater().inflate(R.layout.create_activity_button, parent,false);
mButton.setOnClickListener(ObservationListFragment.this);
res= mButton;
} else if (convertView != null && android.R.id.button1 == convertView.getId() ){
// If the adapter is trying to recycle our footer view, we force the generation of a new view (check on the id of our custom view)
res= super.getDropDownView(position, null, parent);
} else {
res= super.getDropDownView(position, convertView, parent);
}
return res;
}
};
回答3:
What you might be able to do is use the MergeAdapter: this lets you create an adapter that takes in your database adapter and a static View (the button to add item to database) and set that as the Spinner view. I've used this for ListView
s but not for Spinner
s so it is uncertain if it will work but I think it will.
来源:https://stackoverflow.com/questions/7005265/android-spinner-footer