简体   繁体   中英

Populating spinner with EditText from another fragment in Android

I have two fragment.In first one is EditText witch taking some info from user,and in another fragment having Spinner.I am sending EditText,that was first converted to String, to Spinner in second fragment with Android Navigation.And it shows text just fine but when i wish to add another text to Spinner it just replace first text and showing only one text/item in spinner. So my question how to have save text that i previously sent and have nice drop down spinner. BTW i am using data binding i don't know if it is important information for solutions.

fragment from where i am sending data:

@Override
public void onClickComplete() {
    String addCategoryString = addCategory.getText().toString();
    FluctuatingCategoryFragmentDirections.ActionFluctuatingCategoryToCreatingBudgetingItem2 action
            = FluctuatingCategoryFragmentDirections.actionFluctuatingCategoryToCreatingBudgetingItem2();
    action.setFluctuatingCategory(addCategoryString);
    navController.navigate(action);
}

receiving fragment:

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    if (getArguments() != null) {
        CreatingBudgetingItemFragmentArgs args = CreatingBudgetingItemFragmentArgs.fromBundle(getArguments());
        String getCategory = args.getFluctuatingCategory();
        Log.i("Category: ", getCategory);
        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, android.R.id.text1);
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(spinnerAdapter);
        spinnerAdapter.notifyDataSetChanged();
    }
}

When you are navigating to FluctuatingCategoryToCreatingBudgetingItem , the fragment is getting recreated every time, that's why only the value you passed will show up. You must use ViewModel.

Setup a list which will contain the FluctuatingCategoryies and setup your CreatingBudgetingItemFragment to get list item from ViewModel.

Not giving you any code because I want you to start your learning curve. This might help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM