所以,我最近参与了片段并学习了如何使用buttonClick来回调和与活动进行通信。直到最近,我一直在使用我的回调执行单一功能。但现在,我想用它执行不止一种活动。基本上,回调'itemListener用于切换从左到右动画的片段。现在引入了另一个按钮,以相反的方向切换片段,因此任何有关如何执行此操作的建议都将非常感激。这是我的代码:
public class ExamFragment extends Fragment{
private static OnItemClickedListener sDummyCallbacks = new OnItemClickedListener() {
@Override
public void OnItemClicked(Parameters params) {
}
};
OnItemClickedListener mListener = sDummyCallbacks;
private Button nextButton, prevButton;
// firstly, create the interface
public interface OnItemClickedListener {
public void OnItemClicked(Parameters params);
}
//To ensure that the host activity implements the interface
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnItemClickedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnItemClickedListener");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_exam_fragment, container,
false);
nextButton = (Button) view.findViewById(R.id.nextButton);
prevButton = (Button) view.findViewById(R.id.prevButton);
nextButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mListener.OnItemClicked(null);
++num;
}
});
prevButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mListener.OnItemClicked(null);
--num;
}
});
return view;
}
这是我的活动
public class ExamActivity extends Activity implements ExamFragment.OnItemClickedListener{
Fragment my = new ExamFragment();
private int time;
private boolean timerHasStarted = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exam);
lockRotation();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.your_placeholder, my);
transaction.commit();
}
@Override
public void OnItemClicked(Parameters recieveparams) {
my = new ExamFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.animator.enter_anim, R.animator.exit_anim);
transaction.replace(R.id.your_placeholder, my);
transaction.addToBackStack(null);
transaction.commit();
}
}
下一个按钮执行代码中显示的动画,但前一个按钮意味着在相反的方向上执行,引入静态变量可以帮助我确定单击了哪个按钮,但我不喜欢静态,我觉得这是一个更好的方法。对不起,如果我的问题仍然太模糊。