Skip to content
Advertisement

fragment binding (symbol “id” cannot be resolved)

I am trying to use the binding method in android studio to connect two fragments using onCreate and onViewCreated methods. so far i am getting id not resolved error. I have already connected the fragments on the xml graph. Bellow is the code of the settings java file.

package com.mqtt.workactiv.ui.settings;

import static android.os.Build.VERSION_CODES.R;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import com.mqtt.workactiv.databinding.FragmentSettingsBinding;

public class SettingsFragment extends Fragment {

    private FragmentSettingsBinding binding;
    



    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        SettingsViewModel settingsViewModel =
                new ViewModelProvider(this).get(SettingsViewModel.class);

        binding = FragmentSettingsBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

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

        NavController navController = Navigation.findNavController(view);

            Button gateConnButton;
        gateConnButton = view.findViewById(R.id.gatewayConnButton);
        gateConnButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    navController.navigate(R.id.action_navigation_setting_to_gateway4);

                }
            });
    }

}

Advertisement

Answer

Make sure to add this in build.gradle(app)

 buildFeatures {
        viewBinding = true
    }

Then give sync project with gradle files. If this didnt work, try rebuild, invalidate cache/ restart.

Also view.findviewbyid not required if view binding is enabled. You can access button directly by something like this,

 binding.gateConnButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    navController.navigate(R.id.action_navigation_setting_to_gateway4);

                }
            });
Advertisement