我是Android的初学者,我正在尝试编写一个简单的应用程序。当进入片段时,单击按钮启动其他片段,为此目的:
@Override
public void onClick(View v) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity(), "Hello", Toast.LENGTH_SHORT).show();
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
secondFragment.removeAllViews();
transaction.replace(R.id.secondFragment, new DashBoardFragment());
transaction.commit();
}
});
}
但是在其他片段开始后显示Hello Toast,但我想在片段开始之前显示。
答案 0 :(得分:3)
在onClick
之后的toasting
中尝试此操作: -
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
secondFragment.removeAllViews();
transaction.replace(R.id.secondFragment, new DashBoardFragment());
transaction.commit();
}
}, Toast.LENGTH_SHORT);
您的片段交易将在1500毫秒后发生(因此您的干杯信息会在交易发生前拍摄)
完整的点击方法......
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Hello", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
secondFragment.removeAllViews();
transaction.replace(R.id.secondFragment, new DashBoardFragment());
transaction.commit();
}
}, Toast.LENGTH_SHORT);
}