我创建了一个Firebase应用程序。

到目前为止,一切都很好。但是,我有一个无法解决的问题。

我的MainActivity.java正在实现Interface ProgressDisplay.java

Interface有两种方法:

public interface ProgressDisplay {

    public void showProgress();

    public void hideProgress();
}


我无法从子片段中调用这两种方法,我无法在片段中设置可见性。

ManageAccountFragment.java

package com.company.walt.fragments;

public class ManageAccountFragment extends Fragment {

    private EditText mName;
    private Button mUpdateBtn;

    private ProgressBar mProgressBar;
    public ManageAccountFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_manage_account, container, false);

        mName = (EditText)view.findViewById(R.id.input_name);
        mUpdateBtn = (Button)view.findViewById(R.id.btn_update);

        mUpdateBtn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view){

                if (!isEmpty (mName.getText().toString()))
                {

                    showProgress();
                    Toast.makeText(getActivity(), "SHOW DIALOG", Toast.LENGTH_SHORT).show();

                    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
                    if (user != null)
                    {
                        UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
                                .setDisplayName(mName.getText().toString())
                                //.setPhotoUri(Uri.parse("https://avatarfiles.alphacoders.com/862/86285.jpg"))
                                .build();

                        user.updateProfile(profileUpdate).addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                if (task.isSuccessful())
                                {
                                    Log.d(TAG, "onComplete: User Profile updated");
                                }
                            }
                        });

                        hideProgress();
                        Toast.makeText(getActivity(), "HIDE DIALOG", Toast.LENGTH_SHORT).show();

                    }
                }

            }

        });

        hideSoftKeyboard();

        return view;
    }

    private boolean isEmpty(String string){
        return string.equals("");
    }

    /**
     * Display progressbar
     */
    protected void showProgress() {
        if (getActivity() instanceof ProgressDisplay) {
            ((ProgressDisplay) getActivity()).showProgress();
        }
    }

    /**
     * Hide progressbar
     */
    protected void hideProgress() {
        if (getActivity() instanceof ProgressDisplay) {
            ((ProgressDisplay) getActivity()).hideProgress();
        }
    }

    private void hideSoftKeyboard(){
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }

}

MainActivity.java

package com.company.walt.activities;

public class MainActivity extends AppCompatActivity implements ProgressDisplay {

    private static final String TAG = "MainActivity";

    private static final int USER_PROFILE = 1;
    private static final int PROFILE_MANAGE = 2;
    private static final int PROFILE_SETTING = 3;

    private Toolbar mainToolbar;
    private AccountHeader headerResult = null;
    private Drawer result = null;

    private ProgressBar mProgressBar;

    private ToggleButton switcher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if(AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) { setTheme(R.style.NightTheme); }
        else { setTheme(R.style.LightTheme);}

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        switchAppTheme();
        createToolbar();

        mProgressBar = (ProgressBar) findViewById(R.id.progressBar);

        buildHeader(false, savedInstanceState);
        createDrawerBuilder();

        getUserDetails();

    }

    @Override
    protected void onResume() {
        super.onResume();
        checkAuthenticationState();
    }

    /**
     * Used to check if user is authenticated or not
     */
    private void checkAuthenticationState()
    {
        Log.d(TAG, "checkAuthenticationState: checking authentication state.");
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        if (user == null){
            Log.d(TAG, "checkAuthenticationState: user is null, navigating back to login screen.");
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
        else {
            Log.d(TAG, "checkAuthenticationState: user is authenticated.");
        }
    }

    /**
     * Used to switch between light and dark mode
     */
    public void switchAppTheme() {

        switcher = (ToggleButton) findViewById(R.id.switcher);

        if(AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
            switcher.setChecked(true);
        }

        switcher.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                    restartApp();
                } else{
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                    restartApp();
                }
            }
        });
    }

    /**
     * Used to create the toolbar on top
     */
    private void createToolbar(){
        mainToolbar = (Toolbar) findViewById(R.id.main_toolbar);
        setSupportActionBar(mainToolbar);
        getSupportActionBar().setTitle(R.string.app_name);
    }

    /**
     * small helper method to reuse the logic to build the AccountHeader
     * this will be used to replace the header of the drawer with a compact/normal header
     *
     * @param compact
     * @param savedInstanceState
     */
    private void buildHeader(boolean compact, Bundle savedInstanceState) {

        IProfile profile_1;
        //IProfile profile_2;

        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

        if (user != null)
        {
            String uid = user.getUid();
            String name = user.getDisplayName();
            String email = user.getEmail();
            Uri photoUrl = user.getPhotoUrl();

            profile_1 = new ProfileDrawerItem()
                    .withName(name)
                    .withEmail(email)
                    .withIcon(photoUrl);

            //profile_2 = new ProfileDrawerItem().withName("Isensei").withEmail("[email protected]").withIcon(getResources().getDrawable(R.drawable.ic_user_58dp));

            headerResult = new AccountHeaderBuilder()

                    .withActivity(this)
                    .withHeaderBackground(R.drawable.ip_menu_header_bg)
                    .withCompactStyle(compact)
                    .addProfiles(
                            profile_1,
                            //profile_2,

                            new ProfileSettingDrawerItem()
                                    .withName("Manage Account")
                                    .withDescription("Manage your details")
                                    .withIcon(new IconicsDrawable(this,GoogleMaterial.Icon.gmd_settings)
                                            .actionBar().colorRes(R.color.material_drawer_dark_primary_text)).withIdentifier(PROFILE_MANAGE),

                            new ProfileSettingDrawerItem()
                                    .withName("Add Account")
                                    .withDescription("Register new account")
                                    .withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_person_add)
                                            .actionBar().colorRes(R.color.material_drawer_dark_primary_text)).withIdentifier(PROFILE_SETTING)

                    )
                    .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {

                        @Override
                        public boolean onProfileChanged(View view, IProfile profile, boolean current) {

                            //sample usage of the onProfileChanged listener
                            //if the clicked item has the identifier 1 add a new profile ;)

                            if (profile instanceof IDrawerItem && ((IDrawerItem) profile).getIdentifier() == USER_PROFILE)
                            {
                                // Navigate to home fragment
                                FragmentManager manager = getSupportFragmentManager();
                                FragmentTransaction transaction = manager.beginTransaction();
                                Fragment fragment = new Fragment();

                                fragment = new HomeFragment();
                                transaction.replace(R.id.flContent, fragment);
                                transaction.commit();

                            }

                            if (profile instanceof IDrawerItem && ((IDrawerItem) profile).getIdentifier() == PROFILE_MANAGE)
                            {
                                // Navigate to home fragment
                                FragmentManager manager = getSupportFragmentManager();
                                FragmentTransaction transaction = manager.beginTransaction();
                                Fragment fragment = new Fragment();

                                fragment = new ManageAccountFragment();
                                transaction.replace(R.id.flContent, fragment);
                                transaction.commit();

                            }

                            else if (profile instanceof IDrawerItem && ((IDrawerItem) profile).getIdentifier() == PROFILE_SETTING)
                            {
                                Toast.makeText(MainActivity.this, "ACCOUNT", Toast.LENGTH_SHORT).show();

                            }

                        /*
                        if (profile instanceof IDrawerItem && ((IDrawerItem) profile).getIdentifier() == PROFILE_SETTING) {

                            IProfile newProfile = new ProfileDrawerItem()
                                    .withNameShown(true)
                                    .withName("Kensei")
                                    .withEmail("[email protected]")
                                    .withIcon(getResources().getDrawable(R.drawable.ic_user_58dp));

                            if (headerResult.getProfiles() != null) {
                                //we know that there are 2 setting elements. set the new profile above them ;)
                                headerResult.addProfile(newProfile, headerResult.getProfiles().size() - 2);
                            } else {
                                headerResult.addProfiles(newProfile);
                            }
                        }
                        */

                            //false if you have not consumed the event and it should close the drawer
                            return false;
                        }
                    })
                    .build();

        }

    }

    /**
     * Used to create the drawer with all the icons and items
     */
    private void createDrawerBuilder(){
        //create the drawer and remember the `Drawer` result object
        result = new DrawerBuilder()
                .withActivity(this)
                .withAccountHeader(headerResult)
                .withToolbar(mainToolbar)
                .addDrawerItems(
                        new SecondaryDrawerItem().withName(R.string.drawer_services)
                                .withIdentifier(1)
                                .withIconTintingEnabled(true)
                                .withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_device_hub))
                                .withTag("Bullhorn"),

                        new SecondaryDrawerItem().withName(R.string.drawer_products)
                                .withIdentifier(2)
                                .withIconTintingEnabled(true)
                                .withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_shopping_cart))
                                .withTag("Bullhorn"),

                        new SecondaryDrawerItem().withName(R.string.drawer_photos)
                                .withIdentifier(3)
                                .withIconTintingEnabled(true)
                                .withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_camera_roll))
                                .withTag("Bullhorn"),

                        new SecondaryDrawerItem().withName(R.string.drawer_poem)
                                .withIdentifier(4)
                                .withIconTintingEnabled(true)
                                .withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_content_copy))
                                .withTag("Bullhorn"),

                        new SecondaryDrawerItem().withName(R.string.drawer_archives)
                                .withIdentifier(5)
                                .withIconTintingEnabled(true)
                                .withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_folder_open))
                                .withTag("Bullhorn"),

                        new SectionDrawerItem().withName(R.string.drawer_section_header).withEnabled(false),

                        new SecondaryDrawerItem().withName(R.string.drawer_settings)
                                .withIdentifier(6)
                                .withIconTintingEnabled(true)
                                .withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_settings))
                                .withTag("Bullhorn"),

                        new SecondaryDrawerItem().withName(R.string.drawer_feedback)
                                .withIdentifier(7)
                                .withIconTintingEnabled(true)
                                .withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_headset_mic))
                                .withTag("Bullhorn"),

                        new SecondaryDrawerItem().withName(R.string.drawer_pro)
                                .withIdentifier(8)
                                .withIconTintingEnabled(true)
                                .withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_security))
                                .withTag("Bullhorn"),

                        new SecondaryDrawerItem().withName(R.string.drawer_logout)
                                .withIdentifier(9)
                                .withIconTintingEnabled(true)
                                .withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_power_settings_new))
                                .withTag("Bullhorn")

                )
                .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                    @Override
                    public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
                        navigateDrawerItem((int)drawerItem.getIdentifier(), drawerItem);
                        return true;
                    }
                })
                .addStickyDrawerItems(
                        new SecondaryDrawerItem().withName(R.string.drawer_all_right_reserved).withIcon(FontAwesome.Icon.faw_copyright).withEnabled(false)
                ).build();

    }

    /**
     * Used to navigate to drawer fragment items
     */
    public void navigateDrawerItem(int ItemId, IDrawerItem drawerItem) {
        // Create a new fragment and specify the fragment to show based on nav item clicked
        Fragment fragment = null;
        Class fragmentClass;
        switch(ItemId) {
            case 1:
                fragmentClass = ServicesFragment.class;
                break;
            case 2:
                fragmentClass = ProductsFragment.class;
                break;
            case 3:
                fragmentClass = PhotosFragment.class;
                break;
            case 4:
                fragmentClass = PoemsFragment.class;
                break;
            case 5:
                fragmentClass = ArchivesFragment.class;
                break;
            case 6:
                fragmentClass = SettingsFragment.class;
                break;
            default:
                fragmentClass = HomeFragment.class;
        }
        try {
            fragment = (Fragment) fragmentClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // Insert the fragment by replacing any existing fragment
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
        result.closeDrawer();
    }




    /*
    private void setUserDetails(){
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

        if (user != null)
        {
            UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
                    .setDisplayName("Jsk Zack")
                    .setPhotoUri(Uri.parse("https://avatarfiles.alphacoders.com/862/86285.jpg"))
                    .build();

            user.updateProfile(profileUpdate).addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful())
                    {
                        Log.d(TAG, "onComplete: User Profile updated");

                        getUserDetails();
                    }
                }
            });
        }
    }
    */



    private void getUserDetails(){
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

        if (user != null)
        {
            String uid = user.getUid();
            String name = user.getDisplayName();
            String email = user.getEmail();
            Uri photoUrl = user.getPhotoUrl();

            String properties =
                    "uid: " + uid + "\n" +
                    "name: " + name + "\n" +
                    "email: " + email + "\n" +
                    "photoUrl: " + photoUrl;

            Log.d(TAG, "getUserDetails: properties: \n" + properties);
        }
    }






    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            default:
                return super.onOptionsItemSelected(item);
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //add the values which need to be saved from the drawer to the bundle
        outState = result.saveInstanceState(outState);

        //add the values which need to be saved from the accountHeader to the bundle
        outState = headerResult.saveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {
        //handle the back press :D close the drawer first and if the drawer is closed close the activity
        if (result != null && result.isDrawerOpen()) {
            result.closeDrawer();
        } else {
            super.onBackPressed();
        }
    }

    /**
     * Display progressbar
     */
    public void showProgress() {
        findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
    }

    /**
     * Hide progressbar
     */
    public void hideProgress() {
        if(mProgressBar.getVisibility() == View.VISIBLE){
            findViewById(R.id.progressBar).setVisibility(View.INVISIBLE);
        }
    }

    /**
     * Used to relaunch the application
     */
    public void restartApp() {
        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        startActivity(intent);
        finish();
    }

}


我不知道为什么这不起作用,我做错了什么吗?

最佳答案

我认为是因为这行代码

 findViewById(R.id.progressBar).setVisibility(View.INVISIBLE);



  只需在主要活动onCreate(){HERE}中实例化进度栏,然后在“隐藏和显示”功能中使用mProgressBar


 public void showProgress() {
    mProgressBar .setVisibility(View.VISIBLE);
}


我希望这有帮助 ;)

07-26 09:32