Finley Smith
Finley Smith

Reputation: 1617

How to run code on a button click in android fragment

I need help trying to make a app work. I set up a multitab interface using fragments(so it there are 4 tabs with diffrent contents) On the fragment i am working on i want to have 3 buttons which run a intent like this:

    Log.i(TAG, "Website Clicked");
            Intent websiteBrowserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://stackoverflow.com/"));
            startActivity(websiteBrowserIntent);

So i have 3 buttons, heres the .xml:

XML does not seem to work for some reason heres a pastebin: http://pastebin.com/gGuh7qb2

And here is TopRatedFragment.java:

package com.bordengrammar.bordengrammarapp;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class TopRatedFragment extends Fragment {

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

        View rootView = inflater.inflate(R.layout.fragment_top_rated, container,         false);

        return rootView;
    }
}

Upvotes: 3

Views: 30434

Answers (1)

Joel Fernandes
Joel Fernandes

Reputation: 4856

public class TopRatedFragment extends Fragment implements OnClickListener {

    Button btn;

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

        View rootView = inflater.inflate(R.layout.fragment_top_rated, container,         false);

        btn = (Button) rootView.findViewById(R.id.myButton);
        btn.setOnClickListener(this);
        return rootView;
    }

    @Override
    public void onClick(View v) {
        // implements your things
    }
}

P.S. A little search can get you answers.

[EDIT]

public class TopRatedFragment extends Fragment implements OnClickListener {

            Button btn;

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

                View rootView = inflater.inflate(R.layout.fragment_top_rated, container,         false);

                btn = (Button) rootView.findViewById(R.id.myButton);
                btn.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {



                    }
                });
                return rootView;
            }

Please read some tutorials - http://www.vogella.com/articles/AndroidFragments/article.html

Upvotes: 14

Related Questions