当前位置: 首页 > 知识库问答 >
问题:

如何在android中刷新对话框片段中的片段?

祁英哲
2023-03-14

我遇到了一个如何在对话框片段中更新片段的问题。

当我单击过滤器菜单按钮时,会显示一个新的对话框片段,其中包括一个无线电组。

我想在单击ok按钮时更新包含位置列表的片段。

它是PlaceActive的代码,其中包含PlaceFraank:

公共类PlaceActive扩展AppCompatActive{

// 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类的代码:

公共类PlaceFragment扩展了片段{

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类的代码:

公共类ExampleDialog扩展了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个答案

金皓君
2023-03-14

就在调用示例对话框之前。显示(getFragmentManager(),“筛选位置对话框”) 呼叫

exampleDialog.setTargetFragment( PlaceFragment.this, MY_DATA_REQUEST_CODE)

然后,在ExampleDialog类中,在从onClick()方法中的单选按钮获取数据之后,将数据作为额外数据放入一个可能称为intentWithDialogData的intent中,然后调用getTargetFragment()。onActivityResult(MY\u DATA\u REQUEST\u CODE、RESULT\u CODE、intentWithDialogData),在调用片段(PlaceFragment)中重写onActivityResult(),以从传递的意图接收数据

 类似资料:
  • 我读了DialogFragment,然后把它做成这样的一对一。 在另一个SherlockFragment中,我接下来制作: 但是doPositiveClick()、doNegativeClick()方法希望是静态的,这对我来说不好。

  • 我有一个片段,它添加了一个选项到选项菜单。当单击此选项时,将打开一个对话框片段。对话框将原始片段设置为其目标片段。如果在对话片段打开时没有发生方向变化,则目标片段与预期的一样,但是在方向变化之后,目标片段被设置为对话片段本身,而不是先前设置的片段。结果,当试图将目标片段强制转换为被设置为目标片段的片段时,我得到了一个classCastException。我需要在对话框中获取目标片段,因为它实现了一

  • 我有一个包含两个片段的活动:一个用于在网格视图中显示产品,另一个用于显示用户添加到订单中的产品(ListFragment)。当用户在网格视图中单击一个产品时,我需要的是显示一个对话框(DialogFragment),我在其中询问所需产品的数量。然后,当用户在对话框中单击Accept时,我希望产品出现在ListFragment中。 一方面,我必须将产品对象传递给对话框,以便将其名称显示为对话框的标题

  • 这是我在片段内的对话框,它工作正常,现在我希望当我单击“确定”按钮时,它会重新加载当前片段。当调用showDialog方法时,将显示该对话框:mi fragment是android。支持v4。应用程序。碎片 更新这是片段。我想回忆一下片段的onCreateView方法 简单的解决方案 使用viewpager和FragmentPagerAdapter测试

  • 这是我的对话里面的片断,它工作良好,现在我想当我点击“确定”按钮,它重新载入当前的片断。调用showDialog方法时显示对话框:mi fragment is android.support.v4.app.fragment 更新这是片段。我想回顾片段的onCreateView方法 使用viewpager和FragmentPagerAdapter测试

  • 我有Mainactive,它保存片段。我的一个片段(参与者)检查数据库中是否有任何内容。如果没有,则显示带有消息以添加数据的片段(空参与者列表)。如果是,它显示带有2个选项卡的TabHost片段,其中一个包含带有数据库条目的ListView片段(参与者列表)。有一个FAB按钮可以添加更多记录。添加另一条记录后如何刷新ListView?我不确定,因为TabHost不适用于我在应用程序中使用的Frag