Как обновить фрагмент sh внутри фрагмента диалога в android? - PullRequest
0 голосов
/ 18 апреля 2020

У меня проблема с тем, как обновить фрагмент внутри фрагмента диалога.

вот изображение моего приложения: it is my application

, когда я нажимаю кнопка меню фильтра показывает новый фрагмент диалога, который включает радиогруппу.

dialog

Я хочу обновить фрагмент, содержащий список мест, когда я нажал кнопку ОК.

это код PlaceActivity, который содержит PlaceFragment:

publi c Класс PlaceActivity расширяет AppCompatActivity {

// assign frame layout.
FrameLayout frameLayout;
// assign bottom navigation.
BottomNavigationView bottomNavigationView;

//assign and initialize whole of fragments.
FavoriteFragment favoriteFragment = new FavoriteFragment();
MyPlanFragment myPlanFragment = new MyPlanFragment();
PlaceFragment placeFragment = new PlaceFragment();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.place_activity);

    // initialize views by id.
    frameLayout = findViewById(R.id.frame_place_activity);
    bottomNavigationView = findViewById(R.id.bottom_navigation_view);


    // Set book fragment as initial fragment.
    setFragment(placeFragment);
    bottomNavigationView.setSelectedItemId(R.id.bottom_nav_place);

    // Set on click listener on bottom navigation items.
    bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
            switch (menuItem.getItemId()){
                case R.id.bottom_nav_plan:
                    setFragment(myPlanFragment);
                    return true;
                case R.id.bottom_nav_place:
                    setFragment(placeFragment);
                    return true;
                case R.id.bottom_nav_favorite:
                    setFragment(favoriteFragment);
                    return true;
                default:
                    return false;
            }
        }
    });

}


/**
 * set frame layout to the fragment of argument.
 * @param fragment is used in order to inflate frame layout.
 */
private void setFragment(Fragment fragment) {
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.frame_place_activity,fragment);
    fragmentTransaction.commit();
}

}

Вот код класса PlaceFragment:

publi c Класс PlaceFragment extends Fragment {

public static final String TAG = PlaceFragment.class.getName();

// String which stores json string returnable.
String jsonResponse = GooglePlaceJson.MALLS_JSON_RESPONSE;

// Shared Preferences is used to return back the id of selected item.
SharedPreferences sharedPreference;

// Empty view is shown when the list view does not contain any items.
TextView emptyView;

public PlaceFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_place, container, false);
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    super.onCreate(savedInstanceState);
}

// called when view is created.
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    //ListView for showing a list of places
    ListView listView = view.findViewById(R.id.list);

    //TextView for showing a empty list view.
    emptyView = view.findViewById(R.id.empty_text_view);

    //Create an object of QueryUtils in order to get data from it.
    QueryUtils queryUtils = new QueryUtils(jsonResponse);

    //Adding a list of the places.
    ArrayList<Place> places = queryUtils.extractPlaces();

    //Array adapter used to get the source data and the layout of the list item.
    final PlaceAdapter placeAdapter = new PlaceAdapter(getContext(), places);

    // Set the adapter on the {@link ListView}
    // so the list can be populated in the user interface
    listView.setAdapter(placeAdapter);

    // Set the empty view to list view, cause it will show when there is not item on the list view.
    listView.setEmptyView(emptyView);

    // Set clickable method on item list view.
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            // Find the current place that was clicked on
            Place currentPlace = placeAdapter.getItem(position);

            // Intent used to go to second activity.
            Intent goPlaceDetail = new Intent(getContext(), DetailedPlace.class);
            // Pass current Activity to another Activity.
            goPlaceDetail.putExtra("currentPlace",currentPlace);
            startActivity(goPlaceDetail);
        }
    });

}

// Create a menu then add it to the fragment.
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
    inflater.inflate(R.menu.main_menu,menu);
}

// Set on click listener on the menu items.
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()){
        case R.id.place_menu_filter_:
            // Assign shared preference.
            sharedPreference= getContext().getSharedPreferences(ExampleDialog.MY_PREFS_NAME,MODE_PRIVATE);
            // Open dialog to filter places.
            openDialog();
            // Get the checked text
            String checkedTextItem = sharedPreference.getString(ExampleDialog.CHECKED_ITEM_TEXT_KEY,"");
            if (checkedTextItem.equals(ExampleDialog.RESTAURANT)){
                jsonResponse = GooglePlaceJson.RESTAURANT_JSON_RESPONSE;
            } else if(checkedTextItem.equals(ExampleDialog.MALL)){
                jsonResponse = GooglePlaceJson.MALLS_JSON_RESPONSE;
            }

            this.onViewCreated(getView().findViewById(R.id.list),null);
            return true;
        case R.id.action_settings:
            // Go settings activity when the settings menu item was clicked.
            Intent goSettings = new Intent(getContext(), SettingsActivity.class);
            // Start activity to go to second activity.
            startActivity(goSettings);
            return true;
        default:
            return false;
    }
}


/**
 * Method is used to open dialog.
 */
private void openDialog() {
    // Create an object of the custom dialog.
    ExampleDialog exampleDialog = new ExampleDialog();
    exampleDialog.show(getFragmentManager(),"filter place dialog");

}

}

Вот код класса ExampleDialog:

publi c class ExampleDialog extends AppCompatDialogFragment {

// key of shared preference.
public static final String MY_PREFS_NAME =  "dialog_preference";
public static final String CHECKED_ITME_KEY = "checked_item_key";
public static final String CHECKED_ITEM_TEXT_KEY= "checked_item_text_key";


// Place whole returned possible values.
public static final String RESTAURANT = "restaurant";
public static final String MALL = "mall";
public static final String PARK = "park";


// Declare radio button and button groups.
private static RadioGroup radioGroup;
private static RadioButton restaurant,mall,park;





//Created shared Preference editor in order to add data from it.
SharedPreferences.Editor editor;

//Created shared Preference in order to get data from it.
SharedPreferences sharedPreferences;

@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
    // Create an alert dialog builder to build an dialog.
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    // Use layout inflater in order to add resource to our application.
    LayoutInflater inflater = getActivity().getLayoutInflater();
    View view = inflater.inflate(R.layout.dialog_fragment,null);

    // Assign views with find view by id.
    radioGroup = view.findViewById(R.id.place_radio_group);

    mall = view.findViewById(R.id.mall_radio_button);
    restaurant = view.findViewById(R.id.restaurant_radio_button);
    park = view.findViewById(R.id.park_radio_button);

    // Shared preference is used to get data if it is available.
    sharedPreferences = getActivity().getSharedPreferences(MY_PREFS_NAME,MODE_PRIVATE);

    // Get the checked item from application.
    int selectedId = sharedPreferences.getInt(CHECKED_ITME_KEY,0);
    if (selectedId !=0){
        radioGroup.check(selectedId);
    }else {
        radioGroup.check(restaurant.getId());
    };

    // Create shared preference editor in order to set data into shared preference.
    editor = getActivity().getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();


    // Add cancel and ok buttons on the dialog and set it onclick listener.
    builder.setView(view)
            .setTitle(getString(R.string.msg_radio_group))
            .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            })
            .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    // Get id of whole button in order to return a right data.
                    int restaurantId = restaurant.getId();
                    int mallId = mall.getId();
                    int parkId = park.getId();

                    // Get checked button id of radio group.
                    int checkedId = radioGroup.getCheckedRadioButtonId();
                    // Put checked it of radio button on shared preference.
                    editor.putInt(CHECKED_ITME_KEY,checkedId);

                    // Put text of checked item into shared preference.
                    if (checkedId == restaurantId){
                        editor.putString(CHECKED_ITEM_TEXT_KEY,RESTAURANT);
                    }else if (checkedId == mallId){
                        editor.putString(CHECKED_ITEM_TEXT_KEY,MALL);
                    }else if(checkedId == parkId){
                        editor.putString(CHECKED_ITEM_TEXT_KEY,PARK);

                    }
                    editor.apply();
                    radioGroup.check(checkedId);

                }
            });


    // Create dialog.
    return builder.create();
}


public interface ExampleDialogListener{
    void applyTexts();
}

}

1 Ответ

0 голосов
/ 18 апреля 2020

Непосредственно перед вызовом exampleDialog.show(getFragmentManager(),"filter place dialog"); вызовите

exampleDialog.setTargetFragment( PlaceFragment.this, MY_DATA_REQUEST_CODE)

, а затем в классе ExampleDialog сразу после получения данных от переключателя в методе onClick(), поместите данные как extra в намерении может называться intentWithDialogData, затем вызывать getTargetFragment().onActivityResult(MY_DATA_REQUEST_CODE, RESULT_CODE, intentWithDialogData), override onActivityResult() в вызывающем фрагменте ( PlaceFragment ) для получения данных из переданного намерения

...