简体   繁体   English

Activity 可以访问 Fragment 以了解是否已按下按钮?

[英]Can an Activity access a Fragment to know if a button has been pressed?

The Objective: I'm trying to make a notepad application.目标:我正在尝试制作记事本应用程序。 What my app does is, a button is pressed to create a new note.我的应用程序所做的是,按下一个按钮来创建一个新笔记。 This pops up a fragment in which the user types his note.这会弹出一个片段,用户在其中键入他的笔记。 Within the same fragment, I have another button that signifies when the user is done typing.在同一个片段中,我还有另一个按钮,表示用户何时完成输入。

Question 1: Is there a way by which pressing the other button in the Fragment could trigger a method in my Activity?问题1:有没有办法按下片段中的另一个按钮可以触发我的活动中的方法?

Question 2: Would this cause the app to become too bloated?问题2:这会不会导致应用变得过于臃肿? Should I keep the button within my activity itself?我应该将按钮保留在我的活动中吗?

Thank you for your help.谢谢您的帮助。

There is an easy way of doing this as your fragments have access to activity (Kotlin) |有一种简单的方法可以做到这一点,因为您的片段可以访问activity (Kotlin) | getActivity() (Java) and by casting it you can use it. getActivity() (Java) 并通过转换它可以使用它。 But this is not the proper way of doing this because it affects the modularity of fragments.但这不是正确的做法,因为它会影响片段的模块化

The proper way of doing this:这样做的正确方法:

Your activity wants to listen to Fragments events without any overhead:您的活动想要在没有任何开销的情况下收听 Fragments 事件:

In Fragment在片段中

class MyFragment : Fragment() {

    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is MyFragment.Listener) {
            listener = context
        } else {
            throw ClassCastException(context.toString() + " You need to implement MyFragment.Listener")
        }
    }


    interface Listener {
        fun onSomethingHappened()
    }

    private var listener: MyFragment.Listener? = null

    fun aMethodInsideFragmentThatHandlesButtonEvents() {
        listener?.onSomethingHappened()
    }
}

And in your activity:在您的活动中:

class MyActivity : AppCompatActivity(), MyFragment.Listener {
    override void onSomethingHappened() {
        // do your work here
    }

    ...
}

Question 1: Is there a way by which pressing the other button in the Fragment could trigger a method in my Activity?问题1:有没有办法按下片段中的另一个按钮可以触发我的活动中的方法?

Sure, the simplest way to do it is:当然,最简单的方法是:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    val binding = MyFragmentBinding.bind(view) // viewBinding enabled

    binding.myButton.setOnClickListener {
        (requireActivity() as MyActivity).doSomething() // <--
    }
}

However, if this Fragment can be used in different Activity instances, then it should expose a Listener with which it exposes its potential events, and doesn't need to know the actual Activity instance it is talking to.但是,如果这个 Fragment 可以在不同的 Activity 实例中使用,那么它应该公开一个 Listener,通过它公开它的潜在事件,并且不需要知道它正在与之交谈的实际 Activity 实例。

interface ActionHandler {
    fun onMyButtonClicked()
}

lateinit var actionHandler: ActionHandler

override fun onAttach(context: Context) {
    super.onAttach(context)
    actionHandler = context as ActionHandler
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    val binding = MyFragmentBinding.bind(view) // viewBinding enabled

    binding.myButton.setOnClickListener {
        actionHandler.onMyButtonClicked()
    }
}

This way, your Fragment will always have a listener to talk to even after config changes / process death, which seems to not be the case for most other answers here.这样,即使在配置更改/进程死亡之后,您的 Fragment 也将始终有一个可以与之交谈的侦听器,这对于此处的大多数其他答案似乎并非如此。

Question 2: Would this cause the app to become too bloated?问题2:这会不会导致应用变得过于臃肿? Should I keep the button within my activity itself?我应该将按钮保留在我的活动中吗?

This depends on whether the button actually belongs in the Activity, though it probably doesn't.这取决于按钮是否真正属于 Activity,尽管它可能不属于。 Most modern apps are written as single-Activity anyway, and unless the view is shared among all screens, it's put inside a Fragment, possibly maybe even using <include tags from a common layout resource.无论如何,大多数现代应用程序都是作为单 Activity 编写的,除非视图在所有屏幕之间共享,否则它会放在 Fragment 中,甚至可能使用来自通用布局资源的<include标记。

For triggering a method on click of a button in fragment, there are number of ways to achieve this.为了触发在片段中单击按钮的方法,有多种方法可以实现这一点。 Try this.尝试这个。

If (getActivity() instanceof MainActivity){
     //Getting instance of your activity
     MainActivity instance = ((MainActivity)getActivity());
     //Using the instance calling the method in your activity
     instance.methodName();
}

Use the above code in your fragment on button click.单击按钮时在片段中使用上述代码。

Another way is using Interface , calling its abstract methods in fragment and overriding it MainActivity;另一种方法是使用Interface ,在片段中调用它的抽象方法并覆盖它 MainActivity; on button click those methods will be called.在按钮上单击这些方法将被调用。

Or you can also try using RxEventBus .或者您也可以尝试使用RxEventBus You can publish it in the fragment and listen in the MainActivity.您可以在片段中发布它并在 MainActivity 中监听。

Hope this resolves your issue.希望这能解决您的问题。

Just make your activity implement View.OnClickListener and on your fragment set your activity as onClickListener of your button.只需让您的活动实现View.OnClickListener并在您的片段上将您的活动设置为按钮的onClickListener

your fragment:你的片段:

   @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        myButton.setOnclickListener((MyActivity)getActivity));
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM