Example usage for android.widget TabHost newTabSpec

List of usage examples for android.widget TabHost newTabSpec

Introduction

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

Prototype

@NonNull
public TabSpec newTabSpec(@NonNull String tag) 

Source Link

Document

Creates a new TabSpec associated with this tab host.

Usage

From source file:fr.vassela.acrrd.Main.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    try {//from w w  w  .j ava 2  s.c  o  m
        localizerManager.setPreferencesLocale(getApplicationContext());
        themeManager.setPreferencesTheme(getApplicationContext(), this);

        delegate = AppCompatDelegate.create(this, this);
        delegate.installViewFactory();

        super.onCreate(savedInstanceState);

        delegate.onCreate(savedInstanceState);

        delegate.setContentView(R.layout.main);

        SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(getApplicationContext());
        int currentLocaleIndex = Integer.parseInt(sharedPreferences.getString("preferences_locale_set", "0"));
        String currentLocale = localizerManager.getLocale(getApplicationContext()).toString();

        ArrayList<String> slideMenuTitles = new ArrayList<String>();
        slideMenuTitles.add(getApplicationContext().getString(R.string.preferences_locale).toString());
        //slideMenuTitles.add(getApplicationContext().getString(R.string.main_toolbar_test).toString());
        slideMenuTitles.add(getApplicationContext().getString(R.string.main_toolbar_preferences).toString());
        slideMenuTitles.add(getApplicationContext().getString(R.string.main_toolbar_log).toString());
        slideMenuTitles.add(getApplicationContext().getString(R.string.main_toolbar_about).toString());
        slideMenuTitles.add(getApplicationContext().getString(R.string.main_toolbar_exit).toString());

        ArrayList<String> slideMenuSubtitles = new ArrayList<String>();
        slideMenuSubtitles.add(currentLocale);
        //slideMenuSubtitles.add(getApplicationContext().getString(R.string.main_toolbar_test_description).toString());
        slideMenuSubtitles.add(
                getApplicationContext().getString(R.string.main_toolbar_preferences_description).toString());
        slideMenuSubtitles
                .add(getApplicationContext().getString(R.string.main_toolbar_log_description).toString());
        slideMenuSubtitles
                .add(getApplicationContext().getString(R.string.main_toolbar_about_description).toString());
        slideMenuSubtitles
                .add(getApplicationContext().getString(R.string.main_toolbar_exit_description).toString());

        ArrayList<Integer> slideMenuIcons = new ArrayList<Integer>();
        slideMenuIcons.add(themeManager.getLocaleFlag(getApplicationContext(), currentLocaleIndex));
        slideMenuIcons.add(R.drawable.ic_menu_preferences);
        //slideMenuIcons.add(R.drawable.ic_menu_preferences);
        slideMenuIcons.add(R.drawable.ic_menu_archive);
        slideMenuIcons.add(R.drawable.ic_menu_info_details);
        slideMenuIcons.add(R.drawable.ic_menu_revert);

        drawerList = (ListView) findViewById(R.id.drawer_list);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);

        SlidingMenuAdapter slidingMenuAdapter = new SlidingMenuAdapter(this, slideMenuTitles,
                slideMenuSubtitles, slideMenuIcons);

        drawerList.setAdapter(slidingMenuAdapter);

        drawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                switch (position) {
                case 0:
                    break;

                /*case 0 :
                   drawerLayout.closeDrawers();
                   startActivity(new Intent(getApplicationContext(), Test.class));
                   break;*/

                case 1:
                    drawerLayout.closeDrawers();
                    startActivity(new Intent(getApplicationContext(), Preferences.class));
                    break;

                case 2:
                    drawerLayout.closeDrawers();
                    startActivity(new Intent(getApplicationContext(), TelephoneCallLogger.class));
                    break;

                case 3:
                    drawerLayout.closeDrawers();
                    startActivity(new Intent(getApplicationContext(), About.class));
                    break;

                case 4:
                    drawerLayout.closeDrawers();
                    RecordServiceManager recordServiceManager = new RecordServiceManager();
                    boolean isRecordServiceRunning = recordServiceManager.isRunning(getApplicationContext());

                    if (isRecordServiceRunning == false) {
                        MonitoringServiceManager monitoringServiceManager = new MonitoringServiceManager();
                        monitoringServiceManager.stopService(getApplicationContext());

                        PurgeServiceManager purgeServiceManager = new PurgeServiceManager();
                        purgeServiceManager.stopService(getApplicationContext());
                    }

                    moveTaskToBack(true);
                    onBackPressed();
                    break;

                }

            }
        });

        toolbar = (Toolbar) findViewById(R.id.main_toolbar);
        delegate.setSupportActionBar(toolbar);
        delegate.setTitle(getString(R.string.main_toolbar));
        delegate.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        delegate.getSupportActionBar().setDisplayShowHomeEnabled(true);
        delegate.getSupportActionBar().setHomeButtonEnabled(true);

        TabHost tabhost = (TabHost) findViewById(android.R.id.tabhost);
        TabWidget tabwidget = tabhost.getTabWidget();

        TabSpec tab_home = tabhost.newTabSpec(getString(R.string.main_tab_home));
        TabSpec tab_records = tabhost.newTabSpec(getString(R.string.main_tab_records));
        TabSpec tab_preferences = tabhost.newTabSpec(getString(R.string.main_tab_preferences));
        TabSpec tab_about = tabhost.newTabSpec(getString(R.string.main_tab_about));
        TabSpec tab_test = tabhost.newTabSpec("test");

        tab_home.setIndicator(getString(R.string.main_tab_home),
                this.getResources().getDrawable(R.drawable.ic_menu_home));
        tab_home.setContent(new Intent(this, Home.class));

        tab_records.setIndicator(getString(R.string.main_tab_records),
                this.getResources().getDrawable(R.drawable.ic_voice_search));
        tab_records.setContent(new Intent(this, Records.class));

        tab_preferences.setIndicator(getString(R.string.main_tab_preferences),
                this.getResources().getDrawable(R.drawable.ic_menu_preferences));
        tab_preferences.setContent(new Intent(this, Preferences.class));

        tab_about.setIndicator(getString(R.string.main_tab_about),
                this.getResources().getDrawable(R.drawable.ic_menu_info_details));
        tab_about.setContent(new Intent(this, About.class));

        tab_test.setIndicator("test", this.getResources().getDrawable(R.drawable.ic_menu_preferences));
        tab_test.setContent(new Intent(this, Test.class));

        tabhost.addTab(tab_home);
        tabhost.addTab(tab_records);

        Intent intent = getIntent();

        /*String setCurrentTab;
                
        if (savedInstanceState == null)
        {
           Bundle extras = getIntent().getExtras();
                   
           if(extras == null)
           {
         setCurrentTab = null;
           }
           else
           {
         setCurrentTab = extras.getString("setCurrentTab");
           }
        }
        else
        {
           setCurrentTab = (String) savedInstanceState.getSerializable("setCurrentTab");
        }
                
        getIntent().removeExtra("setCurrentTab"); 
                
        if(setCurrentTab.equals("home"))
        {
           tabhost.setCurrentTab(0);
        }
        else if(setCurrentTab.equals("records"))
        {
           tabhost.setCurrentTab(1);
        }
        else
        {
           tabhost.setCurrentTab(0);
        }*/

        if (SHOW_RECORDS.equals(intent.getAction())) {
            tabhost.setCurrentTab(1);
        } else {
            tabhost.setCurrentTab(0);
        }

        initDrawer();

        themeManager.setTabWidget(getApplicationContext(), tabwidget);

    } catch (Exception e) {
        Log.e("Main",
                "onCreate : " + getApplicationContext().getString(R.string.log_main_error_create) + " : " + e);
        databaseManager.insertLog(getApplicationContext(),
                "" + getApplicationContext().getString(R.string.log_main_error_create), new Date().getTime(), 1,
                false);
    }
}

From source file:edu.nd.darts.cimon.NDroidAdmin.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.administrator);
    // Toast.makeText(getBaseContext(), "This is",
    // Toast.LENGTH_LONG).show();

    startService(new Intent(this, NDroidService.class));

    Resources res = getResources(); // Resource object to get Drawables
    TabHost tabHost = getTabHost(); // The activity TabHost
    TabHost.TabSpec spec; // Reusable TabSpec for each tab
    Intent intent; // Reusable Intent for each tab

    // Create an Intent to launch an Activity for the tab (to be reused)
    // intent = new Intent().setClass(this, NDroidSystem.class);
    intent = new Intent().setClass(this, CimonListView.class);
    intent.putExtra("key", Metrics.TYPE_SYSTEM);

    // Initialize a TabSpec for each tab and add it to the TabHost
    spec = tabHost.newTabSpec("system").setIndicator("System", res.getDrawable(R.drawable.icon_system))
            .setContent(intent);//from w w  w.  ja v  a2 s  . c  o  m
    tabHost.addTab(spec);

    // Do the same for the other tabs
    // intent = new Intent().setClass(this, NDroidSensor.class);
    intent = new Intent().setClass(this, CimonListView.class);
    intent.putExtra("key", Metrics.TYPE_SENSOR);
    spec = tabHost.newTabSpec("sensors").setIndicator("Sensors", res.getDrawable(R.drawable.icon_sensor))
            .setContent(intent);
    tabHost.addTab(spec);

    // intent = new Intent().setClass(this, NDroidUser.class);
    intent = new Intent().setClass(this, CimonListView.class);
    intent.putExtra("key", Metrics.TYPE_USER);
    spec = tabHost.newTabSpec("user").setIndicator("User Activity", res.getDrawable(R.drawable.icon_user))
            .setContent(intent);
    tabHost.addTab(spec);

    tabHost.setCurrentTab(0);

    SharedPreferences appPrefs = getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);

    int storedVersion = appPrefs.getInt(PREF_VERSION, -1);

    int appVersion = -1;

    try {
        appVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
    } catch (NameNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if (DebugLog.DEBUG)
        Log.d(TAG, "NDroidAdmin.onCreate - appVersion:" + appVersion + " storedVersion:" + storedVersion);

    if (appVersion > storedVersion) {

        new Thread(new Runnable() {
            public void run() {
                List<MetricService<?>> serviceList;
                serviceList = MetricService.getServices(Metrics.TYPE_SYSTEM);
                for (MetricService<?> mService : serviceList) {
                    mService.insertDatabaseEntries();
                }
                serviceList.clear();
                serviceList = MetricService.getServices(Metrics.TYPE_SENSOR);
                for (MetricService<?> mService : serviceList) {
                    mService.insertDatabaseEntries();
                }
                serviceList.clear();
                serviceList = MetricService.getServices(Metrics.TYPE_USER);
                for (MetricService<?> mService : serviceList) {
                    mService.insertDatabaseEntries();
                }
                serviceList.clear();
            }
        }).start();

        SharedPreferences.Editor editor = appPrefs.edit();
        editor.putInt(PREF_VERSION, appVersion);
        editor.commit();
    }
}

From source file:com.hector.invoice.views.TabExportInvoiceOrder.java

/**
 * Add Tab content to the Tabhost//from  w  ww.j a v  a2  s  . co m
 * 
 * @param activity
 * @param tabHost
 * @param tabSpec
 * @param clss
 * @param args
 */
private void AddTab(BaseFragmentActivity activity, TabHost tabHost, String tabName, int type) {
    View tabview = createTabView(tabHost.getContext(), tabName, type);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT);
    lp.weight = 1;
    lp.gravity = Gravity.CENTER;
    lp.setMargins(0, 0, 0, 0);
    tabview.setLayoutParams(lp);

    TabSpec setContent = tabHost.newTabSpec(tabName).setIndicator(tabview).setContent(new TabFactory(activity));
    tabHost.addTab(setContent);
}

From source file:nl.spellenclubeindhoven.dominionshuffle.SelectActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.select);//www.  ja v  a 2  s . c  o  m

    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

    application = (Application) getApplication();
    dataReader = application.getDataReader();
    cardSelector = application.getCardSelector();

    TabHost tabs = getTabHost();

    TabHost.TabSpec spec = tabs.newTabSpec("inex");
    spec.setContent(R.id.inex_fastscrollview);
    spec.setIndicator(getResources().getString(R.string.tab_select),
            getResources().getDrawable(R.drawable.select_tab));
    tabs.addTab(spec);

    spec = tabs.newTabSpec("constraint");
    spec.setContent(R.id.constraint_fastscrollview);
    spec.setIndicator(getResources().getString(R.string.tab_constraints),
            getResources().getDrawable(R.drawable.limits_tab));
    tabs.addTab(spec);

    spec = tabs.newTabSpec("generate");
    spec.setContent(R.id.generateButtons);
    spec.setIndicator(getResources().getString(R.string.tab_generate),
            getResources().getDrawable(R.drawable.shuffle_tab));
    tabs.addTab(spec);

    inexFastScrollView = ((CustomFastScrollView) findViewById(R.id.inex_fastscrollview));
    inexFastScrollView.setOnScrollListener(this);

    constraintFastScrollView = ((CustomFastScrollView) findViewById(R.id.constraint_fastscrollview));
    constraintFastScrollView.setOnScrollListener(this);

    groupsAndCards = new LinkedList<Object>();

    inExAdapter = new InExAdapter(this, groupsAndCards, cardSelector, getPreferredCardComparator());
    inexList = (ListView) findViewById(R.id.inexList);
    inexList.setAdapter(inExAdapter);
    inexList.setOnItemClickListener(onItemClickListener);
    inexList.setOnItemLongClickListener(onItemLongClickListener);

    constraintList = (ListView) findViewById(R.id.constraintList);
    constraintAdapter = new ConstraintAdapter(this, groupsAndCards, cardSelector, getPreferredCardComparator());
    constraintList.setAdapter(constraintAdapter);
    constraintList.setOnItemClickListener(onItemClickListener);
    constraintList.setOnTouchListener(onConstraintListTouchListener);
    constraintList.setOnKeyListener(onConstraintKeyListener);
    constraintList.setOnItemLongClickListener(onItemLongClickListener);

    Button generateButton = (Button) findViewById(R.id.generateButton);
    generateButton.setOnClickListener(onGenerateClickListener);

    Button lastResultButton = (Button) findViewById(R.id.lastResultButton);
    lastResultButton.setOnClickListener(onLastResultClickListener);

    if (savedInstanceState != null) {
        dialogMessage = savedInstanceState.getString("dialogMessage");
        if (dataReader.getData() != null) {
            selectedGroup = dataReader.getData().getGroup(savedInstanceState.getString("selectedGroup"));
        }
    }

    SharedPreferences prefs = getPreferences(MODE_PRIVATE);

    dialogMimimumCount = getResources().getStringArray(R.array.minumum_items_conditional).length;
    dialogMaximumCount = getResources().getStringArray(R.array.maximum_items).length;
}

From source file:com.android.firewall.FirewallListPage.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    FragmentManager manager = getFragmentManager();

    // tabhost//from  www . jav  a2s  . co  m
    TabHost tabHost = (TabHost) findViewById(android.R.id.tabhost);
    tabHost.setup();

    // viewpager
    pager = (ViewPager) findViewById(R.id.pager);

    adapter = new MainPagerAdapter(manager, this, tabHost, pager);

    // tab size from screen size
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    int tabWidth = metrics.widthPixels / 3;
    int tabHeight = metrics.widthPixels / 7;

    for (int i = 0; i < 3; i++) {
        TabSpec spec = tabHost.newTabSpec("tab" + i);
        spec.setIndicator(getTabView(tabWidth, tabHeight, TAB_TITLES[i]));
        adapter.addTab(spec, "tab" + i);
    }

    this.handleIntent();

}

From source file:org.smap.smapTask.android.activities.MainTabsActivity.java

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // must be at the beginning of any activity that can be called from an external intent
    try {//w ww . j av a 2 s. c o m
        Collect.createODKDirs();
    } catch (RuntimeException e) {
        createErrorDialog(e.getMessage(), true);
        return;
    }

    setContentView(R.layout.main_tabs);

    Resources res = getResources(); // Resource object to get Drawables
    TabHost tabHost = getTabHost(); // The activity TabHost
    TabHost.TabSpec spec;
    Intent intent;

    tabHost.setBackgroundColor(Color.WHITE);
    tabHost.getTabWidget().setBackgroundColor(Color.DKGRAY);

    // Initialise a TabSpec and intent for each tab and add it to the TabHost
    intent = new Intent().setClass(this, MainListActivity.class);
    spec = tabHost.newTabSpec("taskList").setIndicator(getString(R.string.smap_taskList)).setContent(intent);
    tabHost.addTab(spec);

    /*
     * Initialise a Map tab
     */
    Log.i("trial", "Creating Maps Activity");
    intent = new Intent().setClass(this, MapsActivity.class);
    spec = tabHost.newTabSpec("taskMap").setIndicator(getString(R.string.smap_taskMap)).setContent(intent);
    tabHost.addTab(spec);

    // hack to set font size
    LinearLayout ll = (LinearLayout) tabHost.getChildAt(0);
    TabWidget tw = (TabWidget) ll.getChildAt(0);

    int fontsize = Collect.getQuestionFontsize();

    ViewGroup rllf = (ViewGroup) tw.getChildAt(0);
    mTVFF = getTextViewChild(rllf);
    if (mTVFF != null) {
        mTVFF.setTextSize(fontsize);
        mTVFF.setTextColor(Color.WHITE);
        mTVFF.setPadding(0, 0, 0, 6);
    }

    ViewGroup rlrf = (ViewGroup) tw.getChildAt(1);
    mTVDF = getTextViewChild(rlrf);
    if (mTVDF != null) {
        mTVDF.setTextSize(fontsize);
        mTVDF.setTextColor(Color.WHITE);
        mTVDF.setPadding(0, 0, 0, 6);
    }

}

From source file:com.android.inputmethod.keyboard.EmojiPalettesView.java

private void addTab(final TabHost host, final int categoryId) {
    final String tabId = mEmojiCategory.getCategoryName(categoryId, 0 /* categoryPageId */);
    final TabHost.TabSpec tspec = host.newTabSpec(tabId);
    tspec.setContent(R.id.emoji_keyboard_dummy);
    if (mEmojiCategory.getCategoryIcon(categoryId) != 0) {
        final ImageView iconView = (ImageView) LayoutInflater.from(getContext())
                .inflate(R.layout.emoji_keyboard_tab_icon, null);
        iconView.setImageResource(mEmojiCategory.getCategoryIcon(categoryId));
        tspec.setIndicator(iconView);/*from  ww  w. ja va 2s.  c o  m*/
    }
    if (mEmojiCategory.getCategoryLabel(categoryId) != null) {
        final TextView textView = (TextView) LayoutInflater.from(getContext())
                .inflate(R.layout.emoji_keyboard_tab_label, null);
        textView.setText(mEmojiCategory.getCategoryLabel(categoryId));
        textView.setTextColor(mTabLabelColor);
        tspec.setIndicator(textView);
    }
    host.addTab(tspec);
}

From source file:com.google.android.apps.iosched.ui.SessionDetailActivity.java

/** Build and add "notes" tab. */
private void setupNotesTab() {
    final TabHost host = getTabHost();

    final Uri notesUri = Sessions.buildNotesDirUri(mSessionId);
    final Intent intent = new Intent(Intent.ACTION_VIEW, notesUri);
    intent.addCategory(Intent.CATEGORY_TAB);
    intent.putExtra(NotesActivity.EXTRA_SHOW_INSERT, true);

    // Notes content comes from reused activity
    host.addTab(//from   w w  w .ja v  a 2  s . c o m
            host.newTabSpec(TAG_NOTES).setIndicator(buildIndicator(R.string.session_notes)).setContent(intent));
}

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    // Be sure to call the super class.
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        mPlayer = (Player) savedInstanceState.getSerializable("mPlayer");
    }/*from www .j  a v  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_media_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 = Player.create(MainActivity.this, mMediaRouter.getSelectedRoute());
    mSessionManager.setPlayer(mPlayer);
    mSessionManager.setCallback(new SessionManager.Callback() {
        @Override
        public void onStatusChanged() {
            updateUi();
        }

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

    updateUi();
}

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");
    }/*w  w  w.j a  v  a2 s. com*/

    // 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();
}