如何从一个活动引用片段的方法呢? [英] How to reference a fragment's methods from an activity?

查看:194
本文介绍了如何从一个活动引用片段的方法呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我有3个片段工作的一个viewpager应用程序。

 

:我通过类似的FragmentStatePagerAdapter动态添加的片段

 公共类ViewPagerAdapter扩展FragmentStatePagerAdapter {CharSequence的标题[]; //这将存储的选项卡这将会创建ViewPagerAdapter时传递的标题
INT NumbOfTabs; //存储标签的数量,创建ViewPagerAdapter若这也将被传递
//建立一个构造函数和分配的值传递给适当的值在类
公共ViewPagerAdapter(FragmentManager FM,CharSequence的mTitles [],诠释mNumbOfTabsumb){
    超(FM);    this.Titles = mTitles;
    this.NumbOfTabs = mNumbOfTabsumb;}//此方法返回的片段在查看传呼机的每个位置
@覆盖
公共片段的getItem(INT位置){    如果(位置== 0)//如果位置是0,我们正在返回的第一个选项卡
    {
        Current_forecast_fragment current_forecast_fragment =新Current_forecast_fragment();
        返回current_forecast_fragment;
    }
    否则,如果(位置== 1)//因为我们有2个选项卡,如果现在的位置是0它必须是1,所以我们正在返回第二个标签
    {
        返回新Hourly_forecast_fragment();
    }其他{
        返回新Daily_forecast_fragment();
    }}//此方法返回的标题为标签在标签栏@覆盖
公共CharSequence的getPageTitle(INT位置){
    回到标题[位置]
}//此方法返回标签的数量的标签条@覆盖
公众诠释的getCount(){
    返回NumbOfTabs;
}
}

我如何引用片段,可以说从我的主要活动根据目前的预测呢?我想类似的东西,但我需要的片段ID来引用它。有什么建议?

 公共类MainActivity扩展AppCompatActivity {
ViewPager寻呼机;
ViewPagerAdapter适配器;
SlidingTabLayout标签;
CharSequence的标题[] = {当前,每小时,人民日报};
INT Numboftabs = 3;
Current_forecast_fragment mCurrent_forecast_fragment;公共静态最后的字符串标记= MainActivity.class.getSimpleName();
公共静态最后弦乐LOCATION_KEY =location_key;
公共预测mForecast;
公共静态最后弦乐DAILY_FORECAST =DAILY_FORECAST;
公共静态最后弦乐HOURLY_FORECAST =HOURLY_FORECAST;
//默认坐标 - 戈采代尔切夫,英国拉逖:57.156866;长:
私人双重纬度= 41.5667;
私人双人经度= 23.7333;
私人的LocationManager的LocationManager;
@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);
    // -----------我的code从这里开始-----------------    mCurrent_forecast_fragment =(Current_forecast_fragment)getSupportFragmentManager()findFragmentById(R.id ??????);
    //Log.d(MainActivity,mCurrent_forecast_fragment.getTag()+的Georgi);
    的getLocation();    //创建ViewPagerAdapter和传递段管理器,光纤收发器的标题标签和数目的标签。
    适配器=新ViewPagerAdapter(getSupportFragmentManager(),标题,Numboftabs);    //分配ViewPager查看和设置适配器
    寻呼机=(ViewPager)findViewById(R.id.pager);
    pager.setAdapter(适配器);    // Assiging滑动标签布局视图
    标签=(SlidingTabLayout)findViewById(R.id.tabs);
    tabs.setDistributeEvenly(真); //为了使固定设置这个真实的标签,这让标签间距相等的有效幅宽    //设置自定义颜色的标签视图的滚动栏
    tabs.setCustomTabColorizer(新SlidingTabLayout.TabColorizer(){
        @覆盖
        公众诠释getIndicatorColor(INT位置){
            返回getResources()的getColor(R.color.tabsScrollColor)。
        }
    });    //设置ViewPager对于SlidingTabsLayout
    tabs.setViewPager(寻呼机);
}
}


解决方案

很多实验我来用一个简单的解决我的问题后。由于我在XML动态(在viewPagerAdapter),并且不添加片段我不能用ID或标签引用它们weither。我的解决方案,使其存储作为参数传递的片段的引用稍微修改适配器。然后,所有的片段的方法可访问在MainActivity(如果declired公共):

MainActivity:

 公共类MainActivity扩展AppCompatActivity {
ViewPager寻呼机;
ViewPagerAdapter适配器;
SlidingTabLayout标签;
CharSequence的标题[] = {当前,每小时,人民日报};
INT Numboftabs = 3;
Current_forecast_fragment mCurrent_forecast_fragment;@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);
    // -----------我的code从这里开始-----------------
    this.mCurrent_forecast_fragment =新Current_forecast_fragment();    //创建ViewPagerAdapter和传递段管理器,光纤收发器的标题标签和数目的标签。
    适配器=新ViewPagerAdapter(getSupportFragmentManager(),标题,Numboftabs,mCurrent_forecast_fragment);    //分配ViewPager查看和设置适配器
    寻呼机=(ViewPager)findViewById(R.id.pager);
    pager.setOffscreenPageLimit(3);
    pager.setAdapter(适配器);    // Assiging滑动标签布局视图
    标签=(SlidingTabLayout)findViewById(R.id.tabs);
    tabs.setDistributeEvenly(真); //为了使固定设置这个真实的标签,这让标签间距相等的有效幅宽    //设置自定义颜色的标签视图的滚动栏
    tabs.setCustomTabColorizer(新SlidingTabLayout.TabColorizer(){
        @覆盖
        公众诠释getIndicatorColor(INT位置){
            返回getResources()的getColor(R.color.tabsScrollColor)。
        }
    });    //设置ViewPager对于SlidingTabsLayout
    tabs.setViewPager(寻呼机);
}

我的code在ViewPagerAdapter:

 公共类ViewPagerAdapter扩展FragmentStatePagerAdapter {
私人Current_forecast_fragment mCurrent_forecast_fragment;
CharSequence的标题[]; //这将存储的选项卡这将会创建ViewPagerAdapter时传递的标题
INT NumbOfTabs; //存储标签的数量,创建ViewPagerAdapter若这也将被传递
//建立一个构造函数和分配的值传递给适当的值在类
公共ViewPagerAdapter(FragmentManager FM,CharSequence的mTitles [],INT mNumbOfTabsumb,Current_forecast_fragment current_fragment){
    超(FM);
    this.mCurrent_forecast_fragment = current_fragment;
    this.Titles = mTitles;
    this.NumbOfTabs = mNumbOfTabsumb;}//此方法返回的片段在查看传呼机的每个位置
@覆盖
公共片段的getItem(INT位置){    如果(位置== 0)//如果位置是0,我们正在返回的第一个选项卡
    {
        返回this.mCurrent_forecast_fragment;
    }
    否则,如果(位置== 1)//因为我们有2个选项卡,如果现在的位置是0它必须是1,所以我们正在返回第二个标签
    {
        返回新Hourly_forecast_fragment();
    }其他{
        返回新Daily_forecast_fragment();
    }}
}

I have a viewpager app that I am working on with 3 fragments. I am adding the fragments dynamically via the FragmentStatePagerAdapter like that:

public class ViewPagerAdapter extends FragmentStatePagerAdapter {

CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created


// Build a Constructor and assign the passed Values to appropriate values in the class
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
    super(fm);

    this.Titles = mTitles;
    this.NumbOfTabs = mNumbOfTabsumb;

}

//This method return the fragment for the every position in the View Pager
@Override
public Fragment getItem(int position) {

    if(position == 0) // if the position is 0 we are returning the First tab
    {
        Current_forecast_fragment current_forecast_fragment = new Current_forecast_fragment();
        return current_forecast_fragment;
    }
    else if (position == 1)            // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab
    {
        return new Hourly_forecast_fragment();
    }else {
        return new Daily_forecast_fragment();
    }

}

// This method return the titles for the Tabs in the Tab Strip

@Override
public CharSequence getPageTitle(int position) {
    return Titles[position];
}

// This method return the Number of tabs for the tabs Strip

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

How do I reference a fragment, lets say the current forecast one from my main activity? I tried something like that but I need the fragment id to reference it. Any suggestions?:

public class MainActivity extends AppCompatActivity {
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Current","Hourly","Daily"};
int Numboftabs =3;
Current_forecast_fragment mCurrent_forecast_fragment;

public static final String TAG = MainActivity.class.getSimpleName();
public static final String LOCATION_KEY = "location_key";
public Forecast mForecast;
public static final String DAILY_FORECAST = "DAILY_FORECAST";
public static final String HOURLY_FORECAST = "HOURLY_FORECAST";
//default coordinates - Gotse Delchev, UK Lati:57.156866 ; Long:
private double latitude = 41.5667;
private double longitude = 23.7333;
private LocationManager locationManager;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //-----------MY CODE STARTS HERE-----------------

    mCurrent_forecast_fragment = (Current_forecast_fragment) getSupportFragmentManager().findFragmentById(R.id.??????);
    //Log.d("MainActivity",mCurrent_forecast_fragment.getTag() + "Georgi");
    getLocation();

    // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
    adapter =  new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);

    // Assigning ViewPager View and setting the adapter
    pager = (ViewPager) findViewById(R.id.pager);
    pager.setAdapter(adapter);

    // Assiging the Sliding Tab Layout View
    tabs = (SlidingTabLayout) findViewById(R.id.tabs);
    tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width

    // Setting Custom Color for the Scroll bar indicator of the Tab View
    tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
        @Override
        public int getIndicatorColor(int position) {
            return getResources().getColor(R.color.tabsScrollColor);
        }
    });

    // Setting the ViewPager For the SlidingTabsLayout
    tabs.setViewPager(pager);




}
}

解决方案

After a lot of experimentation I came with a simple solution to my problem. Since I am adding the fragments dynamically (in the viewPagerAdapter) and not in XML I couldn't reference them weither by id or tag. My solution is to modify slightly the adapter so that it stores a reference of the fragment passed as a parameter. Then all of the methods of the fragment are accessible (if declired public) in the mainActivity:

MainActivity:

public class MainActivity extends AppCompatActivity {
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Current","Hourly","Daily"};
int Numboftabs =3;
Current_forecast_fragment mCurrent_forecast_fragment;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //-----------MY CODE STARTS HERE-----------------
    this.mCurrent_forecast_fragment = new Current_forecast_fragment();

    // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
    adapter =  new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs,mCurrent_forecast_fragment);

    // Assigning ViewPager View and setting the adapter
    pager = (ViewPager) findViewById(R.id.pager);
    pager.setOffscreenPageLimit(3);
    pager.setAdapter(adapter);

    // Assiging the Sliding Tab Layout View
    tabs = (SlidingTabLayout) findViewById(R.id.tabs);
    tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width

    // Setting Custom Color for the Scroll bar indicator of the Tab View
    tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
        @Override
        public int getIndicatorColor(int position) {
            return getResources().getColor(R.color.tabsScrollColor);
        }
    });

    // Setting the ViewPager For the SlidingTabsLayout
    tabs.setViewPager(pager);
}

My Code in ViewPagerAdapter:

public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private Current_forecast_fragment mCurrent_forecast_fragment;
CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created


// Build a Constructor and assign the passed Values to appropriate values in the class
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb,Current_forecast_fragment current_fragment) {
    super(fm);
    this.mCurrent_forecast_fragment = current_fragment;
    this.Titles = mTitles;
    this.NumbOfTabs = mNumbOfTabsumb;

}

//This method return the fragment for the every position in the View Pager
@Override
public Fragment getItem(int position) {

    if(position == 0) // if the position is 0 we are returning the First tab
    {
        return this.mCurrent_forecast_fragment;
    }
    else if (position == 1)            // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab
    {
        return new Hourly_forecast_fragment();
    }else {
        return new Daily_forecast_fragment();
    }

}
}

这篇关于如何从一个活动引用片段的方法呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆