android - 如何从android中的另一个访问选项卡中的控件( View )?

标签 android eclipse android-fragments android-tabs oncreate

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

when one of tabs is activated the next tab and prev tab is loading too and onCreated() method is called but i don't need that i need just calling onCreated() method when switching to tabs

enter image description here

这是我的项目文件

ma​​inActivity.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;
    }

}

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

最佳答案

来自关于 FragmentPagerAdapter 的 Android 文档:

This version of the pager is best for use when there are a handful of typically more static fragments to be paged through, such as a set of tabs. The fragment of each page the user visits will be kept in memory, though its view hierarchy may be destroyed when not visible. This can result in using a significant amount of memory since fragment instances can hold on to an arbitrary amount of state. For larger sets of pages, consider FragmentStatePagerAdapter

fragment 状态页面适配器:

This version of the pager is more useful when there are a large number of pages, working more like a list view. When pages are not visible to the user, their entire fragment may be destroyed, only keeping the saved state of that fragment. This allows the pager to hold on to much less memory associated with each visited page as compared to FragmentPagerAdapter at the cost of potentially more overhead when switching between pages.

因此,当您使用 FragmentPagerAdapter 时,FrgmentManager 将在用户使用应用程序时将所有 fragment 添加到内存中。此外,当用户切换到任何页面时,FragmentManager 加载 previousnext 页面,它会调用您的选项卡的 onCreate()

因为你现在有 6 个标签,可能你想添加更多标签,FragmentStatePagerAdapter 更合适。

要准确检查哪个 fragment 对用户可见,您可以这样做:

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;
}

}

从您的 Activity 将 onPageChangeListener 设置为 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 */
                 }
            }
        });

覆盖所有 fragment 中的 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
    }
  }
}

关于android - 如何从android中的另一个访问选项卡中的控件( View )?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30930147/

相关文章:

java - 从 ITreeSelection 获取文件

java - Eclipse 想要运行错误的类

android - 在 Android 中为 Fragment 事务设置 "z"索引或相机的翻转动画

android - 在选项卡布局中看不到我的 cardView

android - 错误 : Program type already present: android. arch.lifecycle.LiveData - 编译错误

android - 将 ViewPager 和 PageTransformer 与 Android API <11 结合使用时出现问题

android - Retrofit、Gson 和一组异构对象

Eclipse 源文件夹与包

Android:隐藏自定义操作栏图标

android - react native -当我使用react-native-ble-manager调用扫描功能时,应用程序崩溃