android 如何处理在片段中被压回

7lrncoxx  于 2023-05-12  发布在  Android
关注(0)|答案(2)|浏览(103)

这是我的片段,但我想处理返回按钮时,按下我想执行一些行动。
public class StringName {

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;
    }
}
8hhllhi2

8hhllhi21#

尝试下面的代码来管理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();
            }
}
ztigrdn8

ztigrdn82#

参考这篇文章:Android Fragment Handle back pressed
它涉及在KEY_BACK按下时监听。

相关问题