-1

First of all, forgive me if this is a silly question because I am relatively new in this field. So basically, I have an activity which contains a fragment. This fragment has three buttons. And when any of this buttons are clicked, I wanted to display specific Toast messages. I used the onClick() method which works fine in an activity. But when I use the same in a fragment, the app crashes. Please help me in this regard.Name of the Activity is "User.java" and its XML file is "activity_user.xml". Name of Fragment "user_home.java" and its xml file is "user_home_layout.xml".
I have attached two images, first one contains the activity and its XML file while the second one contains the fragment and its sml file.

1.Activity 2.Fragment

Yagami Light
  • 1,756
  • 4
  • 19
  • 39
Tony Mathew
  • 880
  • 1
  • 12
  • 35
  • 1
    Could you post your stack trace of the app crash? – nstosic Jul 28 '16 at 08:32
  • There can be atleast two possible reasons for the crash. 1) `buttonInFragment = (Button) view.findViewById(R.id.buttonInFragment);` `buttonInActivity = (Button) findViewById(R.id.buttonActivity);` `Toast.makeText(MainActivity.this, "Toast for activity", Toast.Length_Short).show()` `Toast.makeText(getActivity(), "Toast for Fragment", Toast.Length_Short).show()` – Geet Choubey Jul 28 '16 at 08:38
  • @NitroNbg: This is the error that I get: 'java.lang.IllegalStateException: Could not find method ButtonClick(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'GOT'' – Tony Mathew Jul 28 '16 at 10:10
  • http://stackoverflow.com/questions/6091194/how-to-handle-button-clicks-using-the-xml-onclick-within-fragments – Shayan Pourvatan Jul 28 '16 at 10:14

6 Answers6

4

You dint find button in your fragment,

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.user_home_layout, container, false);

    btn1=(Button)view.findViewById(R.id.GOT);  
    btn2=(Button)view.findViewById(R.id.SH);  
    btn3=(Button)view.findViewById(R.id.TD);

return view;
}

and then implement click listener and and in Toast just use getActivity()

Toast.makeText(getActivity(), "Game Of Thrones", Toast.LENGTH_SHORT).show();

Implement method

public void ButtonClick(View v) {
switch(v.getId()) {

 case R.id.GOT:


  Toast.makeText(getActivity(), "Game of Thornes", Toast.LENGTH_LONG).show();

   break;


 case R.id.SH:


  Toast.makeText(getActivity(), "Sherlock", Toast.LENGTH_LONG).show();

   break;


 case R.id.TD:


  Toast.makeText(getActivity(), "True Detective", Toast.LENGTH_LONG).show();

   break;
   }
 }    
Aditya Vyas-Lakhan
  • 13,409
  • 16
  • 61
  • 96
3

You need to set a custom OnClickListener to your button :

yourButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(), "your toast text", Toast.LENGTH_LONG).show();
            }
        });
Lubomir Babev
  • 1,892
  • 1
  • 12
  • 14
1

In your activity:

Toast.makeText(YourActivity.this, "your message", Toast.LENGTH_SHORT).show();

In your Fragment:

Toast.makeText(this.getActivity(), "your message", Toast.LENGTH_SHORT).show();
chris
  • 19
  • 3
1

@TonyMathew, welcome to the Android world. Your implementation of ButtonClick is wrong. This is an extensive tutorial of how you should use Fragments. There is an example of handling click events as well. Long story short, you need to find your buttons in your fragment xml layout by id. DON'T USE BUTTON'S TEXT!

Please, search the web for info, before posting a question here. The chances are that you will find what you are looking for!

P.S. Usually in Java you should name your class in the following way: ClassName.java and not class_name.java

Todor Kostov
  • 1,789
  • 1
  • 13
  • 20
  • First thing I want to point out is that this answer should be definitely a comment and the second this is that there is no problem in finding the button by name. – Iulian Popescu Jul 28 '16 at 09:25
  • @Todor Kostov: The fact is that I'm pretty much confused on handling button clicks. – Tony Mathew Jul 28 '16 at 10:17
  • @lulian Popescu, first of all, the answer should not be a comment, based on the fact that it provides useful information regarding the question and second - there is a big problem when using the label of a button for identification. What will happen when you try to localize your app? If you have the following "Continue" (English) & "Продължи" (Bulgarian translation) as text for the same button, your logic won't work! – Todor Kostov Jul 28 '16 at 11:04
  • Sorry for this, but I just can't see any useful information for the question (everything you're saying is that the implementation is wrong with an url which should teach you how to fix that code), things that could be in a comment. About the identification of a button, I do agree that in the case of localization might be some problems, but they are easy to fix if the strings are loaded from the `strings.xml` and not hardcoded in text. – Iulian Popescu Jul 28 '16 at 12:33
  • @lulian Popescu, loading the strings from **strings.xml** sounds like a possible solution as long as you don't have two or more buttons with the same text. IDs are unique, thus it is always better to use them. – Todor Kostov Jul 28 '16 at 13:30
  • Not always the IDs are unique, you can use the same id multiple times – Iulian Popescu Jul 28 '16 at 13:38
  • You can not use the same id twice in the same layout. – Todor Kostov Jul 28 '16 at 13:46
  • To be honest, I do not know why the same ID can be used multiple times in the same layout, but I know for sure that it can be used without a single problem. – Iulian Popescu Jul 28 '16 at 13:58
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/118552/discussion-between-todor-kostov-and-iulian-popescu). – Todor Kostov Jul 28 '16 at 14:01
1

Just put getActivity() in the context of makeText() like this :

Toast.makeText(getActivity(), "Your message", Toast.LENGTH_SHORT).show();
Dang Nguyen
  • 354
  • 2
  • 9
1

The problem is that your method is not found in activity, and so, an exception is raised (the methods from fragments doesn't count here). To fix that you have 2 options:

  1. Move the ButtonClick method in activity and do some small changes (you'll have to obtain in a different way the Context) and keep the xml file the same;
  2. Set onClickListener for button and handle the onClick event inside the listener.
Iulian Popescu
  • 2,595
  • 4
  • 23
  • 31