如何使用多个按钮从片段类打开新活动?

时间:2016-05-04 20:29:28

标签: android android-intent onclick fragment onclicklistener

我使用滑动菜单从导航抽屉中获得了这个名为BmiFragment的片段活动,我想从中进入一个新的活动,即BmiCalculator.class来执行某些任务,但我无法这样做。我试图通过实现onclicklistener到片段活动来做到这一点。在XML布局中,通过单击它们只需要四个按钮我想打开一个新活动来执行某项任务。请给我一些帮助。 Click here to view for errors

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;

public class BmiFragment extends Fragment implements OnClickListener {

    public BmiFragment() {
    }

    Button btn, btn1, btn2, btn3;

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

        View rootView = inflater.inflate(R.layout.fragment_bmi, container,
                false);
        btn = (Button) rootView.findViewById(R.id.button1);
        btn.setOnClickListener(this);
        btn1 = (Button) rootView.findViewById(R.id.button2);
        btn1.setOnClickListener(this);
        btn2 = (Button) rootView.findViewById(R.id.button3);
        btn2.setOnClickListener(this);
        btn3 = (Button) rootView.findViewById(R.id.button4);
        btn3.setOnClickListener(this);
        return rootView;

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

        case R.id.button1:
        Intent intent = new Intent(this, BmiCalculator.class);//***ERROR: The constructor Intent(BmiFragment, Class<BmiCalculator>) is undefined***//
        startActivity(intent);[enter image description here][1]
        break;

    case R.id.button2:

        break;

    case R.id.button3:

        break;
    case R.id.button4:

        break;
    default:
        break;
    }
}

}

1 个答案:

答案 0 :(得分:0)

Intent intent = new Intent(this,BmiCalculator.class); // 错误:构造函数Intent(BmiFragment,Class)未定义 //         startActivity(intent); [在此处输入图像描述]

而不是这个用途

Intent intent = new Intent(getActivity(), BmiCalculator.class);
startActivity(intent);