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:
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.
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.
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:
You select the row 2 was Make MainAcitvity implement View.OnClickListener, The following dialog box appears, you select OK.
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.
A dear, a làm cái Tut Máy tính cầm tay đi a 😀
Sẽ có bạn nhé.
a oi, bay gio em muon nhap tu 1 screen roi xuat ra 1 screen khac thi lam nhu nao a? (E set lam 2 activity, 1 cai nhap, con cai xuat e chua biet lam kieu gi)
Bạn dùng Intent nhé. Khi startActivity thì dùng startActivityForResult. Có thể xem kỹ hơn tại đây: https://www.cachhoc.net/2016/07/14/lap-trinh-android-bai-8-intent-chuyen-doi-giua-cac-man-hinh/
sao mà giao diện trong điện thoại ảo của e thì chỗ button đè lên chỗ nhập text luôn? không có giống như hình anh minh họa. Cách khắc phục như thế nào hả anh?
Cách khắc phục là bạn code giao diện chứ không kéo thả 🙂
Welcome Military. Rất vui được làm quen với bạn. Mình chưa biết gì ltrinh android. nhưng rất thích cái này. Đang ấp ủ làm 1 ứng dụng như sau. Bạn hướng dẫn giúp mình nhé:
Tạo nhiều button:
+ Button A: khi nhấn button này, android phone will call 1 certain number of machines in 3 Ring tone (hay 5s) then off, This process repeats until we hit the off button. Like flashed repeatedly until no more shots
+ Button B: Also the call button but no shots, waiting for the other side picked up the phone, the button C, D, E show up (Initially the C button,D,E status hidden.
+ The C button, D ,E is the number buttons 1, 2, 3, 4… trong bàn phím khi gọi trên điện thoại vậy. CEO: khi nhấn C thì điện thoại gọi gửi phím số 1 đến điện thoại nghe.
Thank you
Welcome, để làm được các việc đó bạn cứ search từ khóa theo bạn mô tả là được 🙂
Anh cho em hỏi là mình có thể ép kiểu đối tượng trong java mà hai đối tượng này cùng kế thừa từ 1 cha.Vi class object class instance object and layer object SVBach Sciences SV traffic is the same object class inherits from sinhvien.Em want to cast SV Transport SV bachkhoa
This is not offline.
studying all 3 thank Uncle Military, hopes of completing the program, doctors
làm sao để cho nút nhấn hiểu nếu mình còn nhấn thì còn thực hiện vậy anh
You can catch the event OnTouch.
Or too
My brother asked for e e want the clip to the button link to 1 google page milling, we must do s a? tl from a desire sentence
You see here nhé: https://stackoverflow.com/questions/21973415/how-to-open-google-play-store-with-button-click
My brother helped me
for example, you have the answer A B C D
Kids holding answers A and optional B C D is still.
I want to ask is when holding 1 answers the press are different answers k sir
Try google you see: https://www.google.com/search?q=mutile+select+item+android&rlz=1C5CHFA_enVN787VN787&oq=mutile+select+item+android&aqs=chrome..69i57j0l3.10930j0j1&sourceid=chrome&ie=UTF-8
em bắt đầu tìm hiểu về android, vừa đọc mấy dòng dẫn ở đầu em đã nghĩ ngay ra là sinh viên trường mình là chủ trang web này rồi ^_^ liệu có phải do cùng 1 môi trường dạy nên có lối suy nghĩ giống nhau ko anh ^_^
Cái này thì ko rõ 🙂