简体   繁体   English

如何在android片段中投射视图和调用方法?

[英]How to cast view and invoke method inside android fragment?

I am am trying to create an application which will invoke a method inside an android fragment.我正在尝试创建一个应用程序,它将在 android 片段中调用一个方法。 Inside an Activity we generally cast view and invoke method in the onCreate() method.在 Activity 中,我们通常在onCreate()方法中投射视图和调用方法。

Is there any way to cast view and invoke method inside android fragment?有没有办法在android片段中投射视图和调用方法? In which function call back should this method be invoked?这个方法应该在哪个函数回调中调用?

If you created the fragment using the New -> Fragment(Blank), and chose to create a layout file with it too.如果您使用 New -> Fragment(Blank) 创建片段,并选择使用它创建布局文件。 The view casting should have been done for you in the Fragment.java.视图转换应该在 Fragment.java 中为您完成。 If not, here is how you inflate the fragment onto the activity.如果没有,这里是如何将片段膨胀到活动中。

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //fragment_example is the layout of the fragment
        return inflater.inflate(R.layout.fragment_example, container, false);
    }

To answer your question, you can definitely invoke methods inside android fragments.要回答您的问题,您绝对可以在 android 片段中调用方法。 Where you invoke the functions depends on what you're using them for.调用函数的位置取决于您使用它们的目的。 Many of the functions can be called in很多函数都可以调用

@Override
    public void onStart() {}

Again, if you create the fragment the way I pointed out, these placeholders will have been created already for you in the Fragment.java.同样,如果您按照我指出的方式创建片段,那么这些占位符将已经在 Fragment.java 中为您创建。 Also remember to follow the Fragment, Presenter rule.还要记住遵循 Fragment, Presenter 规则。

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

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