我已经通过在xml中设置onclick解决了该问题。还是谢谢你。
我正在尝试通过片段中的按钮来打开活动。但这似乎不适用于我在网上搜索过的代码。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.view2, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
button = (Button) getActivity().findViewById(R.id.sys_file);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "success2", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getActivity(), system_file_visit_control.class));
}
});
}
答案 0 :(得分:1)
尝试将此代码移至onViewCreated
方法。
赞:
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
button = (Button) view.findViewById(R.id.sys_file);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "success2", Toast.LENGTH_SHORT).show();
getContext().startActivity(new Intent(getContext(), system_file_visit_control.class));
}
});
}
如果system_file_visit_control
是一个活动,则在按下按钮后它将移至该活动。
答案 1 :(得分:0)
这可能会帮助您,用此替换您的代码
private View v;
private Context mContext;
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
mContext = context;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v= inflater.inflate(R.layout.fragment_test, container, false);
return v;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
button = (Button) v.findViewById(R.id.sys_file);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "success2", Toast.LENGTH_SHORT).show();
startActivity(new Intent(mContext, system_file_visit_control.class));
}
});
}
答案 2 :(得分:0)
您可以通过以下方式修改onCreateView:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.view2, container, false);
button = (Button) rootView.findViewById(R.id.sys_file);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//Start your activity
}
});
return rootView;
}