如何在android中的另一个选项卡中访问控件(视图)?

时间:2015-06-19 04:54:47

标签: android eclipse android-fragments android-tabs oncreate

我在 eclipse 的应用程序中有5个选项卡,我花了很多时间,但现在我遇到了一个大问题:

  

当其中一个标签被激活时,下一个标签和prev标签也会加载   调用onCreated()方法,但我不需要我只需要   切换到标签时调用onCreated()方法

enter image description here

这是我的项目文件

mainActivity.java

package info.androidhive.tabsswipe;
import info.androidhive.tabsswipe.adapter.TabsPagerAdapter;
import ir.zinoo.mankan.R;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.content.SharedPreferences;


public class MainActivity extends FragmentActivity implements ActionBar.TabListener {


    private ViewPager viewPager;
    private TabsPagerAdapter mAdapter;
    private ActionBar actionBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Initilization

        viewPager = (ViewPager) findViewById(R.id.pager);
        actionBar = getActionBar();
        mAdapter = new TabsPagerAdapter(getSupportFragmentManager());



        viewPager.setAdapter(mAdapter);
        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

         //Adding Tabs
        for (String tab_name : tabs) {
            actionBar.addTab(actionBar.newTab().setTabListener(this));
        }
        actionBar.setStackedBackgroundDrawable(new ColorDrawable(Color.parseColor("#333333")));
        actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#333333")));

        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                // on changing the page
                // make respected tab selected
                actionBar.setSelectedNavigationItem(position);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

                }
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {


    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // on tab selected
        // show respected fragment view
        viewPager.setCurrentItem(tab.getPosition());

    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {

    }
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

tabPagerAdapter.java

package info.androidhive.tabsswipe.adapter;

import info.androidhive.tabsswipe.BmiFragment;
import info.androidhive.tabsswipe.CaloriFragment;
import info.androidhive.tabsswipe.FatFragment;
import info.androidhive.tabsswipe.KamarFragment;
import info.androidhive.tabsswipe.OstokhanFragment;
import info.androidhive.tabsswipe.OtherFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class TabsPagerAdapter extends FragmentPagerAdapter {

    public TabsPagerAdapter(FragmentManager fm) {
        super(fm);
    }
    @Override
    public Fragment getItem(int index) {

        switch (index) {
        case 0:
            // Top Rated fragment activity
            return new BmiFragment();
        case 1:
            // Games fragment activity
            return new CaloriFragment();
        case 2:
            // Movies fragment activity
            return new KamarFragment();
        case 3:
            // Movies fragment activity
            return new OstokhanFragment();
        case 4:
            // Movies fragment activity
            return new FatFragment();
        case 5:
            // Movies fragment activity
            return new OtherFragment();
        }

        return null;
    }

    @Override
    public int getCount() {
         //get item count - equal to number of tabs
        return 6;
    }

}

现在我的问题是如何在切换到特殊标签时避免调用其他标签的创建方法?

1 个答案:

答案 0 :(得分:1)

关于FragmentPagerAdapter的Android文档:

  

当有一些通常更多的静态片段被分页时,这个版本的寻呼机最适合使用,例如一组标签。用户访问的每个页面的片段将保留在内存中,但其视图层次结构可能在不可见时被销毁。这可能导致使用大量内存,因为片段实例可以保持任意数量的状态。对于较大的页面集,请考虑FragmentStatePagerAdapter

FragmentStatePagerAdapter:

  

当有大量的寻呼机时,此版本的寻呼机更有用   页面,更像列表视图。当页面不可见时   用户,他们的整个片段可能会被破坏,只保留   保存了该片段的状态。这允许寻呼机保持很多   与每个访问页面相关联的内存较少   FragmentPagerAdapter的代价可能是更多的开销   在页面之间切换。

因此,当您使用FragmentPagerAdapter时,FrgmentManager会在用户使用app时将所有片段添加到内存中。此外,当用户切换到任何页面时,FragmentManager会加载previousnext页面,它会调用您标签的onCreate()

由于您现在有6个标签,可能您想要添加更多标签,FragmentStatePagerAdapter更适合。

为了准确检查用户可以看到哪个片段,您可以执行以下操作:

public class TabsPagerAdapter extends FragmentPagerAdapter {

/* declare fragment objects here globally */
BmiFragment mBmi = new BmiFragment();
CaloriFragment mCalori = new CaloriFragment();
KamarFragment mKamar = new KamarFragment();


public TabsPagerAdapter(FragmentManager fm) {
    super(fm);
}
@Override
public Fragment getItem(int index) {

    switch (index) {
    case 0:
        // Top Rated fragment activity

        mBmi.setUserVisibleHint(false);
        return mBmi;
    case 1:
        // Games fragment activity

        mCalori.setUserVisibleHint(false);
        return mCalori;
    case 2:
        // Movies fragment activity

        mKamar.setUserVisibleHint(false);
        return mKamar;
    /* like this for all case*/
    }

    return null;
}

}

将onPageChangeListener设置为您的Activity:

中的ViewPager
mPager.setOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                // position tab is visible to user
                switch(position) {
                    case 0 :
                        mBmi.setUserVisibleHint(true);
                        break;
                    /* like this for all case */
                 }
            }
        });

覆盖所有片段中的setUserVisibleHint()方法:

public class <Your_Fragment> extends Fragment {
  @Override
  public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        // do something, your fragment is visible
    } else {  
        // your fragment is loaded, but not visible to user currently
    }
  }
}