简体   繁体   中英

How to create an custom alertDialog from a tabbed fragment?

Problem:

I'm trying to open a custom dialog after pressing a button in my tabbed fragment. It's seems like my MainActivity activity is sent to the dialog while i want my tabbed fragment(GroupFragment) to be sent so i can change the editText(for now) in this fragment.

Code:

       public class GroupFragment extends Fragment implements AddGroupDialog.AddGroupDialogListener {
    
        private Button addGroupButton;
        private TextView textViewNoGroups;
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            View view = inflater.inflate(R.layout.fragment_group, container, false);
    
            addGroupButton = view.findViewById(R.id.addGroupButton);
            textViewNoGroups = view.findViewById(R.id.textViewNoGroups);
    
            addGroupButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    addNewGroupDialog();
                }
            });
    
            scaleAnimation(addGroupButton);
    
            return view;
        }
    
        private void scaleAnimation(View v){
            Animator scale = ObjectAnimator.ofPropertyValuesHolder(v,
                    PropertyValuesHolder.ofFloat(View.SCALE_X, 0, 1.2f, 1),
                    PropertyValuesHolder.ofFloat(View.SCALE_Y, 0, 1.2f, 1)
            );
            scale.setDuration(600);
            scale.start();
        }
    
        private void addNewGroupDialog(){
            AddGroupDialog dialog = new AddGroupDialog();
            assert getFragmentManager() != null;
            dialog.show(getFragmentManager(), "add new group dialog");
        }
    
        @Override
        public void applyString(String groupName) {
            textViewNoGroups.setText(groupName);
        }
    }
    
public class AddGroupDialog extends AppCompatDialogFragment {

    
        private EditText editTextGroupName;
        private AddGroupDialogListener listener;
    
        @NonNull
        @Override
        public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
    
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    
            LayoutInflater inflater = getActivity().getLayoutInflater();
            View view = inflater.inflate(R.layout.layout_add_new_group_dialog, null);
    
            builder.setView(view)
                    .setTitle("")
                    .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            String groupName = editTextGroupName.getText().toString();
                            listener.applyString(groupName);
                        }
                    });
    
            editTextGroupName = view.findViewById(R.id.editTextGroupName);
            return builder.create();
        }
    
        @Override
        public void onAttach(@NonNull Context context) {
            super.onAttach(context);
    
            try {
                listener = (AddGroupDialogListener) context;
            } catch (ClassCastException e){
                throw new ClassCastException(context.toString() +
                        "Must implement AddGroupDialogListener");
            }
        }
    
        public interface AddGroupDialogListener{
            void applyString(String groupName);
        }
    
    }
    
    public class MainActivity extends AppCompatActivity{
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
            ViewPager viewPager = findViewById(R.id.view_pager);
            viewPager.setAdapter(sectionsPagerAdapter);
            TabLayout tabs = findViewById(R.id.tabs);
            tabs.setupWithViewPager(viewPager);
    
        }
    }
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    @StringRes
    private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2, R.string.tab_text_3};
    private final Context mContext;

    public SectionsPagerAdapter(Context context, FragmentManager fm) {
        super(fm);
        mContext = context;
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment = null;

        switch (position){
            case 0:
                fragment = new GroupFragment();
                break;
            case 1:
                fragment = new AttendanceFragment();
                break;
            case 2:
                fragment = new StatisticsFragment();
                break;
        }
        return fragment;
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return mContext.getResources().getString(TAB_TITLES[position]);
    }

    @Override
    public int getCount() {
        return TAB_TITLES.length;
    }
}

Error:

java.lang.ClassCastException: com.example.attendencetaker.MainActivity@26602bcMust implement AddGroupDialogListener

I hope my explanation of the problem is clear. Thank you!

Make the activity implement your interfaces and so on and then pass all data to the fragment with an method on the fragment. You will need an reference to actual Fragment that is displayed.

In your fragment add a method similar to this:

public void updateData(String data) {
    editText.setText(data);
}

And in the override method of the interface in your activity to this:

@Override
public void update(String data) {
    fragment.updateData(data);
}
Update

Use this Adapter instead:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    SectionsPagerAdapter sectionTabAdapter = new SectionTabAdapter(this, getSupportFragmentManager());
    Fragment groupFragment = new GroupFragment();
    Fragment attendanceFragment = new AttendanceFragment();
    Fragment statisticsFragment = new StatisticsFragment();
    sectionTabAdapter.addFragment(groupFragment, context.getString(R.string.title_1);
    sectionTabAdapter.addFragment(attendanceFragment, context.getString(R.string.title_2);
    sectionTabAdapter.addFragment(statisticsFragment, context.getString(R.string.title_3);
    ViewPager viewPager = findViewById(R.id.view_pager);
    viewPager.setAdapter(sectionTabAdapter);
    TabLayout tabs = findViewById(R.id.tabs);
    tabs.setupWithViewPager(viewPager);
}

In your activity then do this:

 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SectionsPagerAdapter sectionTabAdapter = new SectionTabAdapter(this, getSupportFragmentManager()); Fragment groupFragment = new GroupFragment(); Fragment attendanceFragment = new AttendanceFragment(); Fragment statisticsFragment = new StatisticsFragment(); sectionTabAdapter.addFragment(groupFragment, context.getString(R.string.title_1); sectionTabAdapter.addFragment(attendanceFragment, context.getString(R.string.title_2); sectionTabAdapter.addFragment(statisticsFragment, context.getString(R.string.title_3); ViewPager viewPager = findViewById(R.id.view_pager); viewPager.setAdapter(sectionTabAdapter); TabLayout tabs = findViewById(R.id.tabs); tabs.setupWithViewPager(viewPager); }

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