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

时间:2016-08-01 03:03:55

标签: android android-layout android-fragments android-viewpager fragmentpageradapter

我在活动中有一个活动,PagerAdapter(返回一个片段)和ViewPager。

其他建议使用以下代码

//JournalEntryVC.swift

import UIKit
import Alamofire
import BXProgressHUD
import SwiftyJSON
import RealmSwift


class JournalEntryVC: UIViewController, UITableViewDelegate, UITableViewDataSource {


  func reloadInitialData ( ) {
    
    //mutable arrays containing journal entry attributes
    desc.removeAllObjects()
    type.removeAllObjects()
    category.removeAllObjects()
    metric_stat.removeAllObjects()
    entryImages.removeAllObjects()
    dateCreate.removeAllObjects()
    comments.removeAllObjects()
    entryType.removeAllObjects()
    id.removeAllObjects()
    //comments.removeAllObjects()
    content.removeAllObjects()
    patName.removeAllObjects()
    
    
    let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
    dispatch_async(dispatch_get_global_queue(priority, 0)) {
        let request = Alamofire.request(.GET, "https://gethealthie.com/entries.json", headers: [
            "access-token": userCreds.objectForKey("access-token")! as! String,
            "client": userCreds.objectForKey("client")! as! String,
            "token-type": userCreds.objectForKey("token-type")! as! String,
            "uid": userCreds.objectForKey("uid")! as! String,
            "expiry": userCreds.objectForKey("expiry")! as! String
            ]).responseJSON { response in
                
                print(response.response)
                
                let json = JSON(data: response.data!)
                
                
                if json.count == 0 {
                    BXProgressHUD.hideHUDForView(self.view);
                }else {
                    
                    //Realm- create object instances of Patient and Journal class
                    let newPatient = Patient()
                    let myJournal = Journal()
                    
                    for i in 0 ..< json.count {
                        
                        let entry = json[i]
                        print(entry)
                        
                        let name = entry["entry_comments"]
                        let k = name["id"]
                        
                        //add entry attributes to mutable arrays
                        self.type.addObject(entry["type"].stringValue)
                        self.desc.addObject(entry["description"].stringValue)
                        self.category.addObject(entry["category"].stringValue)
                        self.metric_stat.addObject(entry["metric_stat"].stringValue)
                        self.dateCreate.addObject(entry["created_at"].stringValue)
                        self.comments.addObject(entry["entry_comments"].rawValue)
                        self.entryType.addObject(entry["category"].stringValue)
                        let posterInfo = entry["poster"]
                        let first = posterInfo["first_name"].stringValue
                        let last = posterInfo["last_name"].stringValue
                        let full = first + " " + last
                        self.patName.addObject(full)
                        self.id.addObject(entry["id"].stringValue)
                        self.entryImages.addObject(entry["image_url"].stringValue)
                        
                        
                        //Realm- access properties in Journal class and set it equal to the current journal entry attribute i.e. json[i]
                        myJournal.entryType = entry["type"].stringValue
                        myJournal.entryCaption = entry["description"].stringValue
                        myJournal.entryCategory = entry["category"].stringValue
                        myJournal.metricStat = entry["metric_stat"].stringValue
                        myJournal.entryDate = entry["created_at"].stringValue
                        //  myJournal.entryComment = entry["entry_comments"].rawValue as! String
                        
                        //append a NEW journal entry to the array of journal entries in Patient class i.e. let journalEntries = List<Journal>() as the json loops thru different journal entries
                        newPatient.journalEntries.append(myJournal)
                        
                        if i == json.count - 1 {
                            // do some task
                            dispatch_async(dispatch_get_main_queue()) {
                                self.tableView.reloadData()
                                BXProgressHUD.hideHUDForView(self.view)
                            }
                        }
                        
                    }
                    
                    //Realm- add newPatient object instance to realm
                    try! self.realm.write {
                        self.realm.add(newPatient)
                        
                    }
                }
                
        }
    }
  }

}

但是,我无法找到片段ExampleFragment fragment = (ExampleFragment)getFragmentManager().findFragmentById(R.id.example_fragment); fragment.specific_function_name(); 的参考资料。

这是我的活动

R.id.example_fragment

布局     

public class TestActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


         TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.addTab(tabLayout.newTab().setText("Test1"));
        tabLayout.addTab(tabLayout.newTab().setText("Test2"));
        tabLayout.addTab(tabLayout.newTab().setText("Test3"));
        tabLayout.addTab(tabLayout.newTab().setText("Test4"));
        tabLayout.addTab(tabLayout.newTab().setText("Test5"));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

       viewPager = (ViewPager) findViewById(R.id.pager);
        adapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

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

            }

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

            }
        });

        tabLayout.setScrollPosition(pageIndex,0f,true);
        viewPager.setCurrentItem(pageIndex);
    }
}

PageAdapter的代码

<include
    android:id="@+id/toolbar"
    layout="@layout/toolbar" />

<android.support.v4.widget.DrawerLayout
    android:layout_below="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/main_layout" >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="?attr/actionBarSize"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:tabTextAppearance="@style/menuTheme"
            app:tabIndicatorHeight="4dp"
            app:tabMode="scrollable"
            />
        <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            />

    </LinearLayout>
    <fragment
        android:id="@+id/fragment_navigation_drawer"
        android:name="com.musicplayer.mp3player.activities.FragmentDrawer"
        android:layout_width="@dimen/nav_drawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:layout="@layout/fragment_navigation_drawer"
        tools:layout="@layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>

2 个答案:

答案 0 :(得分:0)

尝试如下:

  // Returns the fragment to display for that page
    @Override
    public Fragment getItem(int position) {
        switch (position) {
        case 0: // Fragment # 0 - This will show FirstFragment
            return TestFragment.newInstance(0, "Page # 1");
        case 1: // Fragment # 0 - This will show FirstFragment different title
            return TestFragment2.newInstance(1, "Page # 2");
        case 2: // Fragment # 1 - This will show SecondFragment
            return TestFragment3.newInstance(2, "Page # 3");
        default:
            return null;
        }
    }

你可以像下面这样获取片段实例:

viewpager.getcurrentItem().yourmethod();

在Fragment Class Make Method中,如下所示:

public static DemoFragment newInstance() {
    return new DemoFragment();
}

答案 1 :(得分:0)

确保片段仅初始化一次:

public class PagerAdapter extends FragmentPagerAdapter {
    int mNumOfTabs;
    TestFragment testFragment, testFragment2, testFragment3, testFragment4, testFragment5;
    public PagerAdapter(FragmentManager fm, int NumOfTabs) {
    super(fm);
    this.mNumOfTabs = NumOfTabs;
    }

    @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0:
                if( testFragment == null ) testFragment = new TestFragment();
                return testFragment;
            case 1:
                if( testFragment2 == null ) testFragment2 = new TestFragment2();
                return testFragment2;
            case 2:
                if( testFragment3 == null ) testFragment3 = new TestFragment3();
                return testFragment3;
            case 3:
                if( testFragment4 == null ) testFragment4 = new TestFragment4();
                return testFragment4;
            case 4:
                if( testFragment5 == null ) testFragment5 = new TestFragment5();
                return testFragment5;
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        return mNumOfTabs;
    }
}

然后调用片段上的方法:

    TestFragment testFragment = (TestFragment) viewpager.getcurrentItem(); 
// in case you are not sure, check using instanceOf to determine the Fragment type
    testFragment.specific_function_name();