2

I am using a view pager . I have three fragments in it I added a button in one of them and tried to make a method for it in the fragment class but this doesn't work. I tried after that to put the method in the main Activity class and it worked.

this is my MainActivity code :

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        assert actionBar != null;
        actionBar.setDisplayShowTitleEnabled(false);
        mAuth = FirebaseAuth.getInstance();
        mViewPager = findViewById(R.id.viewpager);
        adapter = new SamplePagerAdapter(this);
        tabLayout = findViewById(R.id.tablayout);
        mViewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(mViewPager);

        mViewPager.setCurrentItem(1);


        TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        tabOne.setText("تعلم");
        tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.learn, 0, 0);
        tabLayout.getTabAt(0).setCustomView(tabOne);

        TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        tabTwo.setText("الصفحة الرئيسية");
        tabTwo.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.home, 0, 0);
        tabLayout.getTabAt(1).setCustomView(tabTwo);

        TextView tabThree = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        tabThree.setText("التحديات");
        tabThree.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.challenges, 0, 0);
        tabLayout.getTabAt(2).setCustomView(tabThree);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                tabPosition = tab.getPosition();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.myQuestions:
                //newGame();
                return true;
            case R.id.aboutApp:
                //showHelp();
                return true;
            case R.id.bestStudents:
                //showHelp();
                return true;
            case R.id.myAccount:
                //showHelp();
                return true;
            case R.id.signOut:
                mAuth.signOut();
                Intent i = new Intent(MainActivity.this, GeneralSignActivity.class);
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if(tabPosition != 1){
            mViewPager.setCurrentItem(1);
        }
        else{
            this.finishAffinity();
            System.exit(0);
        }
    }
}

and this is my fragment code :

public static LearnFragment newInstance(String param1, String param2) {
    LearnFragment fragment = new LearnFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    myView=inflater.inflate(R.layout.fragment_learn,container,false);

    return myView;
}

And this is the xml code of the main activity :

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/sample_main_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@color/color1">

                <TextView
                    android:id="@+id/toolbar_title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:text="@string/app_name"
                    android:textColor="@color/white"
                    android:textSize="@dimen/text_size_in_toolbar" />
            </android.support.v7.widget.Toolbar>

            <android.support.design.widget.TabLayout
                android:id="@+id/tablayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/color1">

            </android.support.design.widget.TabLayout>
        </android.support.design.widget.AppBarLayout>


        <android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="0px"
            android:layout_weight="1"
            android:background="@android:color/white" />

    </LinearLayout>
</android.support.design.widget.CoordinatorLayout>

and this is the fragment xml code :

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mk.playAndLearn.fragment.LearnFragment">

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/button"
    android:onClick="click3"
    android:text="click me"/>

</FrameLayout>
Mostafa Khaled
  • 372
  • 4
  • 16

1 Answers1

1

and tried to make a method for it in the fragment class but this doesn't work

If you have added a Button to the Fragment, then you should initialize the Button inside the Fragment with the view prefix and adding the Button inside the Fragment layout too. So:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    myView = inflater.inflate(R.layout.fragment_learn,container,false);
    Button myBtn = myView.findViewById(R.id.thebuttonid);

    // use onClickListener here to handle the button

    return myView;
}

I suppose you were handling the Button inside the MainActivity class which won't probably work.


You are handling the Button with onClick in the xml so, place the current code inside the Fragment and outside of onCreateView or any other methods:

public void click3(View v) {
    switch(v.getId()) {
        // do your stuff here
    }
} 
ʍѳђઽ૯ท
  • 16,646
  • 7
  • 53
  • 108
  • The button is in the fragment xml not in the main activity – Mostafa Khaled Sep 18 '18 at 20:35
  • You were handling the `Button` inside the MainActivity i guess. That's why – ʍѳђઽ૯ท Sep 18 '18 at 20:38
  • First I tried to handle the button at the fragment class but when it doesn't work I put it in the main activity and then only it worked – Mostafa Khaled Sep 18 '18 at 20:42
  • So my answer is correct. Just handle the `Button` and create your methods inside the `Fragment` if you place the `Button` inside the `Fragment`. Simple, right? :) – ʍѳђઽ૯ท Sep 18 '18 at 20:43
  • When I place the button inside the fragment it doesn't work – Mostafa Khaled Sep 18 '18 at 20:45
  • Updated the answer with xml handling. – ʍѳђઽ૯ท Sep 18 '18 at 20:49
  • The app crashed when I did that – Mostafa Khaled Sep 18 '18 at 21:12
  • Can you paste the logcat somewhere that i can see? However, I’d go just like i wrote in the answer by removing android:onClick from xml and handling the `Button` inside the `onCreateView` by adding the view prefix and `setOnClickListener` – ʍѳђઽ૯ท Sep 18 '18 at 21:21
  • java.lang.IllegalStateException: Could not find method click3(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'button' – Mostafa Khaled Sep 18 '18 at 21:25
  • This : https://stackoverflow.com/questions/6091194/how-to-handle-button-clicks-using-the-xml-onclick-within-fragments) will answer to your another question but, my first section of the answer for the handling Button inside onCreaterView is the best option in your situation. – ʍѳђઽ૯ท Sep 18 '18 at 21:31