片段的onClick方法片段元素片段、元素、方法、onClick

2023-09-07 15:54:35 作者:天性凉薄﹌

我读到片段相当长的一段文章,但我仍然感到困惑怎么做。

I read quite some articles about fragments, but I am still confused about how to do what.

我有一个MainActivity,它并排显示两个片段的一面。在片段中的一个我有一个按钮,在片段布局XML定义的按钮

I have a MainActivity, which displays two fragments side by side. In one of the fragments I have a button and defined in the fragments layout XML for the button

android:onClick="buttonClicked"

现在我想要实现的方法

public void buttonClicked(View view)  

我会认为这具有在FragmentA.java而不是在MainActivity.java执行。但是,只有当方法在MainActivity.java实施工作。这是为什么?对我来说,没有任何意义。 pre蜂窝属于一个活性的方法留在了该活动,目前在平板电脑上,我合并了许多活动一MainActivity和所有的不同的方法进行合并?无论你把例如在FragmentA.java呢?如果你有,因为这个应用程序的手持设备上运行,开始你的自己的活动,然后onClick的方法有不被在MainActivity但是其中需要被调用,然后活动。我此刻的困惑pretty ...

I would have assumed that this has to be implemented in FragmentA.java and not in MainActivity.java. But it only works if that method is implemented in MainActivity.java. Why is that? To me that doesn't make sense. Pre Honeycomb a method belonging to one activity stayed in that activity, now on a tablet I am merging many activities to one MainActivity and all the different methods are merged? Whatever do you put for example in FragmentA.java then? What if you have to start you an own activity because this app runs on a handheld, then the onClick method has not to be in the MainActivity but in the Activity which needs to be called then. I am pretty confused at the moment...

推荐答案

我不知道具体是什么问题,但也许这会有所帮助。

I'm not sure what the specific problem is, but maybe this will help.

从上片段Android文档取值:

您应该设计每个片段作为一个模块化和可重用活性组分。也就是说,因为每个片段定义自己的布局,并有自己的生命周期回调自身的行为,您可以在多种活动一个片段,所以你应该设计重用,并避免直接从另一个片段操纵一个片段。

You should design each fragment as a modular and reusable activity component. That is, because each fragment defines its own layout and its own behavior with its own lifecycle callbacks, you can include one fragment in multiple activities, so you should design for reuse and avoid directly manipulating one fragment from another fragment.

也就是说,你不应该操纵从另一个片段的片段;更确切地说,这应该通过底层活动来完成。阅读此创建活动回调活动部分的文章了解更多信息(这是很重要的东西!)。

That is, you should never manipulate a fragment from another fragment; rather, this should be done through the underlying Activity. Read the "Creating event callbacks to the activity" section in this article for more information (it's important stuff!!).

在另一方面,如果希望按钮执行片段本身(在动作也就是说,如果你想要一个按钮单击要更改的文本的TextView 的片段)之内,你应该实现这在片段 ,而不是活动(这是因为由此产生的行为是包含在片段中键,无关与父活动)。

On the other hand, if you want the button to perform an action within the Fragment itself (i.e. if you wanted a Button click to change the text of a TextView within the Fragment), you should implement this in the Fragment, not the Activity (this is because the resulting behavior is contained within the Fragment and has nothing to do with the parent Activity).

发表评论,并在我的职务是混乱的,我可以澄清......我最近才开始明白片段的自己:)

Leave a comment and I can clarify if my post is confusing... I only recently began to understand Fragment's myself :).