如何从活动中调用片段方法

时间:2017-02-13 00:18:36

标签: android android-fragments android-viewpager android-tablayout

我在tablayout中填充片段。我的一个片段中有一个方法,我想从一个活动中调用它。但是,当我尝试通过这样做Fragment myFragment = (Fragment ) getSupportFragmentManager().findFragmentById(R.id.my_fragment)来引用片段时, myFragment 为空。我是android的新手。 (抱歉英语不好)

到目前为止我的代码。

public class DashboardActivity extends AppCompatActivity {

    private ViewPager pager;
    private TabLayout tabLayout;
    private Toolbar dashboardToolbar;

    public static int position;

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

        HomeFragment myFragment = new HomeFragment ();
        if(getSupportFragmentManager().findFragmentById(R.id.homeFragment) == null) {
                       getSupportFragmentManager().beginTransaction()
                    .add(R.id.homeFragment, myFragment).commit();

        }


        pager = (ViewPager) findViewById(R.id.view_pager);
        setupViewPager(pager);

        tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.setupWithViewPager(pager);

        pager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
               // Toast.makeText(DashboardActivity.this, "tabSelected:  " + tab.getText()+" "+ tab.getPosition(), Toast.LENGTH_SHORT).show();
                // no where in the code it is defined what will happen when tab is tapped/selected by the user
                // this is why the following line is necessary
                // we need to manually set the correct fragment when a tab is selected/tapped
                // and this is the problem in your code
               pager.setCurrentItem(tab.getPosition());
               position = tab.getPosition();

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
              //  Toast.makeText(DashboardActivity.this, "tabReSelected:  " + tab.getText(), Toast.LENGTH_SHORT).show();

                position = tab.getPosition();

                // Reload your recyclerView here
            }
        });


    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new HomeFragment(), "FOR YOU");
        adapter.addFragment(new NotificationFragment(), "NOTIF");
        adapter.addFragment(new ChatFragment(), "CHAT");
        adapter.addFragment(new ProfileFragment(), "PROFILE");
        viewPager.setAdapter(adapter);
    }

}

片段

  public class HomeFragment extends Fragment {
        // Objects Declaration


        public HomeFragment() {
            // Required empty public constructor
        }


        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.homeFragment, container, false);
        }

public void myMethod(){ //method to be called
//do something
}
     }

活动

public class MyActivity extends AppCompatActivity {



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


                HomeFragment myFragment= (HomeFragment ) getSupportFragmentManager().findFragmentById(R.id.homeFragment);

                    if(myFragment!= null) {
                        Toast.makeText(ActivityFilter.this, "Not null.", Toast.LENGTH_SHORT).show();
 home.myMethod(); // this line is not accessed since myFragment is null

                    }else{
                        Toast.makeText(ActivityFilter.this, "Null fragment.", Toast.LENGTH_SHORT).show();
                    }

    }

}

1 个答案:

答案 0 :(得分:1)

您应该使用回拨。

在片段中创建一个公共接口。

private iCommunicateListener listener;
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    // This makes sure that the container activity has implemented
    // the callback interface. If not, it throws an exception
    try {
        listener = (iCommunicateListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement iCommunicateListener");
    }
}

您还必须将活动作为听众。 (你可以有很多听众,但片段应该是可重用的,所以如果你有很多听众,它将不会像它可能的那样可以重复使用)

listener.communicate("doSomething");

现在你有了积极的倾听者。 在您的onClicks或您希望向活动发送信息时,您必须致电foos.map { |foo| {foo => foos.count(foo)} }.uniq

您的活动必须实现iCommunicateListener。

在实现方法通信之后,您可以为不同的字符串选择逻辑或者通过回调发送任何内容。 活动和片段之间还有很多其他的交流方式,但是因为你只是开始学习这个。实现它之后,你会看到结果,你可以看看这个库,它肯定会帮助你进行android开发。 EventBus

使用EventBus,你不必使用回调,这将使你的碎片更加可重用和灵活,但首先要学习正常的回调。这是一个基本模式,您将在许多不同的情况下使用它。 有关碎片的更多信息:Fragments 希望这有帮助!