Android Studio Button Listener Key Listener And Browse Url Example

This example will show you how to use android studio to create and register Button OnClickListener and Text Input Box OnKeyListener object to listen to the specified event. And it also shows you how to open a web browser to browse a web page url.

Below is the UI when this app startup, you can see there are two view components, one is an input text box the other is a button. If the user inputs a web page URL in the top input text box, when he click the BROWSE button or press enter key, the app will open a web browser to browse the url page.
android-onclicklistener-and-onkeylistener-ui

1. Add example UI components.

  1. Right-click the android project name, click the ” New —> Activity —> Empty Activity ” menu item to create a new activity.
  2. Input the activity name and layout name or you can use the default name generated automatically.
  3. Click Finish to complete the wizard. Now you can see the activity java file and the layout XML file in the left tree panel, double click the layout XML file, click the bottom Design tab. Then you can add the LinearLayout component in the root ConstraintLayout.
  4. From the Palette, drag and drop an EditText (Plain Text) and a Button view component in the LinearLayout component.

2. Edit layout and activity file content.

Click bottom Text tab, edit above layout XML file, edit text and button component’s properties as below.

2.1 activity_button_listener_example.xml.

<LinearLayout
     android:layout_width="368dp"
     android:layout_height="wrap_content"
     android:orientation="vertical"
     tools:layout_editor_absoluteX="8dp"
     tools:layout_editor_absoluteY="8dp">

     <EditText
         android:id="@+id/txtPageUrl"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:ems="10"
         android:inputType="textPersonName"
         android:text="Input desired web page url"
         android:textStyle="bold" />

     <Button
         android:id="@+id/btnBrowsePage"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:text="Browse" />
</LinearLayout>

2.2 ButtonListenerExampleActivity.java.

package com.dev2qa.www.helloworldexampleproject;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class ButtonListenerExampleActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Set content view to use the new layout xml file.
        setContentView(R.layout.activity_button_listener_example);

        // Get the page url input component.
        EditText editTxtPageUrl = (EditText)this.findViewById(R.id.txtPageUrl);
        // Create page url text on key action listener.
        PageUrlTextKeyListener pageUrlTextKeyListener = new PageUrlTextKeyListener();
        // Regist text box onkey listener object.
        editTxtPageUrl.setOnKeyListener(pageUrlTextKeyListener);

        // Get the browse button component.
        Button btnBrowsePage = (Button)this.findViewById(R.id.btnBrowsePage);
        // Create button click listener.
        BrowseButtonListener browseButtonListener = new BrowseButtonListener();
        browseButtonListener.setEditTxtPageUrl(editTxtPageUrl);
        // Regist button click listener object.
        btnBrowsePage.setOnClickListener(browseButtonListener);
    }
}

// This class listen to browse button click event.
class BrowseButtonListener implements View.OnClickListener
{
    // Reference to owner activity's EditText view to get user input text.
    private EditText editTxtPageUrl = null;

    public void setEditTxtPageUrl(EditText editTxtPageUrl) {
        this.editTxtPageUrl = editTxtPageUrl;
    }

    @Override
    public void onClick(View v) {
        if(this.editTxtPageUrl!=null)
        {
            // If user click Browse button then open above page url in a web browser.
            String pageUrl = this.editTxtPageUrl.getText().toString();
            // Browse the provided web page url.
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(pageUrl));
            // Use view component's context to start browser.
            v.getContext().startActivity(intent);
        }
    }
}

// This class listen to EditText input box key event.
class PageUrlTextKeyListener implements View.OnKeyListener
{
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        // Convert the v to EditText object.
        EditText editTextPageUrl = (EditText)v;
        // Get the input text.
        String pageUrl = editTextPageUrl.getText().toString();

        // If the text is default text then clear the EditText input box.
        if("Input desired web page url".equalsIgnoreCase(pageUrl))
        {
            editTextPageUrl.setText("");
            return false;
        }else {
            // If user press enter key.
            if (KeyEvent.KEYCODE_ENTER == keyCode) {
                // Browse the provided web page url.
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(pageUrl));
                // Use view component's context to start browser.
                v.getContext().startActivity(intent);
                return true;
            }
            return false;
        }
    }
}

If you do not remember the override method name or imported java class name, you can click the Code —> Override Methods… menu item in the top toolbar. The Code drop-down menu list has a lot of helper menus to generate common codes.

3. Eidt AndroidManifest.xml and run the example.

Before you can run the above example, you should edit AndroidManifest.xml as below. This will launch the newly created activity by default.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.dev2qa.www.helloworldexampleproject">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".ButtonListenerExampleActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Right-click the new activity class name ( start with a ©), not the java file name, click the “Run ButtonListenerExampleActivity…” menu, after some time, you can see the device simulator startup and show the UI at this article beginning. If you enter the correct web url and click enter key or click the BROWSE button, it will pop up a web browser and then browse the web page.

0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x