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() {

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

                test.setOnClickListener(new View.OnClickListener() {
                    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.


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() {
        public void onClick(View v) {
            //make your toast here
   return v;

Answered By – Shahadat Hossain Shaki

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published