I am developing an android which has 4 spinners(A,B,C,D).
What I want to achieve is
If Spinner A is set to a value I want the remaining spinners to automatically change their value depending on the value of A
Like if I set Movie(in A)--->Ticket(in B)---->Place(in C)---->Time(D) to automatically fill in.
Thanking you
ChinniKrishna Kothapalli
I think you can set an OnItemSelectedListener to your Movie Spinner. The Spinner tutorial is an adequate example. Your OnItemSelectedListener may be like this:
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
if (parent.getItemAtPosition(pos).toString().equals("firstMovieName")) {
// set spinner B/C/D with the corresponding information of first movie
}
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
The onItemSelected method above may be too simple for your need. You need figure it out how to link the four spinners yourself, but May it helps :)
Related
I'm using a Recycler View to show all the images from the galley or the external storage of a device in a Grid Layout Manager. And I'm using a Radio Button to show if the image is selected or not.
PROBLEM
Whenever I select or deselect a Radio Button from the visible Views in the Recycler View some other Views which are outside the Visible Screen got selected or deselected.
It is like I'm pressing on the same View of the Recycler View, but the images are different.
PROBLEM
well that's because of the recycler view concept of reusing the views instead of creating new views every time you scroll.
you see if you have 100 items you want to show in a recycler view and only 20 of them could appear to the user, recycler view creates only 20 view holder to represent the 20 items, whenever the user scroll recycler view will still have 20 view holder only but will just switch the data stored in this view holders rather than create new view holders.
now to handle selection of your items there's two ways to do this.
the naive way
hold selection in a boolean array inside the recycle view adapter.
whenever the user scrolls, the adapter calls onBindViewHolder to update the visible viewholder with the proper data.
so when onBindViewHolder gets called just set the radio button selection according the boolean array using the position sent in the method call
at the end of your usage to the recycler view you can create a getter method in the adapter to get the selection array list of boolean and pass the data based on it
public class PhotosGalleryAdapter extends RecyclerView.Adapter<PhotosGalleryViewHolder> {
ArrayList<Your_Data_ClassType> data;
ArrayList<Boolean> dataSelected ;
public PhotosGalleryAdapter(ArrayList<Your_Data_ClassType> data) {
this.data = data;
dataSelected = new ArrayList<>(data.size()) ;
}
...
#Override
public void onBindViewHolder(#NonNull PhotosGalleryViewHolder holder, int position) {
...
RadioButton radioButton = holder.getRadioButton()
radioButton.setChecked(dataSelected.get(position));
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
dataSelected.set(holder.getAbsoluteAdapterPosition() , isChecked) ;
}
});
...
}
}
the other way is to use a selection tracker and it should be the correct way to handle selections in a recycler view.
the problem with this way is it needs a lot of editing to the code and creating new classes to include as parameters in the selection tracker, but in the end you'll find it worth the time you spent on it.
in order to start with this way you need to do the following :
firstly, decide what should be a key (String-Long-Parcelable) so the tracker should use to differentiate between your data , the safest way is either String or Parcelable as I once tried Long and ended up with lots and lots of problems (in your case I will assume it's the photo's uri which will be of type string)
secondly, you need to create two new classes, one that extends ItemDetailsLookup, and the other extends ItemKeyProvider, and should use the key as their generic type (the type that is put between <> )
your two classes should look like this (that you might copy them straight forward)
the one that extends ItemKeyProvider :
public class GalleryItemKeyProvider extends ItemKeyProvider<String>{
PhotosGalleryAdapter adapter ;
/**
* Creates a new provider with the given scope.
*
* #param scope Scope can't be changed at runtime.
*/
public GalleryItemKeyProvider(int scope,PhotosGalleryAdapter m_adapter) {
super(scope);
this.adapter = m_adapter;
}
#Nullable
#Override
public String getKey(int position) {
return adapter.getKey(position);
}
#Override
public int getPosition(#NonNull String key) {
return adapter.getPosition(key);
}
}
the one that extends ItemDetailsLookup :
public class GalleryDetailsLookup extends ItemDetailsLookup<String> {
private final RecyclerView recView ;
public GalleryDetailsLookup(RecyclerView m_recView){
this.recView = m_recView;
}
#Nullable
#Override
public ItemDetails<String> getItemDetails(#NonNull MotionEvent e) {
View view = recView.findChildViewUnder(e.getX(), e.getY());
if (view != null) {
RecyclerView.ViewHolder holder = recView.getChildViewHolder(view);
if (holder instanceof PhotosGalleryViewHolder) {
return ((PhotosGalleryViewHolder) holder).getItemDetails();
}
}
return null;
}
}
thirdly, you should include this new two methods in your adapter to be used by the above classes
public class PhotosGalleryAdapter extends RecyclerView.Adapter<PhotosGalleryViewHolder> {
...
public String getKey(int position) {
return data.get(position).getUri();
}
public int getPosition(String key) {
for (int i = 0; i < data.size(); i++) {
if (data.get(i).getUri() == key) return i;
}
return 0;
}
...
}
forthly (if there's an english word called forthly), you should initialize the tracker with all the above classes that were created before and he will handle the rest, the tracker takes as parameters
a unique selection tracker id (if that will be the only selection tracker you will use then name it anything)
the ItemKeyProvider that we created
the DetailsLookup that we created
a String-Long-Parcelable Storage to store the keys that were selected in (in our case it will be a String Storage)
a Selection predicate, it's responsible to handle the way of selection you want to do, you want it to be able to (select only one item-multiple selection with no limits- based on a weird algorithm like even only or odd only), in my case I will use a default multiple selection one but if you want to alter it with another selection algorithm you should create a new class that extends SelectionPredicates and implement your way of selection, you could also just check the other default ones might be what you're looking for.
anyway, that's how the initialization should look (you should put this code wherever you initialize your recycler view at whether it's in fragment or activity method):
private void initRecycleView() {
...
SelectionTracker<String> tracker = new SelectionTracker.Builder<>("PhotosGallerySelection",
Your_Recycler_View,
new GalleryItemKeyProvider(ItemKeyProvider.SCOPE_MAPPED, photosAdapter),
new GalleryDetailsLookup(Your_Recycler_View),
StorageStrategy.createStringStorage())
.withSelectionPredicate(SelectionPredicates.createSelectAnything())
.build();
...
}
I didn't find a way to let me initialize the adapter with data and then create the tracker inorder to make the viewholders know about their selection or not, so in this case I firstly created the tracker and then made the adapter know about it's data using a setter and notifyDataSetChanged
what I mean by that is after creating the tracker instantly set the tracker and data to the adapter, so the initRecycleView should look like this
private void initRecycleView() {
...
SelectionTracker<String> tracker = new SelectionTracker.Builder<>("PhotosGallerySelection",
Your_Recycler_View,
new GalleryItemKeyProvider(ItemKeyProvider.SCOPE_MAPPED, photosAdapter),
new GalleryDetailsLookup(Your_Recycler_View),
StorageStrategy.createStringStorage())
.withSelectionPredicate(SelectionPredicates.createSelectAnything())
.build();
photosAdapter.setTracker(tracker);
photosAdapter.setData(data);
photosAdapter.notifyDataSetChanged();
...
}
Last but no least, you should handle how the view holders should know if they were selected or not, so you should let the adapter know about the tracker and its data by creating a setter method in it, that's how the adapter should look like in the end :
public class PhotosGalleryAdapter extends RecyclerView.Adapter<PhotosGalleryViewHolder> {
ArrayList<Your_Data_Class> data;
private SelectionTracker<String> tracker;
public PhotosGalleryAdapter() {
data = new ArrayList<>();
}
public ArrayList<Your_Data_Class> getData() {
return data;
}
public void setData(ArrayList<Your_Data_Class> m_data) {
this.data = m_data;
}
#Override
public ScheduleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
...
}
#Override
public void onBindViewHolder(#NonNull PhotosGalleryViewHolder holder, int position) {
...
boolean isSelected = tracker.isSelected(data.get(i).getUri());
RadioButton radioButton = holder.getRadioButton;
radioButton.setChecked(isSelected);
}
#Override
public int getItemCount() {
return data.size();
}
public String getKey(int position) {
return data.get(position).getUri();
}
public int getPosition(String key) {
for (int i = 0; i < data.size(); i++) {
if (data.get(i).getUri() == key) return i;
}
return 0;
}
public void setTracker(SelectionTracker<String> m_tracker) {
this.tracker = m_tracker;
}
}
(as you may notice if you initialized the adapter with its data through the constructor, when he asks the tracker if there were an item selected or not, it will result in a NullPointerException as at the moment of initializing the adapter you still didn't initialize the tracker)
that way you could keep track of your selection the way google suggests in their documentation (which I honestly don't know why the made it very complicate like that).
if you want to know all the selected item in the end of your application/fragment use, you should call tracker.getSelection() which will return a Selection List for you to iterate on
There's a tiny problem/feature with the tracker that it won't start selecting the first item until you use a long press on it, that happens only in the first item you select, if you do want this feature (start selecting mode by long press) then leave it as it is
incase you don't want it you can make the tracker select a ghost key (any unique string key that means nothing to your data) at the beginning which should later enable the selection mode with a simple click on any photo
tracker.select("");
this also the way to make a default/old selection at the beginning, you could make a for loop and call tracker.select(Key) if you do want the tracker to start with few items being selected
N.B : incase you use the Ghost Key method you should watchout that the selection array that will get returned when you call tracker.getSelection() will also contain this Ghost Key.
at the end if you do have the curiosity of reading about selection tracker in the documentation follow this link
or maybe if you know how to read kotlin follow this two links
implementing-selection-in-recyclerview
a guide to recyclerview selection
I was stuck in the selection problem for days before I figure how to do all that so I hope you find your way through it.
Omar Shawky has covered the solutions.
With my answer I will stress on the reason why someone may face this sort of an issues with recycler views and how to avoid this common issue in the future (avoiding pitfalls).
Reason:
This issue happens because RecyclerView recycles views. So a RecyclerView item's view once inflated can get reused to show another off screen (to be scrolled to) item. This helps reduces re-inflation of views which otherwise can be taxing.
So if the radio button of an item's view is selected, and the same view gets reused to show some other item, then that new item can also have a selected radio button.
Solution:
The simplest solution for such issues is to have an if else logic in your ViewHolder to provide logic for both selected and de-selected cases. We also do not rely on information from radio button itself for initial setup (we do not use radioButton.isSelected() at the time of setup)
e.g code to write inside your ViewHolder class:
private boolean isRadioButtonChecked = false; // ViewHolder class level variable. Default value is unchecked
// Now while binding in your ViewHolder class:
// Setup Radio button (assuming there is just one radio button for a recyclerView item).
// Handle both selected and de-selected cases like below (code can be simplified but elaborating for understanding):
if (isRadioButtonChecked) {
radioButton.setChecked(true);
} else {
radioButton.setChecked(false);
}
radioButton.setOnCheckedChangeListener(
(radioButton, isChecked) -> isRadioButtonChecked = isChecked);
Do not do any of the following while setting up:
private boolean isRadioButtonChecked = false; // class variable
//while binding do not only handle select case. We should handle both cases.
if (isRadioButtonChecked) { // --> Pitfall
radioButton.setChecked(true);
}
radioButton.setOnCheckedChangeListener((radioButton, isChecked) -> isRadioButtonChecked = isChecked);
OR
// During initial setup do not use radio button itself to get information.
if (radioButton.isChecked()) { // --> Pitfall
radioButton.setChecked();
}
I have a profile activity where user select there country for the first time ,after that when user wish to change the country he will go to profile activity there he should see the previous selected country in the spinner and then he must be able to select another country from the spinner.
I am trying to update my profile activity ,I have a spinner named country in it..I am using set selected for getting the previous selected value .i am getting the value but when i am trying to change that value its not happening .
The Country_value is string
Below is the code for spinner :
country_adapter_list = new ArrayAdapter(MyProfile.this, R.layout.support_simple_spinner_dropdown_item,Country_listItems);
country = (Spinner) findViewById(R.id.sp_country);
country.setAdapter(country_adapter_list);
country.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
country.setSelection(Country_listItems.indexOf(country_value));
country_data = Country_listItems.get(position);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
OnItemSelected() method will select the item present in list at position.
The setSelection() will internally call the onItemSelected() to set the selected item in the spinner. So calling setSelection() inside onItemselected() will not help you.
Try below code.
#Override
public void onItemSelected(AdapterView<?> **adapterView**, View view,int position, long l) {
**adapterView**.setSelection(Country_listItems.indexOf(country_value));
country_data = Country_listItems.get(position);
}
Your code is working fine, but it will not set selection on Spinner if "country_value" is not found in arraylist that you set.
Video Link
I found error in findViewById in static function.
my function is--
public static void onYearSelect() {
Spinner yearSelector;
String yearName;
yearSelector = (Spinner) findViewById(R.id.year_submit);
yearName = yearSelector.getSelectedItem().toString();
}
is there any way to solve this error!
can i store value of Spinner in yearName as String
You need to add view inside function as parameter.
public static void onYearSelect(View view) {
Spinner yearSelector;
yearSelector = (Spinner) view.findViewById(R.id.year_submit);
yearName = yearSelector.getSelectedItem().toString();
}
The view which contains your layout data.
When you call that function add onYearSelect(rootView) here rootView have the layout view.
EDIT 1:
What is View here ?
A View in Android is a widget that displays something. Buttons, listviews, imageviews, etc. are all subclasses of View. When you say "change view" I assume you mean change the layout by using setContentView(). This usually only needs to be done once per activity. An Activity is basically what you are referring to as a screen.
You can read more here.
Set setOnItemSelectedListener on spinner object and inside onItemSelected() you can set value of yearName. Like below,
yearSelector.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String yearName = parentView.getItemAtPosition(position).toString()
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}});
I'm new to android development, I have some experiences on C# windows programming, but also very little. I'm working on an android application which uses spinners. So far, I found a tutorial which make spinner items, and displays spinner text in text view, as you select spinner item. The code lookes like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinner =(Spinner)findViewById(R.id.sp);
text=(TextView)findViewById(R.id.tv);
ArrayAdapter<CharSequence> adapter =ArrayAdapter.createFromResource(this, R.array.spinnerarray, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new function());
}
public class function implements OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int pos,
long id) {
// TODO Auto-generated method stub
String str=parent.getItemAtPosition(pos).toString();
text.setText(str);
}
I want to make an application, which will calculate some points, with the grade user would choose. Example: spinner will contain grades, such as Negative(1), Positive(2),Good(3), Very Good(4), Excellent(5). I want to achieve, that when an user chooses one grade, lets say very good, that the application will use the grade for very good which is 4, and it would transform it to some points, determined by me ( 1=20, 2=40,3=60,4=80,5=100). The points will be later used in calculation, but I have no idea how to assign points to certain grade. I hope you understand my question and thank you for your help.
I had the same app for windows, there I just used something like: if(veryGood.IsSelected==true){points = 20}, and i want to achieve same effect here.
You need a simple modifications on your function class:
public class function implements OnItemSelectedListener {
private final static int[] grades = new int[]{20,40,60,80,100}; //change in whatever you want. The length of the array must be the same of the adapter, or an ArrayIndexOutOfBoundException may be throwed.
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int pos, long id) {
text.setText(grades[pos] + " points!");
}
}
PS: in Java is a good practice to use upper case initial on class names e.g. Function instead of function.
Like this one, I've seen a few how-to's on this site, but truthfully, I'm not really getting it.
I want one spinner's content to be based upon a previous spinner selection, like in a States and Cities scenario. In general terms, what is the workflow? Are the results of the second spinner filtered based on the first spinner, or is the second spinner pointing to a completely different list based on the first spinner?
For my own simple learning project, I've built several string-arrays in the strings.xml (AL-Cities, AK-Cities, AR-Cities, etc). I'd like the city spinner to populate from the correct array based on a choice from the state spinner. But I'm wondering if instead I should just have one large multidimensional array of "Cities" that have a state abbreviation as an additional identifier, and then point the second spinner at that using the state abbreviation as a filter. It would seem like the former would provide better performance.
Any help (and code examples) would be greatly appreciated. I'm not new to programming (php mostly, so I guess scripting is more accurate), but I am new to java. My code so far with the spinners not linked is below with the second spinner pointing to an undifferentiated city_array.
Thank you!
public class Example1 extends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.example1);
Spinner spinState = (Spinner) findViewById(R.id.spin_state);
ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(
this, R.array.state_array, android.R.layout.simple_spinner_item);
adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinState.setAdapter(adapter3);
Spinner spinCity = (Spinner) findViewById(R.id.spin_city);
ArrayAdapter<CharSequence> adapter4 = ArrayAdapter.createFromResource(
this, R.array.city_array, android.R.layout.simple_spinner_item);
adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinCity.setAdapter(adapter4);
}
}
You could try and get the position from your first spinner, the one you've selected and then populate your second spinner after retrieving the proper array based on that position.
You have to listen for your first adapter being changed:
spinner. setOnItemSelectedListener(new MyOnItemSelectedListener());
class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
String choice = parent.getItemAtPosition(pos).toString();
populateSecondSpinnerMethod(choice)
}
}
public void onNothingSelected(AdapterView parent) { // Do nothing.
}
}