Select spinner without triggering listener - android

Long version I have two spinners on my screen and when I select the one, I do certain operations, and the other spinner should display the original selection, because of design patterns. In this situation, I let the user select the elements on a list by year, and by state. You would agree with me that when the user choose to select by year, the spinner regarding the state should display the default selection (the one that displays all of the item) and not the last selected one.
I am trying to do this from this morning, but when I found this solution I really though I was done.
Short version I want to setSelection(0) on the spinner which is not clicked, without triggering its listener (which by the way, will setSelection(0) on the first spinner, if triggered)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
// irrelevant code...
mYearSpinner.setOnItemSelectedListener(onYearSelected);
mStateSpinner.setOnItemSelectedListener(onStateSelected);
// irrelevant code...
}
private AdapterView.OnItemSelectedListener onYearSelected = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mStateSpinner.setOnItemSelectedListener(null);
mStateSpinner.setSelection(0);
mStateSpinner.setOnItemSelectedListener(onStateSelected);
// Do something...
}
#Override
public void onNothingSelected(AdapterView<?> parent) { }
};
private AdapterView.OnItemSelectedListener onStateSelected = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mYearSpinner.setOnItemSelectedListener(null);
mYearSpinner.setSelection(0);
mYearSpinner.setOnItemSelectedListener(onYearSelected);
// Do something...
}
#Override
public void onNothingSelected(AdapterView<?> parent) { }
};
But no! The listeners will just fire, indiscriminately.
Is there someone who knows how to handle this problem?
Why this solution wouldn't work?
As requested, here is the full code of my onCreateView(...) method
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
Log.d(TAG, "onCreateView");
View view = inflater.inflate(R.layout.fragment_career, container, false);
mExamListView = (ListView) view.findViewById(R.id.exam_list_view);
mYearSpinner = (Spinner) view.findViewById(R.id.select_by_year_spinner);
mStateSpinner = (Spinner) view.findViewById(R.id.select_by_state_spinner);
mLoadingView = view.findViewById(R.id.fragment_career_loading_spinner);
mExamListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Exam exam = (Exam) parent.getItemAtPosition(position);
if (exam.isBookable()) {
FragmentManager fm = getActivity().getSupportFragmentManager();
SessionsDialogFragment.newInstance(exam).show(fm, null);
}
}
});
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> yearAdapter = ArrayAdapter.createFromResource(getActivity(),
R.array.spinner_year, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
yearAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> stateAdapter = ArrayAdapter.createFromResource(getActivity(),
R.array.spinner_state, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
stateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mYearSpinner.setAdapter(yearAdapter);
mStateSpinner.setAdapter(stateAdapter);
mYearSpinner.setOnItemSelectedListener(onYearSelected);
mStateSpinner.setOnItemSelectedListener(onStateSelected);
return view;
}
I tried implementing what --- suggested and I want to report here what happens.
When the application starts all the two listeners are executed only once.
Then, if I select an item on the first spinner (let's say the year spinner), the expected listener is executed only once (as it should be), and so it is, if I keep selecting items on it.
Ultimately, if I select and item on the state spinner, the listeners are executed in this way
1. onStateListener
2. onYearListener
3. onStateListener

From reading your comments it sounds like you want to set the selection of a second spinner to 0 from your first spinners onItemClick method without triggering its listener.
If you keep a record of the old position the spinners are at in integer variables we can check if the position has changed and only run the code if it has.
That way if we set the old position variable to 0 before changing the spinners current position to 0 it will think its position hasn't changed and so won't run the code in the listener.
private AdapterView.OnItemSelectedListener onYearSelected = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (lastYearPosition != position) {
//Do you code here
lastStatePosition = 0;
mStateSpinner.setSelection(0);
}
lastYearPosition = position;
}
#Override
public void onNothingSelected(AdapterView<?> parent) { }
};
private AdapterView.OnItemSelectedListener onStateSelected = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (lastStatePosition != position) {
//Do your code here
lastYearPosition = 0;
mYearSpinner.setSelection(0);
}
lastStatePosition = position;
}

Related

how to add empty first value and set it as null appcompat Spinner

i create in a two way data binding spinner in Android, and added value into with a result of a REST GET.
I need now to add the first value of the spinner as an empty string that when it will be selected from the spinner, the value will be null.
In the fragment class i wrote this code:
//spinner
appCompatSpinner = binding.spinner;
spinnerAdapter = new SpinnerAdapter(getActivity(), viewModel.usersDetailsList );
appCompatSpinner.setAdapter(spinnerActorAdapter);
appCompatSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
viewModel.onSelected(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
mAdapter.notifyDataSetChanged();
Can someone please help me to achieve that?

Android : Spinner OnSelectedItemListener

I have an application with a ListView that displays different transactions made by the user. My code doesn't seem to work.
The problem I have now is that I want to add a Spinner above this ListView to let the user choose whether the transactions should be ordered by date, amount or an own choice of an interval between two dates.
Heres my code for just the spinner onSelectedItem:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_income, container, false);
initializeComponents(view);
registerListeners();
spinnerOrderIncome = (Spinner) view.findViewById(R.id.spinnerOrderIncome);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(), R.array.spinnerSortIncome, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerOrderIncome.setAdapter(adapter);
spinnerOrderIncome.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (spinnerOrderIncome.getSelectedItem().toString()) {
case "date":
lvIncome.setAdapter(new CustomIncomeListAdapter(activity, dbController.getDataFromIncomeTable()));
break;
case "amount":
lvIncome.setAdapter(new CustomIncomeListAdapter(activity, dbController.getSortedAmountFromIncomeTable()));
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
The ListView is already populated with this method that gets the list from the DatabaseController:
public void populateListView() {
lvIncome.setAdapter(new CustomIncomeListAdapter(activity, dbController.getDataFromIncomeTable()));
}
The methods are seen in the switch-statement where thought to change the order of the ListView, but nothing happens when I select the different spinner items (date, amount) Am I on the right track? Help!
Instead of assigning a new adapter to the listView each time you change its data, I would just update the list it contains, then call notifyDataSetChanged to inform the adapter that its datased has changed (so the view will be redrawn).
Something like that, I guess (not tested) :
spinnerOrderIncome.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
CustomIncomeListAdapter myAdapter = (CustomIncomeListAdapter)lvIncome.getAdapter();
myAdapter.getDataSet().clear();
switch (spinnerOrderIncome.getSelectedItem().toString()) {
case "date":
myAdapter.getDataSet().addAll(dbController.getDataFromIncomeTable());
break;
case "amount":
myAdapter.getDataSet().addAll(dbController.getSortedAmountFromIncomeTable());
break;
}
myAdapter.notifyDataSetChanged();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}

Set spinner selected item text

I have a spinner (only relevant parts of code)...
protected void onCreate(Bundle savedInstanceState) {
Spinner to_spinner = (Spinner) findViewById(R.id.to_spinner);
List<Unit> list = myDbHelper.getAllUnits();
SpinnerUnitAdapter tUnitAdapter tUnitAdapter = new SpinnerUnitAdapter(this, android.R.layout.simple_spinner_item, list);
to_spinner.setAdapter(tUnitAdapter);
to_spinner.setOnItemSelectedListener(onItemSelectedListenerTo);
}
with an onItemSelectedListener
AdapterView.OnItemSelectedListener onItemSelectedListenerTo = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view,
int position, long id) {
// do stuff
}
#Override
public void onNothingSelected(AdapterView<?> adapter) {
}
};
When an item is selected (i.e. where it says: "do stuff"), I would like to set/change the text of the selected spinner item. (Note that this is not the same as setting the spinner position (with setSelection()).
I was thinking of doing this with
tUnitAdapter.getView(position, ?, ?).setText("new text");
Am I on the right track? What to put as second ("convertView") and third ("parent") argument in getView. My spinner adapter looks like:
public class SpinnerUnitAdapter extends ArrayAdapter<Unit> {
...
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView label = new TextView(mContext);
label.setTextColor(Color.BLACK);
label.setTextSize(mContext.getResources().getDimension(R.dimen.list_row_font_size));
label.setGravity(Gravity.CENTER);
label.setText(getItem(position).getName());
return label;
}
}
Am I on the right track?
No. You should do the following steps: (in the onItemSelected method)
Update your model (the array of items you passed to the adapter) so that the item at position index takes the new name.
Issue notifyDataSetChanged on the adapter object. Alternatively, you can do this manually by ((TextView) view).setText(new_name);
Note: In onItemSelected method, adapterView points to your spinner view and view points to the row view just selected.
UPDATE #1
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
((TextView) view).setText("new name");
}
UPDATE #2
For this, you should use Java interface to implement a callback which is called once the dialog is closed.
public void onItemSelected(AdapterView<?> adapterView, final View view, int position, long id) {
Dialog dialog = new MyDialog(context, new MyDialog.OnItemSelectListener(){
#Override
public void onItemSelected(String newName){
((TextView) view).setText(newName);
}
});
dialog.show();
}
And declare interface OnItemSelectListener in your MyDialog class.
You can change the text of spinner when you click each item so you should implement onClickListener
public class SpinnerUnitAdapter extends ArrayAdapter<Unit> {
...
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView label = new TextView(mContext);
...
label.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// change label text here
// label.setText(...);
}
});
return label;
}
}
Hope this help
I think I found the solution. I can just do:
public void onItemSelected(AdapterView<?> adapterView, View view,
int position, long id) {
TextView tv = (TextView) adapterView.getSelectedView();
tv.setText("new text");
}

Dropdown Navigation Android

I'm a beginning Android developer and I want to learn how to implement dropdown navigation in my app. Essentially, I would like a different layout to show on the screen when the user selects an item in a spinner in the action bar.
I created a new activity with the Dropdown navigation template in Android Studio but I don't know how to proceed. How would I go about accomplishing this?
To have a different view in the action bar spinner than in the spinner list, you can use a BaseAdapter or an ArrayAdapter and override some methods:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Return a view which appears in the action bar.
return yourCustomView..;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
// Return a view which appears in the spinner list.
// Ignoring convertView to make things simpler, considering
// we have different types of views. If the list is long, think twice!
return super.getView(position, null, parent);
}
More specific details can be found from here: https://stackoverflow.com/a/15293471/1650683
==== EDIT ====
You can find how to integrate dropdown in ActionBar in This article, follow the instruction, you will get it done.
As to bring to a different layout after selecting an item on the spinner, you should set fragment after user clicks on the dropdown item. Sample code:
mOnNavigationListener = new OnNavigationListener() {
// Get the same strings provided for the drop-down's ArrayAdapter
String[] strings = getResources().getStringArray(R.array.action_list);
#Override
public boolean onNavigationItemSelected(int position, long itemId) {
// Create new fragment from our own Fragment class
ListContentFragment newFragment = new ListContentFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment container with this fragment
// and give the fragment a tag name equal to the string at the position
// selected
ft.replace(R.id.fragment_container, newFragment, strings[position]);
// Apply changes
ft.commit();
return true;
}
};
Use spinner for dropdown.This may help you.
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_item, array_name);
adapter.setDropDownViewResource(R.layout.spinner_layout);
final Spinner s1 = (Spinner) findViewById(R.id.spinner1);
s1.setPrompt("Your Title");
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3)
{
--enter your code here--
}}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});

using android ListView onItemClick to select specific Item in slide menu

OK guys, so after 4 hours of struggling i finally decided to ask here my problem. I developed a slide menu with a listView. I got the slide menu all good and i managed to make it doing just one action if one of the Items is clicked. My problem is that i do not know how to manage it further. I am thinking about making a switch case statement but the problem is that i cannot use "position" due to: "position cannot be resolved to a variable"
Here is my list code so far:
public class RandomList extends SherlockListFragment{
String[] list_contents = {
"Add me on Google+",
"Linkedin",
"W&T Top Tips Forum",
};
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.list, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
final ListView list1;
list1 = getListView();
list1.setAdapter(new ArrayAdapter<String> (getActivity(),android.R.layout.simple_list_item_1, list_contents));
list1.setOnItemClickListener(
new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Object listItem = list1.getItemAtPosition(position);
//long index = arg0.getSelectedItemId();
switch(position){
}
Intent myWebLink = new Intent(android.content.Intent.ACTION_VIEW);
myWebLink.setData(Uri.parse("https://plus.google.com/u/0/115467961053443202630/about"));
startActivity(myWebLink);
}
}
);
}
}
Use the variable arg2 in the switch case.This indicates the position of the item which has been clicked.

Categories

Resources