如何在android片段中单击按钮上运行代码

时间:2013-12-13 18:58:14

标签: android button android-fragments onclick

我需要帮助才能让应用有效。我使用片段设置了一个multitab接口(所以它有4个不同内容的选项卡)在我正在处理的片段上我想要有3个按钮来运行这样的意图:

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

所以我有3个按钮,继承人.xml:

由于某种原因,XML似乎不能用于下载: http://pastebin.com/gGuh7qb2

这是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;
    }
}

1 个答案:

答案 0 :(得分:10)

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。一点点搜索可以得到答案。

<强> [编辑]

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;
            }

请阅读一些教程 - http://www.vogella.com/articles/AndroidFragments/article.html