关闭

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

标签: handlerHandler.Callback
146人阅读 评论(0) 收藏 举报
分类:

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);
    }
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:152次
    • 积分:11
    • 等级:
    • 排名:千里之外
    • 原创:1篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档