如何使用不同的按钮在片段内打开新活动?

时间:2017-03-14 09:21:14

标签: java android button fragment

我希望我的按钮能够打开新的活动。我很困惑如何编写代码。我只有一个可以打开新活动的按钮。

1 个答案:

答案 0 :(得分:0)

试试这个

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.profile, container, false);

Button newPage = (Button) v.findViewById(R.id.button2);
newPage.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(getActivity(), FirstActivity.class);
        startActivity(intent);
    }
});

Button newPage1 = (Button) v.findViewById(R.id.button1);
newPage1.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(getActivity(), SecondActivity.class);
        startActivity(intent);
    }
});

Button newPage2 = (Button) v.findViewById(R.id.button3);
newPage2.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(getActivity(), ThirdActivity.class);
        startActivity(intent);
    }
});
return v;

}

另一种方法(Switch和Case)

public class MainActivity extends Fragment implements View.OnClickListener {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.main_activity, container, false);

    Button button1 = (Button) v.findViewById(R.id.button1);
    button1.setOnClickListener(this);
    Button button2 = (Button) v.findViewById(R.id.button2);
    button2.setOnClickListener(this);
    Button button3 = (Button) v.findViewById(R.id.button3);
    button3.setOnClickListener(this);

    return v;
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.button1:
           Intent intent = new Intent(getActivity(),FirstActivity.class);
           startActivity(intent);
            break;
        case R.id.button2:
            // launch Activity2
            break;
        case R.id.button3:
            // launch Activity3
            break;
    }
}

}