FORUMS
Remove All Ads from XDA

OnClickListener in a Fragment

1 posts
Thanks Meter: 0
 
By CodingLover, Junior Member on 22nd January 2017, 05:30 PM
Post Reply Email Thread
Hi,
I'm new to Android development and I'm developing my first Android app about music that contains two fragments: Home Fragment and Genres Fragment. This app is a school project and it's kinda urgent.

In Genres Fragment, I have four ImageButtons and I want to add some action to them, like when clicking a button, it goes to another fragment

So, in the Java file of that fragment, I already have the code for OnClickListener but I don't know what to put in the case condition of each button.

P.S: I can't post images because is says: "All new users prevented from posting outside links in their message". So, instead of an image, I will post the code.

Code:
public class GenresFragment extends Fragment implements View.OnClickListener{


    public GenresFragment() {

        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_genres, container, false);

        ImageButton rapBtn = (ImageButton)v.findViewById(R.id.RapButton);
        ImageButton popBtn = (ImageButton)v.findViewById(R.id.PopButton);
        ImageButton edmBtn = (ImageButton)v.findViewById(R.id.EDMButton);
        ImageButton rockBtn = (ImageButton)v.findViewById(R.id.RockButton);
        rapBtn.setOnClickListener(this);
        popBtn.setOnClickListener(this);
        edmBtn.setOnClickListener(this);
        rockBtn.setOnClickListener(this);
        return v;
    }

    @Override
    public void onClick(View v) {
            switch (v.getId()) {
                case R.id.RapButton:

                break;
                case R.id.PopButton:

                break;
                case R.id.EDMButton:

                break;
                case R.id.RockButton:

                break;
            }
    }
}
Can you help me with this?
Thank you
6th May 2017, 07:32 PM |#2  
Junior Member
Flag Mohali
Thanks Meter: 0
 
More
Replace the fragment on button click
Hello,

you just need to replace the fragment on button click.

// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack if needed
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

Thanks!
Post Reply Subscribe to Thread

Guest Quick Reply (no urls or BBcode)
Message:
Previous Thread Next Thread
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes