Open a website through a button in the app

Asked

Viewed 29 times

1

I’m making an application similar to a schedule and need to put a button to open a registered site, I’ve done with a long click on the table and it worked however, on a button I can not use the same syntax

@Override
    public void onCreateContextMenu(final ContextMenu menu, View v, final ContextMenu.ContextMenuInfo menuInfo) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        final Aluno aluno = (Aluno) listaAlunos.getItemAtPosition(info.position);

    MenuItem itemSite = menu.add("Visitar Site");
    Intent intentSite = new Intent(Intent.ACTION_VIEW);

    String site ="http://www.uol.com.br";
            aluno.getSite();
    if(!site.startsWith("http://")) {
        site = "http://" + site;
    }

    intentSite.setData(Uri.parse(site));
    itemSite.setIntent(intentSite);

1 answer

0

First, I recommend inflating the context menus instead of creating manually. But do it this way below:

Menu XML (menu_site.xml)

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/visitar_site"
        android:title="Visitar Site">
    </item>
</menu>

onCreateContextMenu

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
    getMenuInflater().inflate(R.menu.menu_site, menu);
    super.onCreateContextMenu(menu, v, menuInfo);
}

onContextItemSelected (here you will put the code to open the site

@Override
public boolean onContextItemSelected(MenuItem item)
{
        switch (item.getItemId())
        {
            case R.id.pick_camera: {
                Intent intentSite = new Intent(Intent.ACTION_VIEW);

                String site ="http://www.uol.com.br";
                        aluno.getSite();
                if(!site.startsWith("http://")) {
                    site = "http://" + site;
                }

                intentSite.setData(Uri.parse(site));
                startActivity(intentSite);
            } break;
        }
    return super.onContextItemSelected(item);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.