Example usage for android.widget AdapterView getItemAtPosition

List of usage examples for android.widget AdapterView getItemAtPosition

Introduction

In this page you can find the example usage for android.widget AdapterView getItemAtPosition.

Prototype

public Object getItemAtPosition(int position) 

Source Link

Document

Gets the data associated with the specified position in the list.

Usage

From source file:sysnetlab.android.sdc.ui.fragments.ExperimentSensorListFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    if (mListView != null) {
        mListView.setOnItemClickListener(new ListView.OnItemClickListener() {

            @Override//from w ww.  j  ava 2s.com
            public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
                Log.d("SensorDataCollector",
                        "onActivityCreated(): Sensor ListView clicked at postion " + position);
                if (getActivity() instanceof ViewExperimentActivity) {
                    mCallback.onSensorClicked_ExperimentSensorListFragment(position);
                } else if (getActivity() instanceof CreateExperimentActivity) {
                    mCallback.onSensorClicked_ExperimentSensorListFragment(
                            (AbstractSensor) listView.getItemAtPosition(position));
                }
            }
        });
    }
}

From source file:com.google.android.apps.flexbox.MainActivity.java

private void initializeJustifyContentSpinner(Menu navigationMenu) {
    initializeSpinner(mFlexboxLayout.getJustifyContent(), R.id.menu_item_justify_content, navigationMenu,
            R.array.array_justify_content, new AdapterView.OnItemSelectedListener() {
                @Override//from   www. j  a  va 2  s.c  o  m
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    int justifyContent = FlexboxLayout.JUSTIFY_CONTENT_FLEX_START;
                    String selected = parent.getItemAtPosition(position).toString();
                    if (selected.equals(FLEX_START)) {
                        justifyContent = FlexboxLayout.JUSTIFY_CONTENT_FLEX_START;
                    } else if (selected.equals(FLEX_END)) {
                        justifyContent = FlexboxLayout.JUSTIFY_CONTENT_FLEX_END;
                    } else if (selected.equals(CENTER)) {
                        justifyContent = FlexboxLayout.JUSTIFY_CONTENT_CENTER;
                    } else if (selected.equals(SPACE_BETWEEN)) {
                        justifyContent = FlexboxLayout.JUSTIFY_CONTENT_SPACE_BETWEEN;
                    } else if (selected.equals(SPACE_AROUND)) {
                        justifyContent = FlexboxLayout.JUSTIFY_CONTENT_SPACE_AROUND;
                    }
                    mFlexboxLayout.setJustifyContent(justifyContent);
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                    // No op
                }
            }, new ValueToStringConverter() {
                @Override
                public String asString(int value) {
                    switch (value) {
                    case FlexboxLayout.JUSTIFY_CONTENT_FLEX_START:
                        return FLEX_START;
                    case FlexboxLayout.JUSTIFY_CONTENT_FLEX_END:
                        return FLEX_END;
                    case FlexboxLayout.JUSTIFY_CONTENT_CENTER:
                        return CENTER;
                    case FlexboxLayout.JUSTIFY_CONTENT_SPACE_AROUND:
                        return SPACE_AROUND;
                    case FlexboxLayout.JUSTIFY_CONTENT_SPACE_BETWEEN:
                        return SPACE_BETWEEN;
                    default:
                        return FLEX_START;
                    }
                }
            });
}

From source file:net.named_data.nfd.WiFiDirectFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_wifidirect, container, false);

    // init UI elements
    m_wdGroupConnStatus = (TextView) view.findViewById(R.id.wd_group_conn_status_textview);
    m_wdIpAddress = (TextView) view.findViewById(R.id.wd_ip_address_textview);
    m_wdDeviceName = (TextView) view.findViewById(R.id.wd_this_device_name_textview);
    m_wdIsGroupOwner = (TextView) view.findViewById(R.id.wd_group_owner_textview);
    m_wdSwitch = (Switch) view.findViewById(R.id.wd_switch);

    if (m_sharedPreferences.getBoolean(PREF_WIFIDIRECT_STATUS, false)) {
        m_wdSwitch.setChecked(true);//from w  w w. ja  va  2 s.  c  om
        startNDNOverWifiDirect();
        startUiUpdateLoop();
    } else {
        // the button was off, make any desired UI changes
        m_wdGroupConnStatus.setText("");
    }

    m_wdSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // store state of switch
            m_sharedPreferences.edit().putBoolean(PREF_WIFIDIRECT_STATUS, isChecked).apply();

            if (isChecked) {
                startNDNOverWifiDirect();
                startUiUpdateLoop();
            } else {
                stopNDNOverWifiDirect();
                stopUiUpdateLoop();
                resetUi();
            }
        }
    });

    // list view for displaying peers
    m_wdConnectedPeerListview = (ListView) view.findViewById(R.id.wd_connected_peers_listview);
    m_ConnectedPeers = new ArrayList<>(NDNController.getInstance().getConnectedPeers());
    m_DicoveredPeers = new ArrayList<>(NDNController.getInstance().getDiscoveredPeers());

    m_ConnectedPeersAdapter = new ConnectPeerListAdapter(getActivity(), R.layout.row_devices, m_ConnectedPeers);
    m_wdConnectedPeerListview.setAdapter(m_ConnectedPeersAdapter);
    m_wdConnectedPeerListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Peer selectedPeer = (Peer) parent.getItemAtPosition(position);

            // toast a quick message!
            if (selectedPeer == null) {
                Toast.makeText(getActivity(),
                        getResources().getString(R.string.fragment_wifidirect_toast_peer_no_longer_available),
                        Toast.LENGTH_LONG).show();
            } else {
                String peerInfo = selectedPeer.getNumProbeTimeouts() == 0
                        ? getResources().getString(R.string.fragment_wifidirect_toast_connection_works_well)
                        : getResources().getString(R.string.fragment_wifidirect_toast_didnt_get_response)
                                + (selectedPeer.getNumProbeTimeouts() * NDNController.PROBE_DELAY / 1000)
                                + getResources().getString(R.string.fragment_wifidirect_toast_seconds);
                Toast.makeText(getActivity(), peerInfo, Toast.LENGTH_LONG).show();
            }
        }
    });

    m_wdDiscoveredPeerListview = (ListView) view.findViewById(R.id.wd_discovered_peers_listview);
    m_DiscoveredPeersAdapter = new DiscoveredPeerListAdapter(getActivity(), R.layout.row_devices,
            m_DicoveredPeers);
    m_wdDiscoveredPeerListview.setAdapter(m_DiscoveredPeersAdapter);

    m_wdDiscoveredPeerListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            final WifiP2pDevice device = (WifiP2pDevice) parent.getItemAtPosition(position);

            if (device.status == WifiP2pDevice.INVITED) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setMessage(
                        getResources().getString(R.string.fragment_wifidirect_dialog_cancel_invitation)
                                + device.deviceName + getResources().getString(R.string.question_mark))
                        .setCancelable(false)
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                m_progressDialog = show(getActivity(),
                                        getResources()
                                                .getString(R.string.fragment_wifidirect_dialog_cancelling),
                                        getResources().getString(
                                                R.string.fragment_wifidirect_dialog_cancelling_invitation)
                                                + device.deviceName,
                                        true, true);
                                m_progressDialog.setCancelable(false);

                                NDNController.getInstance().cancelConnect();
                            }
                        }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                return;
                            }
                        });
                AlertDialog dialog = builder.create();
                dialog.show();
                return;
            }

            if (device.status == WifiP2pDevice.CONNECTED) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                String alertMessage = getResources()
                        .getString(R.string.fragment_wifidirect_dialog_disconnect_from) + device.deviceName
                        + getResources().getString(R.string.question_mark);
                if (NDNController.getInstance().getIsGroupOwner()) {
                    alertMessage = alertMessage
                            + getResources().getString(R.string.fragment_wifidirect_dialog_destroy_group_alter);
                }
                builder.setMessage(alertMessage).setCancelable(false)
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                m_progressDialog = show(getActivity(),
                                        getResources()
                                                .getString(R.string.fragment_wifidirect_dialog_disconnecting),
                                        getResources().getString(
                                                R.string.fragment_wifidirect_dialog_disconnecting_from)
                                                + device.deviceName,
                                        true, true);
                                m_progressDialog.setCancelable(false);

                                NDNController.getInstance().disconnect();
                            }
                        }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                return;
                            }
                        });
                AlertDialog dialog = builder.create();
                dialog.show();
                return;
            }

            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage(
                    getResources().getString(R.string.fragment_wifidirect_dialog_invite) + device.deviceName
                            + getResources().getString(R.string.fragment_wifidirect_dialog_join_group)
                            + getResources().getString(R.string.question_mark))
                    .setCancelable(false)
                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            m_progressDialog = ProgressDialog.show(getActivity(),
                                    getResources().getString(R.string.fragment_wifidirect_dialog_inviting),
                                    getResources().getString(R.string.fragment_wifidirect_dialog_inviting)
                                            + device.deviceName
                                            + getResources()
                                                    .getString(R.string.fragment_wifidirect_dialog_join_group),
                                    true, true);
                            m_progressDialog.setCancelable(false);

                            NDNController.getInstance().connect(device);
                        }
                    }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            return;
                        }
                    });
            AlertDialog dialog = builder.create();
            dialog.show();
        }
    });
    return view;
}

From source file:com.garlicg.screenrecord4cm.SettingsActivity.java

/**
 * Create video size setting view/*from www  .java 2 s  .  c  o m*/
 */
private void createVideoSize(Bundle savedInstanceState) {
    int vp = mPrefs.getVideoPercentage();
    final VideoPercentage[] spinnerItems = AppPrefs.videoPercentages();
    int spinnerSelection = AppPrefs.findVideoPercentagePosition(spinnerItems, vp);

    ArrayAdapter<VideoPercentage> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item,
            spinnerItems);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    final Spinner spinner = ViewFinder.byId(this, R.id.videoPercentageSpinner);
    spinner.setAdapter(adapter);

    spinner.setSelection(spinnerSelection);
    spinner.post(new Runnable() {
        @Override
        public void run() {
            // setSelection later
            spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    if (view == null)
                        return;

                    VideoPercentage item = (VideoPercentage) parent.getItemAtPosition(position);
                    new AppPrefs(view.getContext()).saveVideoPercentage(item);
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                }
            });
        }
    });
}

From source file:com.cmput301w17t07.moody.CreateMoodActivity.java

/**
 * displayAttributes method used when the user gets back from the "Map" display
 * and displays the changed spinner attributes.
 * <br>/*from  w w  w .  j av  a2s. c o m*/
 * Spinner dropdown logic taken from <br>
 * link: http://stackoverflow.com/questions/13377361/how-to-create-a-drop-down-listm <br>
 * Author: Nicolas Tyler, 2013/07/15 8:47 <br>
 * taken by Xin Huang 2017-03-04 15:30 (used and switch function written by Nick 2017/03/12 14:30) <br>
 */
private void displayAttributes() {
    Spinner dropdown = (Spinner) findViewById(R.id.Emotion);
    String[] items = new String[] { "anger", "confusion", "disgust", "fear", "happiness", "sadness", "shame",
            "surprise" };
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item,
            items);
    dropdown.setAdapter(adapter);

    switch (tempMood.getFeeling()) {
    case "anger":
        dropdown.setSelection(0);
        break;
    case "confusion":
        dropdown.setSelection(1);
        break;
    case "disgust":
        dropdown.setSelection(2);
        break;
    case "fear":
        dropdown.setSelection(3);
        break;
    case "happiness":
        dropdown.setSelection(4);
        break;
    case "sadness":
        dropdown.setSelection(5);
        break;
    case "shame":
        dropdown.setSelection(6);
        break;
    case "surprise":
        dropdown.setSelection(7);
        break;

    }
    dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            EmotionText = parent.getItemAtPosition(position).toString();
            tempMood.setFeeling(EmotionText);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            Toast.makeText(CreateMoodActivity.this, "Please pick a feeling!", Toast.LENGTH_SHORT).show();
        }
    });

    Spinner dropdown_SocialSituation = (Spinner) findViewById(R.id.SocialSituation);
    String[] item_SocialSituation = new String[] { "", "alone", "with one other person", "with two people",
            "with several people", "with a crowd" };
    ArrayAdapter<String> adapter_SocialSituation = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_dropdown_item, item_SocialSituation);
    dropdown_SocialSituation.setAdapter(adapter_SocialSituation);
    switch (tempMood.getSocialSituation()) {
    case "alone":
        dropdown_SocialSituation.setSelection(1);
        break;
    case "with one other person":
        dropdown_SocialSituation.setSelection(2);
        break;
    case "with two people":
        dropdown_SocialSituation.setSelection(3);
        break;
    case "with several people":
        dropdown_SocialSituation.setSelection(4);
        break;
    case "with a crowd":
        dropdown_SocialSituation.setSelection(5);
        break;

    }

    dropdown_SocialSituation.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            SocialSituation = parent.getItemAtPosition(position).toString();
            tempMood.setSocialSituation(SocialSituation);
            TextView sizeView = (TextView) findViewById(R.id.SocialText);
            sizeView.setText("  " + SocialSituation);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            Toast.makeText(CreateMoodActivity.this, "Please pick a feeling!", Toast.LENGTH_SHORT).show();
        }
    });
}

From source file:com.kunze.androidlocaltodo.TaskListActivity.java

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Cursor cursor = (Cursor) parent.getItemAtPosition(position);
    final Task task = mDB.LoadTask(cursor);
    ShowTaskDialog(task, new OnClickListener() {
        @Override/* w ww.  jav  a 2  s . c  om*/
        public void onClick(DialogInterface dialog, int which) {
            mDB.SaveTask(task);
            RefreshView();
        }
    });
}

From source file:com.orange.datavenue.StreamListFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    if (mStreamAdapter == null) {
        mStreamAdapter = new StreamAdapter(getActivity(), R.layout.stream_item, R.id.name, mStreams);
        setListAdapter(mStreamAdapter);//from   w w  w .ja va  2 s . co  m
        getStreams();
    }

    getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Log.d(TAG_NAME, "onItemClick()");
            if (mActionMode != null) {
                mActionMode.finish();
            }
            Model.instance.currentStream = (Stream) parent.getItemAtPosition(position);
            ((StreamActivity) getActivity()).changeLayout(StreamActivity.MODE_DETAIL);
        }

    });

    getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            Log.d(TAG_NAME, "onItemLongClick()");
            Model.instance.currentStream = (Stream) parent.getItemAtPosition(position);
            mSelected = position;
            getListView().setItemChecked(mSelected, true);
            mActionMode = ((AppCompatActivity) getActivity()).startSupportActionMode(mActionModeCallback);
            return true;
        }
    });

}

From source file:org.wheelmap.android.fragment.SearchDialogFragment.java

@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {

    if (adapterView == mCategorySpinner) {
        CategoryOrNodeType search = (CategoryOrNodeType) adapterView.getAdapter().getItem(position);
        switch (search.type) {
        case CATEGORY:
            mCategorySelected = search.id;
            break;
        case NODETYPE:
            mNodeTypeSelected = search.id;
            break;
        }//from w ww  .j a v  a  2  s . c  o  m
    } else if (adapterView == mDistanceSpinner) {
        String distance = (String) adapterView.getItemAtPosition(position);
        try {
            mDistance = Float.valueOf(distance);
        } catch (NumberFormatException e) {
            mDistance = Extra.UNKNOWN;
        }
    }
}

From source file:org.gots.ui.TabSeedActivity.java

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {

        String cameraFilename = savedInstanceState.getString("CAMERA_FILENAME");
        if (cameraFilename != null)
            cameraPicture = new File(cameraFilename);
    }/*from   w  ww.j a  va2 s.co m*/

    gotsPurchase = new GotsPurchaseItem(this);
    GotsAnalytics.getInstance(getApplication()).incrementActivityCount();
    GoogleAnalyticsTracker.getInstance().trackPageView(getClass().getSimpleName());

    setContentView(R.layout.seed_tab);

    ActionBar bar = getSupportActionBar();
    bar.setDisplayHomeAsUpEnabled(true);
    // bar.setDisplayShowTitleEnabled(false);

    getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // ********************** **********************
    if (getIntent().getExtras() == null) {
        Log.e("SeedActivity", "You must provide a org.gots.seed.id as an Extra Int");
        finish();
        return;
    }
    if (getIntent().getExtras().getInt(GOTS_GROWINGSEED_ID) != 0) {
        int seedId = getIntent().getExtras().getInt(GOTS_GROWINGSEED_ID);
        mSeed = GotsGrowingSeedManager.getInstance().initIfNew(this).getGrowingSeedById(seedId);
    } else if (getIntent().getExtras().getInt(GOTS_VENDORSEED_ID) != 0) {
        int seedId = getIntent().getExtras().getInt(GOTS_VENDORSEED_ID);
        GotsSeedProvider helper = new LocalSeedProvider(getApplicationContext());
        mSeed = (GrowingSeedInterface) helper.getSeedById(seedId);
    } else
        mSeed = new GrowingSeed(); // DEFAULT SEED

    //        if (getIntent().getSerializableExtra(GOTS_TASKWORKFLOW_ID) != null)
    //            taskWorkflow = (TaskInfo) getIntent().getSerializableExtra(GOTS_TASKWORKFLOW_ID);
    pictureGallery = (Gallery) findViewById(R.id.idPictureGallery);

    displayPictureGallery();

    pictureGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
            File f = (File) arg0.getItemAtPosition(position);
            File dest = new File(gotsPrefs.getGotsExternalFileDir(), f.getName());
            try {
                FileUtilities.copy(f, dest);
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.fromFile(dest), "image/*");
                startActivity(intent);
            } catch (IOException e) {
                Log.w(TAG, e.getMessage());
            }

        }
    });

    bar.setTitle(mSeed.getSpecie());

    SeedWidgetLong seedWidget = (SeedWidgetLong) findViewById(R.id.IdSeedWidgetLong);
    seedWidget.setSeed(mSeed);

    if (mSeed.getDateSowing() != null) {
        TextView textDateSowing = (TextView) findViewById(R.id.idTextSowingDate);
        textDateSowing.setText(new SimpleDateFormat().format(mSeed.getDateSowing()));

        TextView textDateHarvest = (TextView) findViewById(R.id.idTextHarvestDate);
        if (mSeed.getDateHarvest().getTime() > 0)
            textDateHarvest.setText(new SimpleDateFormat().format(mSeed.getDateHarvest()));
        else {
            Calendar plannedHarvest = Calendar.getInstance();
            plannedHarvest.setTime(mSeed.getDateSowing());
            plannedHarvest.add(Calendar.DAY_OF_YEAR, mSeed.getDurationMin());
            textDateHarvest.setText(new SimpleDateFormat().format(plannedHarvest.getTime()));
            textDateHarvest.setAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.tween));
        }
    } else
        findViewById(R.id.idLayoutCulturePeriod).setVisibility(View.GONE);

    mViewPager = (ViewPager) findViewById(R.id.pager);
    TabsAdapter mTabsAdapter = new TabsAdapter(this, mViewPager);

    // ********************** Tab actions **********************
    if (mSeed.getGrowingSeedId() > 0) {
        mTabsAdapter.addTab(
                bar.newTab().setTag("event_list").setText(getString(R.string.seed_description_tabmenu_actions)),
                ListActionActivity.class, null);
    }
    // // ********************** Tab description **********************
    mTabsAdapter.addTab(
            bar.newTab().setTag("event_list").setText(getString(R.string.seed_description_tabmenu_detail)),
            SeedActivity.class, null);

    // ********************** Tab Wikipedia**********************
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        mTabsAdapter.addTab(bar.newTab().setTag("event_list")
                .setText(getString(R.string.seed_description_tabmenu_wikipedia)), WebViewActivity.class, null);

        urlDescription = "http://" + Locale.getDefault().getLanguage() + ".wikipedia.org/wiki/"
                + mSeed.getSpecie();

    }

    if (!gotsPurchase.isPremium()) {
        GotsAdvertisement ads = new GotsAdvertisement(this);

        LinearLayout layout = (LinearLayout) findViewById(R.id.idAdsTop);
        layout.addView(ads.getAdsLayout());
    }

    Fragment fragment = new WorkflowTaskFragment();
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.frame_workflow, fragment).commit();

}

From source file:com.duongnx.ndk.examples.activities.NativeAudioActivity.java

/**
 * Called when the activity is first created.
 *//*from w w w . j  av a 2  s . c  o m*/
@Override
@TargetApi(17)
protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.activity_native_audio);
    setTitle(Defines.NATIVE_AUDIO);
    assetManager = getAssets();

    // initialize native audio system
    createEngine();

    int sampleRate = 0;
    int bufSize = 0;
    /*
     * retrieve fast audio path sample rate and buf size; if we have it, we pass to native
     * side to create a player with fast audio enabled [ fast audio == low latency audio ];
     * IF we do not have a fast audio path, we pass 0 for sampleRate, which will force native
     * side to pick up the 8Khz sample rate.
     */
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        AudioManager myAudioMgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        String nativeParam = myAudioMgr.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE);
        sampleRate = Integer.parseInt(nativeParam);
        nativeParam = myAudioMgr.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER);
        bufSize = Integer.parseInt(nativeParam);
    }
    createBufferQueueAudioPlayer(sampleRate, bufSize);

    // initialize URI spinner
    Spinner uriSpinner = (Spinner) findViewById(R.id.uri_spinner);
    ArrayAdapter<CharSequence> uriAdapter = ArrayAdapter.createFromResource(this, R.array.uri_spinner_array,
            android.R.layout.simple_spinner_item);
    uriAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    uriSpinner.setAdapter(uriAdapter);
    uriSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            URI = parent.getItemAtPosition(pos).toString();
        }

        public void onNothingSelected(AdapterView parent) {
            URI = null;
        }

    });

    // initialize button click handlers

    ((Button) findViewById(R.id.hello)).setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            // ignore the return value
            selectClip(CLIP_HELLO, 5);
        }
    });

    ((Button) findViewById(R.id.android)).setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            // ignore the return value
            selectClip(CLIP_ANDROID, 7);
        }
    });

    ((Button) findViewById(R.id.sawtooth)).setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            // ignore the return value
            selectClip(CLIP_SAWTOOTH, 1);
        }
    });

    ((Button) findViewById(R.id.reverb)).setOnClickListener(new OnClickListener() {
        boolean enabled = false;

        public void onClick(View view) {
            enabled = !enabled;
            if (!enableReverb(enabled)) {
                enabled = !enabled;
            }
        }
    });

    ((Button) findViewById(R.id.embedded_soundtrack)).setOnClickListener(new OnClickListener() {
        boolean created = false;

        public void onClick(View view) {
            if (!created) {
                created = createAssetAudioPlayer(assetManager, "background.mp3");
            }
            if (created) {
                isPlayingAsset = !isPlayingAsset;
                setPlayingAssetAudioPlayer(isPlayingAsset);
            }
        }
    });

    // native uriPlayer is broken in android 21 and over, internal bug id: b/29321867
    // will re-open after it is fixed in later OSes
    if (Build.VERSION.SDK_INT <= 19) {
        ((Button) findViewById(R.id.uri_soundtrack)).setOnClickListener(new OnClickListener() {
            boolean created = false;

            public void onClick(View view) {
                if (!created && URI != null) {
                    created = createUriAudioPlayer(URI);
                }
            }
        });

        ((Button) findViewById(R.id.pause_uri)).setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                setPlayingUriAudioPlayer(false);
            }
        });

        ((Button) findViewById(R.id.play_uri)).setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                setPlayingUriAudioPlayer(true);
            }
        });

        ((Button) findViewById(R.id.loop_uri)).setOnClickListener(new OnClickListener() {
            boolean isLooping = false;

            public void onClick(View view) {
                isLooping = !isLooping;
                setLoopingUriAudioPlayer(isLooping);
            }
        });

        ((Button) findViewById(R.id.mute_left_uri)).setOnClickListener(new OnClickListener() {
            boolean muted = false;

            public void onClick(View view) {
                muted = !muted;
                setChannelMuteUriAudioPlayer(0, muted);
            }
        });

        ((Button) findViewById(R.id.mute_right_uri)).setOnClickListener(new OnClickListener() {
            boolean muted = false;

            public void onClick(View view) {
                muted = !muted;
                setChannelMuteUriAudioPlayer(1, muted);
            }
        });

        ((Button) findViewById(R.id.solo_left_uri)).setOnClickListener(new OnClickListener() {
            boolean soloed = false;

            public void onClick(View view) {
                soloed = !soloed;
                setChannelSoloUriAudioPlayer(0, soloed);
            }
        });

        ((Button) findViewById(R.id.solo_right_uri)).setOnClickListener(new OnClickListener() {
            boolean soloed = false;

            public void onClick(View view) {
                soloed = !soloed;
                setChannelSoloUriAudioPlayer(1, soloed);
            }
        });

        ((Button) findViewById(R.id.mute_uri)).setOnClickListener(new OnClickListener() {
            boolean muted = false;

            public void onClick(View view) {
                muted = !muted;
                setMuteUriAudioPlayer(muted);
            }
        });

        ((Button) findViewById(R.id.enable_stereo_position_uri)).setOnClickListener(new OnClickListener() {
            boolean enabled = false;

            public void onClick(View view) {
                enabled = !enabled;
                enableStereoPositionUriAudioPlayer(enabled);
            }
        });

        ((Button) findViewById(R.id.channels_uri)).setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                if (numChannelsUri == 0) {
                    numChannelsUri = getNumChannelsUriAudioPlayer();
                }
                Toast.makeText(NativeAudioActivity.this, "Channels: " + numChannelsUri, Toast.LENGTH_SHORT)
                        .show();
            }
        });

        ((SeekBar) findViewById(R.id.volume_uri)).setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            int lastProgress = 100;

            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (BuildConfig.DEBUG && !(progress >= 0 && progress <= 100)) {
                    throw new AssertionError();
                }
                lastProgress = progress;
            }

            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            public void onStopTrackingTouch(SeekBar seekBar) {
                int attenuation = 100 - lastProgress;
                int millibel = attenuation * -50;
                setVolumeUriAudioPlayer(millibel);
            }
        });

        ((SeekBar) findViewById(R.id.pan_uri)).setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            int lastProgress = 100;

            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (BuildConfig.DEBUG && !(progress >= 0 && progress <= 100)) {
                    throw new AssertionError();
                }
                lastProgress = progress;
            }

            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            public void onStopTrackingTouch(SeekBar seekBar) {
                int permille = (lastProgress - 50) * 20;
                setStereoPositionUriAudioPlayer(permille);
            }
        });
    } else {
        int[] uriIds = { R.id.uri_soundtrack, R.id.pause_uri, R.id.play_uri, R.id.loop_uri, R.id.mute_left_uri,
                R.id.mute_right_uri, R.id.solo_left_uri, R.id.solo_right_uri, R.id.mute_uri,
                R.id.enable_stereo_position_uri, R.id.channels_uri, R.id.volume_uri, R.id.pan_uri,
                R.id.uri_spinner, };
        for (int id : uriIds)
            findViewById(id).setVisibility(View.GONE);
    }

    ((Button) findViewById(R.id.record)).setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            int status = ActivityCompat.checkSelfPermission(NativeAudioActivity.this,
                    Manifest.permission.RECORD_AUDIO);
            if (status != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(NativeAudioActivity.this,
                        new String[] { Manifest.permission.RECORD_AUDIO }, AUDIO_ECHO_REQUEST);
                return;
            }
            recordAudio();
        }
    });

    ((Button) findViewById(R.id.playback)).setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            // ignore the return value
            selectClip(CLIP_PLAYBACK, 3);
        }
    });

}