-1

I am having challenge implementing some buttons in MainActivity that when each is clicked, should take me to the Fragment Class, and i have other buttons that i want to set to start fragment activity. Now these fragments are hosted on Tip4Activity with an adapter.

My question is how can i create a button that when clicked should take me to Page1Fragment? then with workable similar operation, i will be fine to create other buttons

This is what i did in MainActivity.java

Tips3 = (Button)findViewById(R.id.mybtn1);
        Tips3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Fragment fragment= new Page1Fragment();
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.replace(R.id.container, fragment); 
                transaction.addToBackStack(null);  
                transaction.commit();
            }
        });

The button from activity_main.xml

 <Button
            android:id="@+id/mybtn1"
            style="?buttonBarButtonStyle"
            android:layout_width="300dp"
            android:layout_height="40dp"
            android:layout_marginTop="13dp"
            android:layout_weight="1"
            android:layout_gravity="center"
            android:text="The Preparation"
            android:textColor="#ffffff"
            android:textSize="17sp"
            android:textStyle="bold" />

This is my Page1Fragment.java

private static final String TAG = "Page1Fragment ----- ; ";
    // Store instance variables
    private String title;
    private int page;
    private ConsentForm form;


    //Store instance variables based on arguments passed
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        page = getArguments().getInt("SomeInt", 1);
        title = getArguments().getString("someTitle");
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_page1, container, false);


        // set the html content for TextView
        TextView newTextView = (TextView) v.findViewById(R.id.Tv1);
        newTextView.setText(Html.fromHtml(getString(R.string.htmlFormattedText1)));
        return v;
    }
    

    // newInstance constructor for creating fragments with arguments
    public static Page1Fragment newInstance(int page, String title) {
        Page1Fragment Page1Fragment = new Page1Fragment();
        Bundle args = new Bundle();
        args.putInt("someInt", page);
        args.putString("someTitle", title);
        Page1Fragment.setArguments(args);
        return Page1Fragment;
    }
}

This is the Activity hosting all the fragments with the aid of adapter tips_4.xml

 public class Tips_4 extends AppCompatActivity {
    Toolbar toolbar;
    TabLayout tabLayout;
    ViewPager viewPager;
    Button Tips3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tips_4);

        //--------add click listener here ----------------------
        Tips3 = (Button)findViewById(R.id.mybtn1);
        Tips3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Fragment fragment= new Page1Fragment();
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.replace(R.id.container, fragment);
                transaction.addToBackStack(null);
                transaction.commit();
            }
        });

        toolbar= findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);

        ViewPager viewPager= (ViewPager) findViewById(R.id.view_pager);
        viewPager.setAdapter(new SimpleFragmentPageAdapter(getSupportFragmentManager(),this));

        //Attach the page change listener inside the activity
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            // This method will be invoked when a new page becomes selected
            @Override
            public void onPageSelected(int position) {
                Toast.makeText(Tips_4.this, "Selected Fragment Page:" + position, Toast.LENGTH_SHORT).show();
            }
            // This method will be invoked when the current page is scrolled
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetpixels) {

            }
            // Called when the scroll state changes:
            //SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


        tabLayout= (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.setupWithViewPager(viewPager);


    }

This is the Exception trace

 --------- beginning of crash
2020-07-20 15:58:48.515 15613-15613/com.joseph.advancedmaths E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.joseph.advancedmaths, PID: 15613
    java.lang.IllegalArgumentException: No view found for id 0x7f080067 (com.joseph.advancedmaths:id/container) for fragment Page1Fragment{8075d59 #0 id=0x7f080067}
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1454)
        at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
        at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:802)
        at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
        at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
        at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
        at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
        at androidx.fragment.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6549)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:888)
Joseph
  • 400
  • 4
  • 19
  • 1
    Does this answer your question? [How to open a Fragment on button click from a fragment in Android](https://stackoverflow.com/questions/32700818/how-to-open-a-fragment-on-button-click-from-a-fragment-in-android) – Rex Endozo Jul 20 '20 at 16:41

2 Answers2

0

If you set the click listener after setContentView in the onCreate method of your activity, you should have no problem. You can even do it on the onCreatedView method just in case.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tips_4);

//--------add click listener here ----------------------
    Tips3 = (Button)findViewById(R.id.mybtn1);
    Tips3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Fragment fragment= new Page1Fragment();
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.container, fragment); 
            transaction.addToBackStack(null);  
            transaction.commit();
        }
    });


    toolbar= findViewById(R.id.app_bar);
    setSupportActionBar(toolbar);

    ViewPager viewPager= (ViewPager) findViewById(R.id.view_pager);
    viewPager.setAdapter(new SimpleFragmentPageAdapter(getSupportFragmentManager(),this));

    //Attach the page change listener inside the activity
    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        // This method will be invoked when a new page becomes selected
        @Override
        public void onPageSelected(int position) {
            Toast.makeText(Tips_4.this, "Selected Fragment Page:" + position, Toast.LENGTH_SHORT).show();
        }
        // This method will be invoked when the current page is scrolled
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetpixels) {

        }
        // Called when the scroll state changes:
        //SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });


    tabLayout= (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.setupWithViewPager(viewPager);


}

Try this and let me know how it works out.

Lheonair
  • 468
  • 5
  • 14
  • Sir, i don't get it. I created the button in mainactivity, are you saying i should remove java code from MainActivity.java and place it in the Page1Fragment.java? – Joseph Jul 20 '20 at 14:09
  • Sorry, I copied the wrong class. Now it should be OK. In your Main Activity Class, you did not set your click listener. You have to set if after the setContentView() line of your onCreate method. – Lheonair Jul 20 '20 at 14:14
  • The button refused to listen when clicked. It kept still. The button xml code is in activity_main.xml and its class is MainActivity.java – Joseph Jul 20 '20 at 14:21
  • Can you share the code for you activity updated, please? – Lheonair Jul 20 '20 at 14:23
  • great :) and now, what's the error you're getting on console/logcat? Is it still the same? – Lheonair Jul 20 '20 at 14:30
  • Yes sir. Let me make it clear, i have buttons in MainActivity and the MainActivity is the landing once the app starts. One of the button when clicked starts Tips_4 activity. Now Tips_4 activity is where i have viewpagerwhich with the company of ViewPagerAdapter opens these fragments i want to reach to. Now i want to creating a button that will take me to a particular frament instead of getting to tips_4 and swipe fragments manually. That's how i decided to create a button that will start the fregment to ease of stress of searching – Joseph Jul 20 '20 at 14:38
  • Bottom line is: You have a button in an activity and you want to start a fragment on click. It's ok, I get that :) But remember in your questions to always point to the error. I see in your console you're getting an error in line 49 of your Page1Fragment. Is that error still there? – Lheonair Jul 20 '20 at 14:44
  • No sir there is no error now. i will remove the logcat now in my question. But the issue now is the the button does not respond when clicked. Remeber that the button listener is placed in the Tips_4 activity and the button xml code placed in the Mainactivity, – Joseph Jul 20 '20 at 14:51
0

Well, it looks like the fragment is not showing because params are null.

 public void onClick(View view) {
            Fragment fragment = Page1Fragment.newInstance(1, "Hello");
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.container, fragment); 
            transaction.addToBackStack(null);  
            transaction.commit();
        }

Take a look at this instruction

Fragment fragment = Page1Fragment.newInstance(1, "Hello");