Andriod programming – Posts 3: Getting Button Click event

Days before his very detailed study, the Android is impatient in wanting to know how to click buttons that change the letter TextView. So this article we will learn how to get Button to manipulate events to TextView and EditText. We will continue in the post Project 2 and the task is how to click buttons when the TextView display the words that we have entered in EditText.

[qads]

We review the previous day a bit interface as follows:
text-edit-button

To be able to manipulate with Button and TextView and EditText we must connect these elements to java code java code to manipulate with them. To connect to java, each element should have 1 id. Can you understand id is an identification number for each element. We set the id to elements such as the following TextView android:id=”@+id/tv”. Whereby tv TextView is the identity of that. After this you should set tvName, tvPhone,… TextView tv stands, Name is the name, Phone is the phone, ie TextView to display to display the names and phone TextView. So our code would look like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.nguyenvanquan7826.tut2texteditbutton.MainActivity">

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <EditText
        android:id="@+id/edit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter text here" />

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click me" />

</LinearLayout>

Once you've set the id of the component, MainActivity.java file you back to start implementing code.
Since this article we are all touched first his java code should introduce a little. Currently our Java code as follows:

package com.nguyenvanquan7826.tut2texteditbutton;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

Unlike in pure Java that you learned earlier. We will not have the main function to start a program that each Activity will start running by function onCreate. Here:

  • super.onCreate(savedInstanceState); is of AppCompatActivity onCreate function calls that currently inherit.
  • setContentView(R.layout.activity_main); the orders of our interface is activity_main.xml file – our main xml file was manipulated from the beginning until now. If you create 1 other xml files in / res / layout, we absolutely can set it as the interface for this Acitivity setContentView command.

Now we begin the main part is connected to the processor and interface. To connect interface, we will declare the corresponding variable of type Button, EditText và TextView. You see the following code:

package com.nguyenvanquan7826.tut2texteditbutton;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    /*
    * khai bao cac bien view
    * */
    private TextView tv;
    private EditText edit;
    private Button btn;

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

        // goi ham ket noi view
        connectView();
    }
    /*
    * ket noi cac thanh phan view
    * */
    private void connectView() {
        tv = (TextView) findViewById(R.id.tv);
        edit = (EditText) findViewById(R.id.edit);
        btn = (Button) findViewById(R.id.btn);
    }
}

After quotations corresponding variables that we need actions in line 14, 15, 16, we call the function onCreate connectView. ConnectView function is the function that we write to connect to the interface. To connect the elements we use function findViewById for transmission to the R.id.xyz where xyz is the id that we have set for the elements in the XML file. However, this function returns the type of View (View is the father of all types of components, ie TextView, EditText, Button,… are inherited from View) So we need a cast on the exact type of each element as above.

So is the connection to the interface is done. Now we begin to do capture the event for the Button by calling setOnClickListener. We have many events to capture, however I only guide you 2 The most common way that I would like people often use.

How to 1: Arrested at game

/*
* ket noi cac thanh phan view
* */
private void connectView() {
    tv = (TextView) findViewById(R.id.tv);
    edit = (EditText) findViewById(R.id.edit);
    btn = (Button) findViewById(R.id.btn);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            doClickButton();
        }
    });
}

private void doClickButton() {
    String text = edit.getText().toString().trim();
    tv.setText(text);
    edit.setText("");
}

The more you write btn.setOnClickListener in parentheses and writing is new OnC the suggestion box will appear and you select the first one is View.OnClickListener it is 1 interface to automatically generate code for your function onClick.
setOnClickListener-button

Ie when you click on the button, the system will call onClick, It is now just what we wanted, but here is take it on the text in EditText TextView. We write function and call it in the onClick doClickButton. In function doClickButton, we see 3 current.

  • The first line of the text is taken out EditText String text assigned to the variable (toString function is to turn what we took out a chain, trim function is to remove blanks at the beginning and end if). Thus we EditText text by taking the function gettext();
  • The second line is the text book we have to get on with the function TextView setText(text)
  • The third line, We deleted text in EditText.

Now you run and enjoy the fruits alone.
event-click-button

How to 2: Getting to the many buttons at once

If you notice, is the way 1, every button we will be 1 and event segment for its own. Thus in the case of multiple Button (As VD as handheld computers) the code will be very lengthy and inconvenient. So how 2 will be suitable for such cases. The way you can edit the code of the event starts as follows.

/*
* ket noi cac thanh phan view
* */
private void connectView() {
    tv = (TextView) findViewById(R.id.tv);
    edit = (EditText) findViewById(R.id.edit);
    btn = (Button) findViewById(R.id.btn);

    btn.setOnClickListener(this);
}

That means we do not create new OnClickListener again that this is passed into the function setOnClickListener. But now you will see an error. Put the cursor on the word this, where he failed, then press Everything + Enter you'll see a dialog box appears hints:
implement-onlick-button

You select the row 2 was Make MainAcitvity implement View.OnClickListener, The following dialog box appears, you select OK.
implement-method-onclick

Wait a student will perform system code and you will see the function Spontaneous onClick and at par with the function onCreate, above, the class lines more implements View.OnClickListener. Here we understand that the entire class is an interface MainAcitivty example, View.OnClickListener so it can function to execute the arrest onClick events for the entire button (or certain view) has called setOnClickListener(this); So we can start event for a lot of buttons simultaneously. To distinguish what we click on the button at the onClick function has 1 turn View, which is what do we distinguish. Suppose we add 1 In addition to the interface button to delete the text in EditText our code will be as follows:

Interface Code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.nguyenvanquan7826.tut2texteditbutton.MainActivity">

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <EditText
        android:id="@+id/edit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter text here" />

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click me" />

    <Button
        android:id="@+id/btnClear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Clear" />

</LinearLayout>

Code Java.

package com.nguyenvanquan7826.tut2texteditbutton;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    /*
    * khai bao cac bien view
    * */
    private TextView tv;
    private EditText edit;
    private Button btn;
    private Button btnClear;

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

        // goi ham ket noi view
        connectView();
    }

    /*
    * ket noi cac thanh phan view
    * */
    private void connectView() {
        tv = (TextView) findViewById(R.id.tv);
        edit = (EditText) findViewById(R.id.edit);
        btn = (Button) findViewById(R.id.btn);
        btnClear = (Button) findViewById(R.id.btnClear);

        // set on click
        btn.setOnClickListener(this);
        btnClear.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn:
                doClickButton();
                break;
            case R.id.btnClear:
                doClickButtonClear();
                break;
        }
    }

    private void doClickButton() {
        String text = edit.getText().toString().trim();
        tv.setText(text);
        edit.setText("");
    }

    private void doClickButtonClear() {
        edit.setText("");
    }

}

Today we stop here. Rất mong các bạn có thể hiểu và thực hành tốt việc bắt sự kiện cho button cũng như việc thao tác đặt text, lấy text từ TextView và EditText.