How can I create a new Spinner dynamically after itemSelected? - android

I have a Spinner element in one Android Activity.
Now I want that, if I selected on Item of this Spinner, I should be able to create a new Spinner and put it into in my activity. If I select one Item of this second Spinner, I should be able to create a new Spinner ....
so this is the code:
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
v = getActivity().getLayoutInflater().inflate(R.layout.alert_insert_dialog, null);
builder.setView(v);
builder.setTitle("Insert Alerts");
builder.setCancelable(false);
listValueSet_Agent = new ArrayList<AlertValueSet>();
valueSet = new AlertValueSet("2.16.840.1.113883.1.11.20.4","106190000",
"2.16.840.1.113883.6.96","Penicillin","SNOMED CT");
listValueSet_Agent.add(valueSet);
valueSet = new AlertValueSet("2.16.840.1.113883.1.11.20.4","281647001",
"2.16.840.1.113883.6.96","Aspirin","SNOMED CT");
listValueSet_Agent.add(valueSet);
valueSet = new AlertValueSet("2.16.840.1.113883.1.11.20.4","282100009",
"2.16.840.1.113883.6.96","Codeine","SNOMED CT");
listValueSet_Agent.add(valueSet);
valueSet = new AlertValueSet("2.16.840.1.113883.1.11.20.4","282100009",
"2.16.840.1.113883.6.96","Select Agent","SNOMED CT");
listValueSet_Agent.add(valueSet);
//spinner status
Spinner sAgent = (Spinner) v.findViewById(R.id.combo_agent);
adapterAgent = new ArrayAdapter<AlertValueSet>(v.getContext(),
android.R.layout.simple_spinner_item, listValueSet_Agent);
sAgent.setAdapter(adapterAgent);
sAgent.setSelection(0);
sAgent.setOnItemSelectedListener(new SpinnerActivity());
return builder.create();
}
This class is instead, the implementation of OnItemSelectedListener class:
public class SpinnerActivity implements AdapterView.OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Spinner spinnerAgentN = new Spinner(v.getContext());
spinnerAgentN.setAdapter(adapterAgent);
spinnerAgentN.setSelection(listValueSet_Agent.size()-1);
spinnerAgentN.setOnItemSelectedListener(new SpinnerActivity());
LinearLayout linearLayout = (LinearLayout)v.findViewById(R.id.layoutText);
linearLayout.addView(spinnerAgentN,2);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
Now the problem is, if I try to run my application, this method (onItemSelected) is called for every time, and I can see in my activity N spinner, but this is not good.
If I try to delete this code:
spinnerAgentN.setOnItemSelectedListener(new SpinnerActivity());
I don't have any problem.
How can I fixed it?

while data is set to the adapter, then called onitem click listener automatically. So in on item click listener method you have to check the position value. if the position value is 0 then you don't have set the data to second spinner otherwise you have to set the data to second spinner.

Inside onItemSelected()
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
AlertValueSet set = listValueSet_Agent.get(pos);
// Fetch new data based on the selected item and set it back to the spinner
adapterAgent = new ArrayAdapter<AlertValueSet>(v.getContext(),
android.R.layout.simple_spinner_item, listValueSet_Agent);
sAgent.setAdapter(adapterAgent);
}

As per my understanding of code and requirement, there are two options for resolve your query.
But I will explain only one which is fit for your requirement
just declare your array as below.
listValueSet_Agent = new ArrayList<AlertValueSet>();
valueSet = new AlertValueSet("Select","2.16.840.1.113883.1.11.20.4","106190000",
"2.16.840.1.113883.6.96","Penicillin","SNOMED CT");
listValueSet_Agent.add(valueSet);
valueSet = new AlertValueSet("Select","2.16.840.1.113883.1.11.20.4","281647001",
"2.16.840.1.113883.6.96","Aspirin","SNOMED CT");
listValueSet_Agent.add(valueSet);
valueSet = new AlertValueSet("Select","2.16.840.1.113883.1.11.20.4","282100009",
"2.16.840.1.113883.6.96","Codeine","SNOMED CT");
listValueSet_Agent.add(valueSet);
valueSet = new AlertValueSet("Select","2.16.840.1.113883.1.11.20.4","282100009",
"2.16.840.1.113883.6.96","Select Agent","SNOMED CT");
listValueSet_Agent.add(valueSet);
Now, change your onItemSelected method as below,
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
if(pos > 0)
{
Spinner spinnerAgentN = new Spinner(v.getContext());
spinnerAgentN.setAdapter(adapterAgent);
spinnerAgentN.setSelection(listValueSet_Agent.size()-1);
spinnerAgentN.setOnItemSelectedListener(new SpinnerActivity());
LinearLayout linearLayout = (LinearLayout)v.findViewById(R.id.layoutText);
linearLayout.addView(spinnerAgentN,2);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}

Related

How do you delete an Item from a ListView from a dialog box class?

I made my own dialog box class. This class has a button to delete an item from a listview(which is the main acctivity_main.xml). When I push the delete button the item does not get deleted.
I have seen this topic Android: how to remove an item from a listView and arrayAdapter. It just appears the user does not know how to get the item index correctly, which I believe I have done correctly.
Remove ListView items in Android This one is pretty close. But in my code I created my own dialog, this one is using a positive and negative button. I am passing variables between my dialog class and to the mainActivity.
my onClickListener in OnCreate withing the MainActivity
mFoodDataAdapter = new FoodDataAdapter();
final ListView listFoodData = (ListView) findViewById(R.id.listView);
listFoodData.setAdapter(mFoodDataAdapter);
//Handle clicks on the ListView
listFoodData.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int whichItem, long id) {
FoodData tempFoodData = mFoodDataAdapter.getItem(whichItem);
//create a new dialog window
DialogShowFood dialog = new DialogShowFood();
// send in a reference to the note to be shown
dialog.sendFoodDataSelected(tempFoodData);
FoodDataAdapter adapter1 = new FoodDataAdapter();
/*this is where i send the data to the DialogShowFood.java*/
dialog.sendFoodDataAdapter(adapter1, whichItem);
// show the dialog window with the note in it
dialog.show(getFragmentManager(),"");
}
});
Here is my class for the dialog "DialogShowFood.java"
public class DialogShowFood extends DialogFragment {
FoodData mFood;
MainActivity.FoodDataAdapter mAdapter;
int mitemToDelete;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.dialog_show_food, null);
Button btnDelete = (Button) dialogView.findViewById(R.id.btnDelete);
builder.setView(dialogView).setMessage("Your food");
/*this sends the item to delete to the adapter*/
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mAdapter.deleteFoodData(mitemToDelete);
dismiss();
}
});
return builder.create();
}
/*this gets the data to delete from the MainActivity*/
public void sendFoodDataAdapter(MainActivity.FoodDataAdapter adapter1, int whichItem) {
mAdapter = adapter1;
mitemToDelete = whichItem;
}
}
The function inside the adapter
/*this is the function in the base adapter to delete the item*/
public void deleteFoodData(int n){
Toast.makeText(MainActivity.this,Integer.toString(n), Toast.LENGTH_SHORT).show();
foodDataList.remove(n);
notifyDataSetChanged();
}
The Toast outputs the proper indexes of the item to delete, it just does not delete the item for some reason.

showAsDropDown but upwards like spinner

I have used popup listview to work like spinner .I want it to pop upwards like spinner does when its at the bottom of the screen .
I have tried :
popupWindowDogs.showAsDropDown(buttonShowDropDown,5,0);
ALSO,
popupWindowDogs.showAsDropDown(buttonShowDropDown, (int)(Math.round(buttonShowDropDown.getX())),-(totallinear_layouts+buttonShowDropDown.getHeight()));
totallinearlayouts = sum of all heights of linear layouts till the button.
This works properly on a few devices but not like Spinner. How can I make it to work like Spinner? I mean to inflate exactly as the size of the device and the list height. I really appreciate any help. Thanks in Advance.
Reference:https://www.codeofaninja.com/2013/04/show-listview-as-drop-down-android.html
MainActivity.java
public class MainActivity extends Activity {
String TAG = "MainActivity.java";
String popUpContents[];
PopupWindow popupWindowDogs;
Button buttonShowDropDown;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize pop up window items list
// add items on the array dynamically
// format is DogName::DogID
List<String> dogsList = new ArrayList<String>();
dogsList.add("Akita Inu::1");
dogsList.add("Alaskan Klee Kai::2");
dogsList.add("Papillon::3");
dogsList.add("Tibetan Spaniel::4");
// convert to simple array
popUpContents = new String[dogsList.size()];
dogsList.toArray(popUpContents);
// initialize pop up window
popupWindowDogs = popupWindowDogs();
// button on click listener
View.OnClickListener handler = new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonShowDropDown:
// show the list view as dropdown
popupWindowDogs.showAsDropDown(v, -5, 0);
break;
}
}
};
// our button
buttonShowDropDown = (Button) findViewById(R.id.buttonShowDropDown);
buttonShowDropDown.setOnClickListener(handler);
}
public PopupWindow popupWindowDogs() {
// initialize a pop up window type
PopupWindow popupWindow = new PopupWindow(this);
// the drop down list is a list view
ListView listViewDogs = new ListView(this);
// set our adapter and pass our pop up window contents
listViewDogs.setAdapter(dogsAdapter(popUpContents));
// set the item click listener
listViewDogs.setOnItemClickListener(new DogsDropdownOnItemClickListener());
// some other visual settings
popupWindow.setFocusable(true);
popupWindow.setWidth(250);
popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
// set the list view as pop up window content
popupWindow.setContentView(listViewDogs);
return popupWindow;
}
/*
* adapter where the list values will be set
*/
private ArrayAdapter<String> dogsAdapter(String dogsArray[]) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dogsArray) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// setting the ID and text for every items in the list
String item = getItem(position);
String[] itemArr = item.split("::");
String text = itemArr[0];
String id = itemArr[1];
// visual settings for the list item
TextView listItem = new TextView(MainActivity.this);
listItem.setText(text);
listItem.setTag(id);
listItem.setTextSize(22);
listItem.setPadding(10, 10, 10, 10);
listItem.setTextColor(Color.WHITE);
return listItem;
}
};
return adapter;
}
}
DogsDropdownOnItemClickListener.java
public class DogsDropdownOnItemClickListener implements OnItemClickListener {
String TAG = "DogsDropdownOnItemClickListener.java";
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
// get the context and main activity to access variables
Context mContext = v.getContext();
MainActivity mainActivity = ((MainActivity) mContext);
// add some animation when a list item was clicked
Animation fadeInAnimation = AnimationUtils.loadAnimation(v.getContext(), android.R.anim.fade_in);
fadeInAnimation.setDuration(10);
v.startAnimation(fadeInAnimation);
// dismiss the pop up
mainActivity.popupWindowDogs.dismiss();
// get the text and set it as the button text
String selectedItemText = ((TextView) v).getText().toString();
mainActivity.buttonShowDropDown.setText(selectedItemText);
// get the id
String selectedItemTag = ((TextView) v).getTag().toString();
Toast.makeText(mContext, "Dog ID is: " + selectedItemTag, Toast.LENGTH_SHORT).show();
}
}

Android - spinner within dialog won't populate

I'm trying to add a two spinners inside a dialog (popup). The problem I'm having is populating the spinners. I get no error I can see, and basically the same code works if It's in a tab-fragment, and not the dialog.
This is the code that does not popluate the spinners inside the dialog.
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
League league;
league = ((LeagueMainActivity)getActivity()).getLeague();
View v = inflater.inflate(R.layout.diaglog_add_match, null);
Spinner spinner1 = (Spinner) v.findViewById(R.id.spinner_dialog_player1);
Spinner spinner2 = (Spinner) v.findViewById(R.id.spinner_dialog_player2);
String [] items = {"test 1", "test 2"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Log.d("Spinner: ", "" + spinner1);
spinner1.setAdapter(adapter);
spinner2.setAdapter(adapter);
builder.setView(inflater.inflate(R.layout.diaglog_add_match, null))
.setTitle("Add match")
.setPositiveButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// sign in the user ...
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//LoginDialogFragment.this.getDialog().cancel();
/* do I really need to do anything??? */
}
});
AlertDialog dialog = builder.create();
return dialog;
}
This is the code that works within a (tabbed) fragment:
public class UnnamedFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_unnamed, container, false);
Spinner spinner1 = (Spinner) rootView.findViewById(R.id.spinner);
String [] items = {"test 1", "test 2"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Log.d("Spinner: ", "" + spinner1);
spinner1.setAdapter(adapter);
return rootView;
}
}
Okay so what I did wrong was inflating/creating two independent views with the same context.
First I did:
View v = inflater.inflate(R.layout.diaglog_add_match, null);
And then:
builder.setView(inflater.inflate(R.layout.diaglog_add_match, null))
So I set the view for the builder as a new view, and not the same ones I used for the spinner.
So instead if I do:
View v = inflater.inflate(R.layout.diaglog_add_match, null);
builder.setView(v)
That does the trick.

Spinner data accept is mulfunctioning

I have a spinner which displays both options, but when I accept the female option, it still takes the answer as a male, any suggestions?
List<String> SpinnerArray = new ArrayList<String>();
SpinnerArray.add("Male");
SpinnerArray.add("Female");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, SpinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner Items = (Spinner) findViewById(R.id.genderSpinner);
Items.setAdapter(adapter);
// Importing all assets like buttons, text fields
inputFullName = (EditText) findViewById(R.id.registerName);
String selected = Items.getSelectedItem().toString();
if (selected.equals("Male")) {
inputGen = "Male";
}
if (selected.equals("Female")){
inputGen = "Female";
}
Following the official guide:
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
...
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
You can try a switch of position and then try your same conditions.

Android set position in a spinner

I want to set the position for a spinner. I have a string array for the adapter, i.e,
final String[] cat = { "Highest", "Lowest", "Most Recent"};
But I want my spinner to initially display a blank. So I tried this.
mSpinner.setSelection(-1);
But this doesn't solve my problem. Any ideas how to do this? Help is much needed and appreciated. Thanks.
UPDATE:
My code:
private void displayDialog() {
// TODO displayDialog
final ArrayAdapter<String> adp = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, sortBy);
LayoutInflater li = LayoutInflater.from(this);
View promptsView = li.inflate(R.layout.dialog_layout, null);
promptsView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
final Spinner mSpinner= (Spinner) promptsView
.findViewById(R.id.spDialog);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Sort By...");
builder.setIcon(R.drawable.launcher);
mSpinner.setAdapter(adp);
mSpinner.setSelection(-1);
mSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View v,
int pos, long id) {
strSpinner = mSpinner.getSelectedItem().toString();
if(strSpinner.equals("Highest Price")){
highest.setTypeface(Typeface.DEFAULT_BOLD);
lowest.setTypeface(Typeface.DEFAULT);
location.setTypeface(Typeface.DEFAULT);
price = dbHelper.sortHighestPrice();
adapter = new MyCustomAdapter(imgs, text, price);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
} else if (strSpinner.equals("Lowest Price")){
highest.setTypeface(Typeface.DEFAULT);
lowest.setTypeface(Typeface.DEFAULT_BOLD);
location.setTypeface(Typeface.DEFAULT);
price = dbHelper.sortLowestPrice();
adapter = new MyCustomAdapter(imgs, text, price);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
} else if (strSpinner.equals("Location")) {
highest.setTypeface(Typeface.DEFAULT);
lowest.setTypeface(Typeface.DEFAULT);
location.setTypeface(Typeface.DEFAULT_BOLD);
} else {
Log.d("Default", "Default");
}
}
Make your first item Blank.
final String[] cat = {"", "Highest", "Lowest", "Most Recent"};
make your first item blank and set selection of spinner by default is 0.
To set Spinner default value position to -1.
Override the Spinner Class.
that overrides the setAdapter() method.There you can set position to -1.
Please follow the link for details :
How to make an Android Spinner with initial text "Select One"

Categories

Resources