androidandroid-studioandroid-fragmentsandroid-fragmentactivityandroid-tablayout

Button inside a Fragment


Hi I am creating an application that is using a Button inside a Fragment, so when I click that Button, then that Button will make a Toast text, I use the Button click listener instead. But the problem is that my Button didn't response to a clicked, when I click it the Button response nothing so I get a stressed out with it. Here is my main problem's code :

test = (Button) findViewById(R.id.button2);
t_layout = (TabLayout) findViewById(R.id.tabs);
t_layout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            Fragment fragment;
            String contain = tab.getText().toString();
        if(contain.equals("POWER")){
                fragment = new power_fragment();
                FragmentManager fm = getFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                ft.replace(R.id.fragment2, fragment);
                ft.commit();

                test.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toast.makeText(getApplicationContext(),"Test on",Toast.LENGTH_SHORT).show();
                             }
                          }
                       }
                    }
               });

I am using a Tabitems so when I click the Tabitem of "POWER" the Fragment will change to power_fragment layout which contains the test Button. But the test Button can't make a Toast text even when it is clicked.


Solution

  • inside your fragment class

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_my_blood_group_requests, container, false);
    
        btn = (Button) v.findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //make your toast here
            }
        });
       return v;
      }