如何处理片段

时间:2018-01-20 19:10:43

标签: android android-fragments onbackpressed

这是我的片段,但我想在按下时处理后退按钮我想对它执行一些操作。

公共类BusinessDetail扩展了Fragment {

    public TextView headlineSecond;
    String headline;        

    public BusinessDetail() {

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_business_detail, container, false);

        headline =getArguments().getString("headline");

        return view;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        headlineSecond = (TextView) view.findViewById(R.id.id_headline_second_business);


        headlineSecond.setText(headline);
    }

    public boolean onBackPressed() {
        Log.d("ashu","back button pressed");
        return false;
    }
}

2 个答案:

答案 0 :(得分:0)

参考这篇文章: Android Fragment Handle back pressed

它涉及按KEY_BACK按下。让我知道它是否有效!

答案 1 :(得分:0)

尝试下面的代码来管理backpress:

 @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        try {
                view.setFocusableInTouchMode(true);
                view.requestFocus();
                view.setOnKeyListener(new View.OnKeyListener() {
                    @Override
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        if (keyCode == KeyEvent.KEYCODE_BACK) {
                              //other stuff
                                return true;
                        }
                        return false;
                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
            }
}