Example usage for android.widget TabHost setOnTabChangedListener

List of usage examples for android.widget TabHost setOnTabChangedListener

Introduction

In this page you can find the example usage for android.widget TabHost setOnTabChangedListener.

Prototype

public void setOnTabChangedListener(OnTabChangeListener l) 

Source Link

Document

Register a callback to be invoked when the selected state of any of the items in this list changes

Usage

From source file:com.example.android.mediarouter.player.RadioActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    // Be sure to call the super class.
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        mPlayer = (RadioPlayer) savedInstanceState.getSerializable("mPlayer");
    }/*from   w w  w . j  av  a  2 s. c o  m*/

    // Get the media router service.
    mMediaRouter = MediaRouter.getInstance(this);

    // Create a route selector for the type of routes that we care about.
    mSelector = new MediaRouteSelector.Builder().addControlCategory(MediaControlIntent.CATEGORY_LIVE_AUDIO)
            .addControlCategory(MediaControlIntent.CATEGORY_LIVE_VIDEO)
            .addControlCategory(MediaControlIntent.CATEGORY_REMOTE_PLAYBACK)
            .addControlCategory(SampleMediaRouteProvider.CATEGORY_SAMPLE_ROUTE).build();

    // Add a fragment to take care of media route discovery.
    // This fragment automatically adds or removes a callback whenever the activity
    // is started or stopped.
    FragmentManager fm = getSupportFragmentManager();
    DiscoveryFragment fragment = (DiscoveryFragment) fm.findFragmentByTag(DISCOVERY_FRAGMENT_TAG);
    if (fragment == null) {
        fragment = new DiscoveryFragment(mMediaRouterCB);
        fragment.setRouteSelector(mSelector);
        fm.beginTransaction().add(fragment, DISCOVERY_FRAGMENT_TAG).commit();
    } else {
        fragment.setCallback(mMediaRouterCB);
        fragment.setRouteSelector(mSelector);
    }

    // Populate an array adapter with streaming media items.
    String[] mediaNames = getResources().getStringArray(R.array.media_names);
    String[] mediaUris = getResources().getStringArray(R.array.media_uris);
    mLibraryItems = new LibraryAdapter();
    for (int i = 0; i < mediaNames.length; i++) {
        mLibraryItems.add(new MediaItem("[streaming] " + mediaNames[i], Uri.parse(mediaUris[i]), "video/mp4"));
    }

    // Scan local external storage directory for media files.
    File externalDir = Environment.getExternalStorageDirectory();
    if (externalDir != null) {
        File list[] = externalDir.listFiles();
        if (list != null) {
            for (int i = 0; i < list.length; i++) {
                String filename = list[i].getName();
                if (filename.matches(".*\\.(m4v|mp4)")) {
                    mLibraryItems.add(new MediaItem("[local] " + filename, Uri.fromFile(list[i]), "video/mp4"));
                }
            }
        }
    }

    mPlayListItems = new PlaylistAdapter();

    // Initialize the layout.
    setContentView(R.layout.sample_radio_router);

    TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
    tabHost.setup();
    String tabName = getResources().getString(R.string.library_tab_text);
    TabSpec spec1 = tabHost.newTabSpec(tabName);
    spec1.setContent(R.id.tab1);
    spec1.setIndicator(tabName);

    tabName = getResources().getString(R.string.playlist_tab_text);
    TabSpec spec2 = tabHost.newTabSpec(tabName);
    spec2.setIndicator(tabName);
    spec2.setContent(R.id.tab2);

    tabName = getResources().getString(R.string.statistics_tab_text);
    TabSpec spec3 = tabHost.newTabSpec(tabName);
    spec3.setIndicator(tabName);
    spec3.setContent(R.id.tab3);

    tabHost.addTab(spec1);
    tabHost.addTab(spec2);
    tabHost.addTab(spec3);
    tabHost.setOnTabChangedListener(new OnTabChangeListener() {
        @Override
        public void onTabChanged(String arg0) {
            updateUi();
        }
    });

    mLibraryView = (ListView) findViewById(R.id.media);
    mLibraryView.setAdapter(mLibraryItems);
    mLibraryView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    mLibraryView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            updateButtons();
        }
    });

    mPlayListView = (ListView) findViewById(R.id.playlist);
    mPlayListView.setAdapter(mPlayListItems);
    mPlayListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    mPlayListView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            updateButtons();
        }
    });

    mInfoTextView = (TextView) findViewById(R.id.info);

    mPauseResumeButton = (ImageButton) findViewById(R.id.pause_resume_button);
    mPauseResumeButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mPaused = !mPaused;
            if (mPaused) {
                mSessionManager.pause();
            } else {
                mSessionManager.resume();
            }
        }
    });

    mStopButton = (ImageButton) findViewById(R.id.stop_button);
    mStopButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mPaused = false;
            mSessionManager.stop();
        }
    });

    mSeekBar = (SeekBar) findViewById(R.id.seekbar);
    mSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            PlaylistItem item = getCheckedPlaylistItem();
            if (fromUser && item != null && item.getDuration() > 0) {
                long pos = progress * item.getDuration() / 100;
                mSessionManager.seek(item.getItemId(), pos);
                item.setPosition(pos);
                item.setTimestamp(SystemClock.elapsedRealtime());
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            mSeeking = true;
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            mSeeking = false;
            updateUi();
        }
    });

    // Schedule Ui update
    mHandler.postDelayed(mUpdateSeekRunnable, 1000);

    // Build the PendingIntent for the remote control client
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mEventReceiver = new ComponentName(getPackageName(), SampleMediaButtonReceiver.class.getName());
    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setComponent(mEventReceiver);
    mMediaPendingIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent, 0);

    // Create and register the remote control client
    registerRemoteControlClient();

    // Set up playback manager and player
    mPlayer = RadioPlayer.create(RadioActivity.this, mMediaRouter.getSelectedRoute());
    mSessionManager.setPlayer(mPlayer);
    mSessionManager.setCallback(new RadioSessionManager.Callback() {
        @Override
        public void onStatusChanged() {
            updateUi();
        }

        @Override
        public void onItemChanged(PlaylistItem item) {
        }
    });

    updateUi();
}

From source file:ru.gkpromtech.exhibition.events.EventsActivity.java

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

    // restore saved positions
    int savedPosition = 0;
    if (savedInstanceState != null) {
        savedFilter = savedInstanceState.getInt(SAVE_FILTER, EventReader.EVENT_FILTER_ALL);
        savedPosition = savedInstanceState.getInt(SAVE_PAGE_NUMBER, 0);
    } else {/*from   w  ww . jav  a2 s .c  om*/
        // calculate day to position ViewPager
        Calendar calendar = Calendar.getInstance();
        Date d = calendar.getTime();
        List<Date> days = new ArrayList<>(EventReader.getInstance(this).getDays());
        if (days.contains(d))
            savedPosition = days.indexOf(d);
    }

    FrameLayout view = (FrameLayout) findViewById(R.id.container);
    getLayoutInflater().inflate(R.layout.activity_events, view, true);

    TabHost tabHost = (TabHost) view.findViewById(R.id.tabHost);
    tabHost.setup();

    tabHost.addTab(tabHost
            .newTabSpec("tag" + EventReader.EVENT_FILTER_ALL).setIndicator(createIndicatorView(tabHost,
                    getResources().getString(R.string.all_uppercase), R.drawable.ic_events_all))
            .setContent(R.id.tab1));

    tabHost.addTab(tabHost
            .newTabSpec("tag" + EventReader.EVENT_FILTER_SHOW).setIndicator(createIndicatorView(tabHost,
                    getResources().getString(R.string.event_status_business), R.drawable.ic_white_plane))
            .setContent(R.id.tab2));

    tabHost.addTab(tabHost
            .newTabSpec("tag" + EventReader.EVENT_FILTER_MY).setIndicator(createIndicatorView(tabHost,
                    getResources().getString(R.string.event_status_my), R.drawable.ic_person))
            .setContent(R.id.tab3));

    pager = (ViewPager) findViewById(R.id.pager);
    pagerAdapter = new EventsFragmentPagerAdapter(getSupportFragmentManager(), EventReader.getInstance(this),
            savedFilter);
    pager.setAdapter(pagerAdapter);

    // set saved page
    pager.setCurrentItem(savedPosition);
    tabHost.setCurrentTabByTag("tag" + savedFilter);

    pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    });

    tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
        @Override
        public void onTabChanged(String tabId) {
            switch (tabId) {
            case "tag" + EventReader.EVENT_FILTER_ALL:
                savedFilter = EventReader.EVENT_FILTER_ALL;
                break;
            case "tag" + EventReader.EVENT_FILTER_SHOW:
                savedFilter = EventReader.EVENT_FILTER_SHOW;
                break;
            case "tag" + EventReader.EVENT_FILTER_MY:
                savedFilter = EventReader.EVENT_FILTER_MY;
                break;
            }
            AnalyticsManager.sendEvent(EventsActivity.this, R.string.events_category, R.string.action_change,
                    savedFilter);
            pagerAdapter.setFilter(savedFilter);
        }
    });

    AnalyticsManager.sendEvent(this, R.string.events_category, R.string.action_open, savedFilter);
}

From source file:com.tutor.fragment.ViewPageFragment.java

private boolean initialjfTabHostFromWeb(LayoutInflater inflater, View mView) {
    List<FDItemTyeModel> jfItems = GetjfItems();
    if (jfItems == null || jfItems.size() == 0) {
        return false;
    }//from  w w w .j  a  v a  2  s  .com
    final TabHost tabHost = (TabHost) mView.findViewById(R.id.jf_tabhost);
    tabHost.setup();
    View tabItem = inflater.inflate(R.layout.tab_fd_widebg, null);
    TextView tbTabItemTitle = (TextView) tabItem.findViewById(R.id.tvTabItemTitle);
    for (int i = 0; i < 3; i++) {

        if (i == 2) {
            tabItem = inflater.inflate(R.layout.tab_fd_widebg, null);
            tbTabItemTitle = (TextView) tabItem.findViewById(R.id.tvTabItemTitle);
            tbTabItemTitle.setText("");
            tabHost.addTab(tabHost.newTabSpec("-1").setIndicator(tabItem).setContent(R.id.tab3));
            setJFListViewAdapter(tabHost);
            break;
        }
        switch (i) {
        case 0:
            InitialJfItemInf(jfItems.get(i).getItem_ID());
            tbTabItemTitle.setText(jfItems.get(i).getItem_Name());
            tabHost.addTab(tabHost.newTabSpec(jfItems.get(i).getItem_Name()).setIndicator(tabItem)
                    .setContent(R.id.tab1));
            break;
        case 1:
            tabItem = inflater.inflate(R.layout.tab_fd_widebg, null);
            tbTabItemTitle = (TextView) tabItem.findViewById(R.id.tvTabItemTitle);
            tbTabItemTitle.setText(jfItems.get(i).getItem_Name());
            tabHost.addTab(tabHost.newTabSpec(jfItems.get(i).getItem_Name()).setIndicator(tabItem)
                    .setContent(R.id.tab2));
            break;
        }
    }

    tabHost.setOnTabChangedListener(new OnTabChangeListener() {
        @Override
        public void onTabChanged(String tabId) {
            if (tabId != "-1") {
                int itemId = Integer.parseInt(jfTypesMap.get(tabId.toString()).toString());
                InitialJfItemInf(itemId);
                setJFListViewAdapter(tabHost);
            } else {
                tabHost.setCurrentTab(0);
                Intent intent = new Intent(getActivity(), MoreActivity.class);

                intent.putExtra("Flag", "jf");
                startActivity(intent);
            }
        }
    });

    return true;
}

From source file:eu.operando.operandoapp.OperandoProxyStatus.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    MainUtil.initializeMainContext(getApplicationContext());
    Settings settings = mainContext.getSettings();
    settings.initializeDefaultValues();//from   w w w.  j a va 2 s  .  c  om
    setCurrentThemeStyle(settings.getThemeStyle());
    setTheme(getCurrentThemeStyle().themeAppCompatStyle());
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
    settings.registerOnSharedPreferenceChangeListener(this);

    webView = (WebView) findViewById(R.id.webView);
    webView.getSettings().setJavaScriptEnabled(true);

    //region Floating Action Button

    fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (MainUtil.isServiceRunning(mainContext.getContext(), ProxyService.class)
                    && !MainUtil.isProxyPaused(mainContext)) {
                //Update Preferences to BypassProxy
                MainUtil.setProxyPaused(mainContext, true);
                fab.setImageResource(android.R.drawable.ic_media_play);
                //Toast.makeText(mainContext.getContext(), "-- bypass (disable) proxy --", Toast.LENGTH_SHORT).show();
            } else if (MainUtil.isServiceRunning(mainContext.getContext(), ProxyService.class)
                    && MainUtil.isProxyPaused(mainContext)) {

                MainUtil.setProxyPaused(mainContext, false);
                fab.setImageResource(android.R.drawable.ic_media_pause);
                //Toast.makeText(mainContext.getContext(), "-- re-enable proxy --", Toast.LENGTH_SHORT).show();
            } else if (!mainContext.getAuthority()
                    .aliasFile(BouncyCastleSslEngineSource.KEY_STORE_FILE_EXTENSION).exists()) {
                try {
                    installCert();
                } catch (RootCertificateException | GeneralSecurityException | OperatorCreationException
                        | IOException ex) {
                    Logger.error(this, ex.getMessage(), ex.getCause());
                }
            }
        }
    });

    //endregion

    //region TabHost

    final TabHost tabHost = (TabHost) findViewById(R.id.tabHost2);
    tabHost.setup();

    TabHost.TabSpec tabSpec = tabHost.newTabSpec("wifi_ap");
    tabSpec.setContent(R.id.WifiAndAccessPointsScrollView);
    tabSpec.setIndicator("", getResources().getDrawable(R.drawable.ic_home));
    tabHost.addTab(tabSpec);

    tabSpec = tabHost.newTabSpec("response_domain_filters");
    tabSpec.setContent(R.id.ResponseAndDomainFiltersScrollView);
    tabSpec.setIndicator("", getResources().getDrawable(R.drawable.ic_filter));
    tabHost.addTab(tabSpec);

    tabSpec = tabHost.newTabSpec("pending_notifications");
    tabSpec.setContent(R.id.PendingNotificationsScrollView);
    tabSpec.setIndicator("", getResources().getDrawable(R.drawable.ic_pending_notification));
    tabHost.addTab(tabSpec);

    tabSpec = tabHost.newTabSpec("logs");
    tabSpec.setContent(R.id.LogsScrollView);
    tabSpec.setIndicator("", getResources().getDrawable(R.drawable.ic_report));
    tabHost.addTab(tabSpec);

    tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
        @Override
        public void onTabChanged(String tabId) {
            switch (tabId) {
            case "pending_notifications":
                //region Load Tab3
                ((TableLayout) ((LinearLayout) ((ScrollView) findViewById(R.id.PendingNotificationsScrollView))
                        .getChildAt(0)).getChildAt(1)).removeAllViews();
                LoadPendingNotificationsTab();
                //endregion
                break;
            case "logs":
                //region Load Tab 4
                //because it is a heavy task it is being loaded asynchronously
                ((TableLayout) ((LinearLayout) ((ScrollView) findViewById(R.id.LogsScrollView)).getChildAt(0))
                        .getChildAt(1)).removeAllViews();
                new AsyncTask() {
                    private ProgressDialog mProgress;
                    private List<String[]> apps;

                    @Override
                    protected void onPreExecute() {
                        super.onPreExecute();
                        mProgress = new ProgressDialog(MainActivity.this);
                        mProgress.setCancelable(false);
                        mProgress.setCanceledOnTouchOutside(false);
                        mProgress.setTitle("Fetching Application Data Logs");
                        mProgress.show();
                    }

                    @Override
                    protected Object doInBackground(Object[] params) {
                        apps = new ArrayList();
                        for (String[] app : getInstalledApps(false)) {
                            apps.add(new String[] { app[0], GetDataForApp(Integer.parseInt(app[1])) });
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Object o) {
                        super.onPostExecute(o);
                        mProgress.dismiss();
                        for (String[] app : apps) {
                            if (app[0].contains(".")) {
                                continue;
                            }
                            TextView tv = new TextView(MainActivity.this);
                            tv.setTextSize(18);
                            tv.setText(app[0] + " || " + app[1]);
                            ((TableLayout) ((LinearLayout) ((ScrollView) findViewById(R.id.LogsScrollView))
                                    .getChildAt(0)).getChildAt(1)).addView(tv);

                            View separator = new View(MainActivity.this);
                            separator.setBackgroundColor(Color.BLACK);
                            separator.setLayoutParams(
                                    new TableRow.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 5));
                            ((TableLayout) ((LinearLayout) ((ScrollView) findViewById(R.id.LogsScrollView))
                                    .getChildAt(0)).getChildAt(1)).addView(separator);
                        }
                    }
                }.execute();
                //endregion
                break;
            }
        }
    });

    //endregion

    //region Buttons

    WiFiAPButton = (Button) findViewById(R.id.WiFiAPButton);
    WiFiAPButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent i = new Intent(mainContext.getContext(), AccessPointsActivity.class);
            startActivity(i);
        }
    });

    responseFiltersButton = (Button) findViewById(R.id.responseFiltersButton);
    responseFiltersButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent(mainContext.getContext(), ResponseFiltersActivity.class);
            startActivity(i);
        }
    });

    domainFiltersButton = (Button) findViewById(R.id.domainFiltersButton);
    domainFiltersButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent(mainContext.getContext(), DomainFiltersActivity.class);
            startActivity(i);
        }
    });

    domainManagerButton = (Button) findViewById(R.id.domainManagerButton);
    domainManagerButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent(mainContext.getContext(), DomainManagerActivity.class);
            startActivity(i);
        }
    });

    permissionsPerDomainButton = (Button) findViewById(R.id.permissionsPerDomainButton);
    permissionsPerDomainButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent(mainContext.getContext(), PermissionsPerDomainActivity.class);
            startActivity(i);
        }
    });

    trustedAccessPointsButton = (Button) findViewById(R.id.trustedAccessPointsButton);
    trustedAccessPointsButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent(mainContext.getContext(), TrustedAccessPointsActivity.class);
            startActivity(i);
        }
    });

    updateButton = (Button) findViewById(R.id.updateButton);
    updateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // mark first time has not runned and update like it's initial .
            final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putBoolean("firstTime", true);
            editor.commit();
            DownloadInitialSettings();
        }
    });

    statisticsButton = (Button) findViewById(R.id.statisticsButton);
    statisticsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(mainContext.getContext(), StatisticsActivity.class);
            startActivity(i);
        }
    });

    //endregion

    //region Action Bar
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        setTitle(R.string.app_name);
    }

    //endregion

    //region Send Cached Settings
    //send cached settings if exist...
    BufferedReader br = null;
    try {
        File file = new File(MainContext.INSTANCE.getContext().getFilesDir(), "resend.inf");
        StringBuilder content = new StringBuilder();
        br = new BufferedReader(new FileReader(file));
        String line;
        while ((line = br.readLine()) != null) {
            content.append(line);
        }
        if (content.toString().equals("1")) {
            File f = new File(file.getCanonicalPath());
            f.delete();
            new DatabaseHelper(MainActivity.this)
                    .sendSettingsToServer(new RequestFilterUtil(MainActivity.this).getIMEI());
        }
    } catch (Exception ex) {
        ex.getMessage();
    } finally {
        try {
            br.close();
        } catch (Exception ex) {
            ex.getMessage();
        }
    }
    //endregion

    initializeProxyService();
}

From source file:com.momock.outlet.tab.PagerTabOutlet.java

public void attach(TabHolder target) {
    Logger.check(target != null, "Parameter target cannot be null!");
    Logger.check(target.getTabContent() instanceof ViewPager,
            "The PagerTabOutlet must contains a ViewPager content!");
    this.target = target;
    final TabHost tabHost = target.getTabHost();
    final ViewPager tabContent = (ViewPager) target.getTabContent();
    plugs = getPlugs();//from www .j a  v a  2  s. c  o  m

    ViewPager pager = (ViewPager) target.getTabContent();
    for (int i = 0; i < plugs.getItemCount(); i++) {
        ITabPlug plug = (ITabPlug) plugs.getItem(i);
        Logger.check(plug.getContent() instanceof ViewHolder,
                "The plug of PagerTabOutlet must include a ViewHolder!");
        ((ViewHolder) plug.getContent()).reset();
    }
    pager.setAdapter(new PagerAdapter() {

        @Override
        public int getCount() {
            return plugs.getItemCount();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ITabPlug plug = (ITabPlug) plugs.getItem(position);
            View view = ((ViewHolder) plug.getContent()).getView();
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    });

    tabContent.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            TabWidget widget = tabHost.getTabWidget();
            int oldFocusability = widget.getDescendantFocusability();
            widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
            tabHost.setCurrentTab(position);
            widget.setDescendantFocusability(oldFocusability);
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });
    tabHost.setup();
    tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {

        @Override
        public void onTabChanged(String tabId) {
            int index = tabHost.getCurrentTab();
            ITabPlug plug = (ITabPlug) plugs.getItem(index);
            setActivePlug(plug);
            tabContent.setCurrentItem(index, true);
        }
    });
    for (int i = 0; i < plugs.getItemCount(); i++) {
        final ITabPlug plug = (ITabPlug) plugs.getItem(i);
        Logger.check(plug.getContent() instanceof ViewHolder,
                "Plug in PagerTabOutlet must contains a ViewHolder content!");

        TabHost.TabSpec spec = tabHost.newTabSpec("" + i);
        target.setTabIndicator(spec, plug);
        spec.setContent(new TabContentFactory() {

            @Override
            public View createTabContent(String tag) {
                View v = new View(tabHost.getContext());
                v.setMinimumWidth(0);
                v.setMinimumHeight(0);
                return v;
            }

        });
        tabHost.addTab(spec);
        if (getActivePlug() == plug)
            tabHost.setCurrentTab(i);
    }
}

From source file:com.momock.outlet.tab.FragmentPagerTabOutlet.java

public void attach(final FragmentTabHolder tabHolder) {
    Logger.check(tabHolder != null, "Parameter tabHolder cannot be null!");
    this.target = tabHolder;
    final TabHost tabHost = target.getTabHost();
    plugs = getPlugs();// w  w  w . java 2 s .co  m
    Logger.check(target.getTabContent() instanceof ViewPager, "The tab content container must be a ViewPager!");
    final ViewPager tabContent = (ViewPager) target.getTabContent();
    tabContent.setOffscreenPageLimit(plugs.getItemCount());
    tabContent.setAdapter(new FragmentPagerAdapter(target.getFragmentManager()) {

        @Override
        public Fragment getItem(final int position) {
            final ITabPlug plug = (ITabPlug) plugs.getItem(position);
            Fragment f = ((FragmentHolder) plug.getContent()).getFragment();
            if (f instanceof CaseFragment) {
                CaseFragment cf = (CaseFragment) f;
                cf.setActiveCaseIndicator(new IActiveCaseIndicator() {

                    @Override
                    public boolean isActiveCase() {
                        return getActivePlug() == plug;
                    }

                });
            }
            return f;
        }

        @Override
        public int getCount() {
            return plugs.getItemCount();
        }

        void doFinishUpdate(ViewGroup container) {
            super.finishUpdate(container);
        }

        @Override
        public void finishUpdate(final ViewGroup container) {
            new Handler().post(new Runnable() {

                @Override
                public void run() {
                    doFinishUpdate(container);
                }

            });
        }

        @Override
        public void setPrimaryItem(ViewGroup container, int position, final Object object) {
            super.setPrimaryItem(container, position, object);
            new Handler().post(new Runnable() {

                @Override
                public void run() {

                    if (object instanceof CaseFragment) {
                        CaseFragment cf = (CaseFragment) object;
                        if (cf.getCase() != null && cf.getCase().getParent() != null)
                            cf.getCase().getParent().setActiveCase(cf.getCase());
                    }
                }

            });
        }
    });
    tabHost.setup();
    for (int i = 0; i < plugs.getItemCount(); i++) {
        final ITabPlug plug = (ITabPlug) plugs.getItem(i);
        Logger.check(plug.getContent() instanceof FragmentHolder,
                "Plug in PagerTabOutlet must contains a FragmentHolder content!");

        TabHost.TabSpec spec = tabHost.newTabSpec("" + i);
        target.setTabIndicator(spec, plug);
        spec.setContent(new TabContentFactory() {

            @Override
            public View createTabContent(String tag) {
                View v = new View(tabHost.getContext());
                v.setMinimumWidth(0);
                v.setMinimumHeight(0);
                return v;
            }

        });
        tabHost.addTab(spec);
        if (getActivePlug() == plug) {
            tabHost.setCurrentTab(i);
            tabContent.setCurrentItem(i, true);
        }
    }
    tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {

        @Override
        public void onTabChanged(String tabId) {
            int index = tabHost.getCurrentTab();
            ITabPlug plug = (ITabPlug) plugs.getItem(index);
            setActivePlug(plug);
            tabContent.setCurrentItem(index, true);
        }
    });
    tabContent.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            TabWidget widget = tabHost.getTabWidget();
            int oldFocusability = widget.getDescendantFocusability();
            widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
            tabHost.setCurrentTab(position);
            widget.setDescendantFocusability(oldFocusability);
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });
}

From source file:com.github.colorchief.colorchief.MainActivity.java

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

    setContentView(R.layout.activity_main);

    final TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
    tabHost.setup();//from   w ww.ja v a 2s .  c  o m

    final TabHost.TabSpec tabImageView = tabHost.newTabSpec("Image View");
    final TabHost.TabSpec tabSettings = tabHost.newTabSpec("Settings");
    final TabHost.TabSpec tabAbout = tabHost.newTabSpec("About");

    tabImageView.setIndicator("", ContextCompat.getDrawable(this, R.drawable.ic_action_picture));
    tabImageView.setContent(R.id.tabImageView);

    tabSettings.setIndicator("", ContextCompat.getDrawable(this, R.drawable.ic_action_gear));
    tabSettings.setContent(R.id.tabSettings);

    tabAbout.setIndicator("", ContextCompat.getDrawable(this, R.drawable.ic_action_help));
    tabAbout.setContent(R.id.tabAbout);

    /** Add the tabs  to the TabHost to display. */
    tabHost.addTab(tabImageView);
    tabHost.addTab(tabSettings);
    tabHost.addTab(tabAbout);

    colorLUT.initLUT(LUT_SIZE, LUT_SIZE, LUT_SIZE);

    //check savedInstance
    // for Tab state and set active tab accordingly
    // for LUT values and update (restore) accordingly
    if (savedInstanceState != null) {
        tabHost.setCurrentTab(savedInstanceState.getInt("Active Tab"));
        colorLUT.setColorLutArray(savedInstanceState.getIntArray("Color LUT"));
    }

    ((SeekBar) findViewById(R.id.seekBarChromaPowerFactor)).setMax(POWER_FACTOR_SEEK_BAR_MAX);
    ((SeekBar) findViewById(R.id.seekBarChromaPowerFactor)).setProgress(getSeekPosition(powerFactor));

    if (Lselect == LutCalculate.L_SELECT_IN) {
        ((RadioButton) findViewById(R.id.radioButtonLin)).setChecked(true);
        ((RadioButton) findViewById(R.id.radioButtonLout)).setChecked(false);
    } else if (Lselect == LutCalculate.L_SELECT_OUT) {
        ((RadioButton) findViewById(R.id.radioButtonLin)).setChecked(false);
        ((RadioButton) findViewById(R.id.radioButtonLout)).setChecked(true);
    }
    if (Cselect == LutCalculate.C_SELECT_ABSOLUTE) {
        ((RadioButton) findViewById(R.id.radioButtonCin)).setChecked(true);
        ((RadioButton) findViewById(R.id.radioButtonCrelative)).setChecked(false);
        ((SeekBar) findViewById(R.id.seekBarChromaPowerFactor)).setEnabled(false);

    } else if (Cselect == LutCalculate.C_SELECT_RELATIVE) {
        ((RadioButton) findViewById(R.id.radioButtonCin)).setChecked(false);
        ((RadioButton) findViewById(R.id.radioButtonCrelative)).setChecked(true);
        ((SeekBar) findViewById(R.id.seekBarChromaPowerFactor)).setEnabled(true);
    }

    if (uriIccProfileIn != null)
        iccProfileIn.loadFromFile(uriIccProfileIn);
    if (uriIccProfileOut != null)
        iccProfileOut.loadFromFile(uriIccProfileOut);

    if (bitmapLoaded) {

        transformImage();
        updateImageViewer();

    } else {
        ((ImageView) findViewById(R.id.imageView)).setImageBitmap(
                BitmapFactory.decodeResource(getResources(), R.drawable.ic_action_folder_open_blue));

    }

    ((ImageView) findViewById(R.id.imageView)).addOnLayoutChangeListener(new View.OnLayoutChangeListener() {

        @Override
        public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop,
                int oldRight, int oldBottom) {
            // if layout is not complete we will get all zero values for the positions, so ignore the event
            if (left == 0 && top == 0 && right == 0 && bottom == 0) {
                return;
            } else {
                if (bitmapLoaded) {
                    try {
                        decodeImageUri(uriBitmapOriginal, (ImageView) findViewById(R.id.imageView));
                    } catch (FileNotFoundException e) {
                        Log.e(TAG, "Failed to grab Bitmap: " + e);
                    }
                    //if (iccProfileOut.isValidProfile() && iccProfileIn.isValidProfile())
                    transformImage();
                    updateImageViewer();

                }
            }

        }
    });

    ((SeekBar) findViewById(R.id.seekBarChromaPowerFactor))
            .setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    powerFactor = getPowerFactor(seekBar.getProgress());
                    //convertImage(seekBar);
                    //updateImageViewer();
                }
            });

    //when switching tabs, make sure:
    //a: update the image when switching to the imageview tab in case any settings changes were made
    //b: hide the color controls overlay if we are not on the imageview tab
    tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
        @Override
        public void onTabChanged(String tabId) {
            if (tabId.equals(tabImageView.getTag())) {
                //Log.d(TAG,"Tab changed to image view");

                if (iccProfileIn.isValidProfile() && iccProfileOut.isValidProfile() && bitmapLoaded) {
                    recalculateTransform();
                    transformImage();
                    updateImageViewer();
                }
            } else if (tabId.equals(tabAbout.getTag())) {
                ((LinearLayout) findViewById(R.id.overlayColorControl)).setVisibility(View.INVISIBLE);
                InputStream inputStream = getResources().openRawResource(R.raw.about);
                ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();
                try {
                    int bytesRead = inputStream.read();
                    while (bytesRead != -1) {
                        byteArrayStream.write(bytesRead);
                        bytesRead = inputStream.read();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                //TextView textViewAbout = (TextView) findViewById(R.id.textViewAbout);
                //textViewAbout.setText(Html.fromHtml(byteArrayStream.toString()));
                WebView webViewAbout = (WebView) findViewById(R.id.webViewAbout);
                webViewAbout.loadDataWithBaseURL(null, byteArrayStream.toString(), "text/html", "utf-8", null);
            } else {
                ((LinearLayout) findViewById(R.id.overlayColorControl)).setVisibility(View.INVISIBLE);
            }
        }
    });

}

From source file:com.sentaroh.android.SMBSync2.ActivityMain.java

@SuppressLint("InflateParams")
private void aboutSMBSync() {
    final Dialog dialog = new Dialog(this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.about_dialog);

    final LinearLayout title_view = (LinearLayout) dialog.findViewById(R.id.about_dialog_title_view);
    final TextView title = (TextView) dialog.findViewById(R.id.about_dialog_title);
    title_view.setBackgroundColor(mGp.themeColorList.dialog_title_background_color);
    title.setTextColor(mGp.themeColorList.text_color_dialog_title);
    title.setText(getString(R.string.msgs_dlg_title_about) + "(Ver " + packageVersionName + ")");

    // get our tabHost from the xml
    final TabHost tab_host = (TabHost) dialog.findViewById(R.id.about_tab_host);
    tab_host.setup();// w  ww .j a v  a 2  s .co m

    final TabWidget tab_widget = (TabWidget) dialog.findViewById(android.R.id.tabs);

    if (Build.VERSION.SDK_INT >= 11) {
        tab_widget.setStripEnabled(false);
        tab_widget.setShowDividers(LinearLayout.SHOW_DIVIDER_NONE);
    }

    CustomTabContentView tabViewProf = new CustomTabContentView(this,
            getString(R.string.msgs_about_dlg_func_btn));
    tab_host.addTab(tab_host.newTabSpec("func").setIndicator(tabViewProf).setContent(android.R.id.tabcontent));

    CustomTabContentView tabViewHist = new CustomTabContentView(this,
            getString(R.string.msgs_about_dlg_change_btn));
    tab_host.addTab(
            tab_host.newTabSpec("change").setIndicator(tabViewHist).setContent(android.R.id.tabcontent));

    LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    LinearLayout ll_func = (LinearLayout) vi.inflate(R.layout.about_dialog_func, null);
    LinearLayout ll_change = (LinearLayout) vi.inflate(R.layout.about_dialog_change, null);

    final WebView func_view = (WebView) ll_func.findViewById(R.id.about_dialog_function);
    func_view.loadUrl("file:///android_asset/" + getString(R.string.msgs_dlg_title_about_func_desc));
    func_view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    func_view.getSettings().setBuiltInZoomControls(true);

    final WebView change_view = (WebView) ll_change.findViewById(R.id.about_dialog_change_history);
    change_view.loadUrl("file:///android_asset/" + getString(R.string.msgs_dlg_title_about_change_desc));
    change_view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    change_view.getSettings().setBuiltInZoomControls(true);

    final CustomViewPagerAdapter mAboutViewPagerAdapter = new CustomViewPagerAdapter(this,
            new WebView[] { func_view, change_view });
    final CustomViewPager mAboutViewPager = (CustomViewPager) dialog.findViewById(R.id.about_view_pager);
    //       mMainViewPager.setBackgroundColor(mThemeColorList.window_color_background);
    mAboutViewPager.setAdapter(mAboutViewPagerAdapter);
    mAboutViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            //             util.addDebugMsg(2,"I","onPageSelected entered, pos="+position);
            tab_widget.setCurrentTab(position);
            tab_host.setCurrentTab(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            //             util.addDebugMsg(2,"I","onPageScrollStateChanged entered, state="+state);
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            //             util.addDebugMsg(2,"I","onPageScrolled entered, pos="+position);
        }
    });

    tab_host.setOnTabChangedListener(new OnTabChangeListener() {
        @Override
        public void onTabChanged(String tabId) {
            util.addDebugMsg(2, "I", "onTabchanged entered. tab=" + tabId);
            mAboutViewPager.setCurrentItem(tab_host.getCurrentTab());
        }
    });

    final Button btnOk = (Button) dialog.findViewById(R.id.about_dialog_btn_ok);

    CommonDialog.setDlgBoxSizeLimit(dialog, true);

    // OK?
    btnOk.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
    // Cancel?
    dialog.setOnCancelListener(new Dialog.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface arg0) {
            btnOk.performClick();
        }
    });

    dialog.show();
}