Fragment用handler向Activity发送消息并调用Activity的Handler.Callback


Fragment01中布局一个按钮。点击改按钮向Activity发送消息:隐藏Fragment01,显示Fragment02.


public class MainActivity extends AppCompatActivity implements Handler.Callback{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.fragment01,new Fragment01(),"currentFragment");
        ft.commit();
    }

    @Override
    public boolean handleMessage(Message msg) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();
        if (msg.what==1){
            ft.hide(fragmentManager.findFragmentByTag("currentFragment"));
            ft.add(R.id.fragment01,new Fragment02());
            ft.commit();
        }
        return false;
    }
}

public class Fragment01 extends Fragment {
    Handler.Callback callback;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment,container,false);
    }

    //获取Fragment依附的activity
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.callback= (Handler.Callback) activity;
    }

    @Override
    public void onStart() {
        super.onStart();
        Fragment fragment = getFragmentManager().findFragmentById(R.id.fragment01);
        View view = fragment.getView();
        Button button = (Button) view.findViewById(R.id.begin);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Handler handler = new Handler(callback);
                Message message = Message.obtain();
                message.what=1;
                handler.sendMessage(message);
            }
        });
    }
}

public class Fragment02 extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment02,container,false);
    }
}


阅读更多
文章标签: handler Handler.Callback
个人分类: android
下一篇python学习笔记5-创建一个webapp
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭