【问题标题】:How I can call method in fragment from activity?如何从活动中调用片段中的方法?
【发布时间】:2015-08-23 22:56:08
【问题描述】:

我有主要活动,我想在片段中调用方法我使用 getSupportFragmentManager 获取片段但总是返回 null 给我,你能帮我吗

主活动:

import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBarActivity;

public class MainActivity extends ActionBarActivity implements OnItemPressListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


    }
   public void A()
   {
       FragmentManager fragManager = this.getSupportFragmentManager();
      MainFragment fragment= (MainFragment)fragManager.findFragmentById(R.id.mainfragment);///always Null
       fragment.B();
   }.
}

main_fragment:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/mainfragment"
    tools:context=".mainFragment">
    <GridView
        android:id="@+id/gridview_movie"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"></GridView>
</FrameLayout>

MainFragmet:

import android.support.v4.app.Fragment;;

public class MainFragment extends Fragment {
 public void B() {
///do some thing
}
}

【问题讨论】:

  • 片段是否实际加载到R.id.mainfragment 中?您的MainActivity 中没有任何代码建议您这样做。

标签: android android-fragments


【解决方案1】:

你只需要从主要活动中的片段中获取一个实例

MainFragment fragment=new MainFragment();

【讨论】:

    【解决方案2】:

    我在您的问题中没有看到任何代码表明您曾经实例化 Fragment 并将其加载到 R.id.mainfragment 中。此外,您的main_fragment.xml 文件包含带有match_parent 参数的GridView。如果您打算将片段加载到R.id.mainfragment,这是没有意义的,因为您的GridView 只会掩盖它。

    考虑到这一点,我将对您的代码进行以下更正。

    1. 从您的 layout 文件中删除您的 GridView

      <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:id="@+id/mainfragment"
          tools:context=".mainFragment" />
      
    2. MainActivity 中的onCreate() 中添加类似以下内容:

      if(getSupportFragmentManager.findFragmentById(R.id.mainfragment) == null) {
          getSupportFragmentManager()
              .beginTransaction
              .add(R.id.mainfragment, new MainFragment())
              .commit();
      }
      
      //...This can be in onCreate(), or inside a method, to access MainFragment's methods
      MainFragment frag = (MainFragment) getSupportFragmentManager().findFragmentById(R.id.mainfragment);
      if (frag != null) frag.callYourMethodHere();
      

    【讨论】:

    • 如果我从 main_fragment 中删除,我可以在哪里放置 gridView
    • @mohammadtofi 这取决于它的目的,但我的直接想法是,如果你想让它占据整个屏幕,它应该是你的 Fragment 布局的一部分。
    【解决方案3】:

    如果你想使用 findFragmentById... 你必须这样写:

        <fragment
        android:id="@+id/mainfragment"
        class="com.oldfeel.base.BaseFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    

    【讨论】:

    • findFragmentById() 也可以用于动态片段,而不仅仅是静态片段。
    【解决方案4】:

    首先,您还没有在主要活动中实例化您的片段,请尝试以下代码:

    /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.news_articles);
    
            // Check whether the activity is using the layout version with
            // the fragment_container FrameLayout. If so, we must add the first fragment
            if (findViewById(R.id.fragment_container) != null) {
    
                // However, if we're being restored from a previous state,
                // then we don't need to do anything and should return or else
                // we could end up with overlapping fragments.
                if (savedInstanceState != null) {
                    return;
                }
    
                // Create an instance of ExampleFragment
                HeadlinesFragment firstFragment = new HeadlinesFragment();
    
                // In case this activity was started with special instructions from an Intent,
                // pass the Intent's extras to the fragment as arguments
                firstFragment.setArguments(getIntent().getExtras());
    
                // Add the fragment to the 'fragment_container' FrameLayout
                getSupportFragmentManager().beginTransaction()
                        .add(R.id.fragment_container, firstFragment, "myAwesonFragment").commit();
            }
        }
    

    那么如果你的方法 A 执行以下操作

    public void A()
       {
           BrowseFragment fragment = (BrowseFragment) getSupportFragmentManager().findFragmentByTag("myAwesonFragment");
            //Check if the Bottom Sheet is Expanded
            fragment.B();
       }
    

    就是这样,这次它不会为空。当我想定位片段时,我个人总是使用 findFragmentByTag。

    PD:我们使用 getSupportFragmentManager() 是因为您使用的是 android.support.v4.app.Fragment 如果您使用 android.app.Fragment 使用 getFragmentManager()

    【讨论】:

      猜你喜欢
      • 2021-12-23
      • 1970-01-01
      • 2013-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-15
      • 1970-01-01
      相关资源
      最近更新 更多