我希望我的按钮能够打开新的活动。我很困惑如何编写代码。我只有一个可以打开新活动的按钮。
答案 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;
}
}
}