Saturday, February 14, 2015

Bài 15: ToggleButton



ToggleButton có thể nói là dạng đặc biệt của button,nó có 2 trạng thái cơ bản là checknot check.Khi ở trạng thái check chúng ta click nó sẽ chuyển sang trạng thái not check và ngược lại

Tùy theo phiên bản android mà hình ảnh ToggleButton khác nhau(check và not check).

Ví dụ ngày hôm nay chỉ đơn giản khi ta click ToggleButton sẽ thay đổi hình ảnh trên ImageView thay đổi theo trạng thái ToggleButton thay đổi.

 -activity_main.xml:

    <RelativeLayout 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: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=".MainActivity" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/toggleButton1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:src="@drawable/ic_launcher"
        android:contentDescription="@string/app_name"
        />

    <ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="180dp"
        android:text="ToggleButton" />

</RelativeLayout>

 -MainActivity.java:



package com.example.togglebutton;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ImageView imageView=(ImageView)
                findViewById(R.id.imageView1);
        final ToggleButton toggleButton=(ToggleButton)
                findViewById(R.id.toggleButton1);
        //Xử lí sự kiện khi click ToggleButton
        toggleButton.setOnClickListener(new OnClickListener() {
          
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
            if(toggleButton.isChecked()){
                imageView.setImageDrawable(getResources().getDrawable(R.drawable.check));
            }
            else{
                imageView.setImageDrawable(getResources().getDrawable(R.drawable.not_check));
            }
            }
        });
      
        toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
          
            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), toggleButton.isChecked()?"Check":"Not Check", Toast.LENGTH_SHORT).show();//Thông báo lên toast khi trạng thái của
                                                                                                                      //ToggleButton thay đổi
            }
        });
              
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

-setOnCheckedChangeListener() để nhận sự kiện check thay đổi

-Thay đổi text hiển thị:
     android:textOn text trên ToggleButton khi ở trạng thái check.
     android:textOn text trên ToggleButton khi ở trạng thái notcheck.

        android:textOn="Check"
        android:textOff="Not Check"

Download source code:ToggleButton

Sunday, February 8, 2015

Bài 14:Custom Button

Custom Button

Chào các bạn!Hôm nay tôi sẽ hướng dẫn các bạn cách custom một button.
Tại sao lại phải custom?
Như các bạn đã biết giao diện mặc định của các view nói chung và button nói riêng khá là thô.Việc custom chúng là rất cần thiết để phù hợp với giao app của bạn.

Custom ta có thể thực trực tiếp qua code hoặc thông qua file xml.Trong bài hôm nay tôi sẽ giới thiệu tới các bạn custom button sử dụng file xml bởi nó khá đơn giản và dễ dàng.

Giao diện ví dụ như sau:

Trong ví dụ  này chúng ta sẽ tạo 3 button:
+Button 1 đơn giản chỉ là ta custom lại màu nền và tạo viền cho button
+Button 2 thì sẽ thay đổi màu nền theo trạng thái khác nhau của button
+Button 3 với hình ảnh bên trái và text bên phải.

Nào chúng ta cùng bắt đầu:
-Tạo trong folder /drawable tạo :

-btn1.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <gradient  android:startColor="#ff0800"
                   android:endColor="#ffff00"
                android:angle="270"
                />
    <padding android:left="10dp"
        android:top="10dp"
        android:right="10dp"
        android:bottom="10dp"/>

    <stroke android:color="#000000"
            android:width="2dp"/>              <!-- Màu và độ rộng của viền -->

    <corners android:radius="4dp"/>         <!-- Thiết lập góc cạnh của nút -->

</shape>

 -btn2.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
     <item android:state_pressed="true" >   <!-- Trạng thái khi nút click -->
               <shape>
                  <gradient
                       android:startColor="#ff0000"
                       android:endColor="#ffff00"
                       android:angle="270" />
             
                  <stroke
                       android:width="1dp"
                       android:color="#FFFFFF" />
         
                  <corners
                       android:radius="3dp" />
         
                  <padding
                      android:left="10dp"
                       android:top="10dp"
                       android:right="10dp"
                      android:bottom="10dp" />
             </shape>
     </item>

  <item>            <!-- Trạng thái bình thường khi không click -->
            <shape>
     
                  <solid
                       android:color="#ef4444" />            <!-- Thiết lập màu nền cho nút -->
             
                  <stroke
                       android:width="1dp"
                       android:color="#FFFFFF" />
             
                  <corners
                       android:radius="3dp" />
             
                  <padding
                       android:left="10dp"
                       android:top="10dp"
                       android:right="10dp"
                       android:bottom="10dp" />
              </shape>
 </item>

</selector>

-Để tạo Button 3 trong file activity_main.xml ta thêm thuộc tính android:drawableLeft="@drawable/ic_launcher"

 -activity_main.xml:
 <RelativeLayout 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: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=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="131dp"
        android:background="@drawable/btn1"
        android:text="Button 3" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="36dp"
        android:background="@drawable/btn2"
        android:text="Button 2" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button2"
        android:layout_below="@+id/button2"
        android:layout_marginTop="30dp"
        android:drawableLeft="@drawable/ic_launcher"
        android:text="Button 3" />

</RelativeLayout>



Vậy là xong! Bây giờ bạn thử click vào button 1 và button 2 để xem sự khác nhau.
P/S:Tôi chưa ưng ý với màu này lắm nhưng do thời gian hạn hẹp nên bạn hãy tự lựa chọn phối màu cũng như kích thước sao cho phù hợp.

Download Source Code:custom button

Mọi thắc mắc,góp ý xin vui lòng comment tại fan page:android




Bài 13:EditText và một số vấn đề liên quan

Chào các bạn! Như tối nói ở bài trước,trong bài này tôi sẽ hướng dẫn các bạn cách bạn sự kiện text thay đổi trong EditText và một số vấn đề liên quan.
Nếu bạn chú ý vào khung nhập URL của trình Web,bạn sẽ thấy khi ta đang nhập tứng kí tự nếu phù hợp với lịch sử trình duyệt nó sẽ hiện ra những đia chỉ mà ta từng truy cập đây là một ứng dụng cụ thể của việc bắt sự kiện text thay đổi trong EditText.

Nào bây giờ chúng ta vào bài ngày hôm nay!
Bắt sự kiện trong EditText
Tôi có tạo một ví dụ với giao diện đơn giản như sau:


Tôi giải thích sơ qua:Khi đang trong quá trình nhập dữ liệu nó sẽ tự động tính toán và đưa kết quả mà ta không cần phải nhấn một nút  nào cả.

-Tạo một Project có tên EditText:

-Trong file activity_main.xml ta nhập:
 <RelativeLayout 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"

    tools:context=".MainActivity" >

    <TextView

        android:id="@+id/textView1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignParentLeft="true"

        android:layout_alignParentRight="true"

        android:layout_alignParentTop="true"

        android:textSize="18sp"

        android:textStyle="bold"

        android:textColor="#ffff00"

        android:background="#0000ff"

        android:text="Trình tính tổng 2 số:" />

    <EditText

        android:id="@+id/editText2"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignBottom="@+id/textView3"

        android:layout_alignParentRight="true"

        android:layout_marginLeft="20dp"

        android:layout_toRightOf="@+id/textView2"

        android:ems="10"

        android:hint="Nhập số thứ hai!(6 text)"

        android:inputType="numberDecimal"
     
        android:textSize="16sp"






        android:gravity="center"

        android:maxLength="6" />

    <TextView

        android:id="@+id/textView5"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignBaseline="@+id/textView4"

        android:layout_alignBottom="@+id/textView4"

        android:layout_centerHorizontal="true"

        android:text="0.0"

        android:textAppearance="?android:attr/textAppearanceLarge"

        android:textSize="30sp"

        android:textStyle="bold" />

    <TextView

        android:id="@+id/textView4"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignParentLeft="true"

        android:layout_below="@+id/editText2"

        android:layout_marginTop="34dp"

        android:background="#0000ff"

        android:padding="10dp"

        android:text="Kết Quả:"

        android:textColor="#ff0000"

        android:textSize="17sp"

        android:textStyle="bold" />

    <TextView

        android:id="@+id/textView2"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignParentLeft="true"

        android:layout_below="@+id/textView1"

        android:background="#fff000"

        android:padding="10dp"

        android:text="Số a:"

        android:textColor="#ff0000" />

    <EditText

        android:id="@+id/editText1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignBottom="@+id/textView2"

        android:layout_alignLeft="@+id/editText2"

        android:layout_alignParentRight="true"

        android:ems="10"



        android:gravity="center"       

        android:hint="Nhập số thứ nhât!(4 text)"

        android:inputType="numberDecimal"
       
        android:textSize="16sp"

        android:maxLength="4" >

        <requestFocus />

    </EditText>

    <TextView

        android:id="@+id/textView3"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_below="@+id/textView2"

        android:layout_marginTop="22dp"

        android:layout_toLeftOf="@+id/editText2"

        android:background="#fff000"

        android:padding="10dp"

        android:text="Số b:"

        android:textColor="#ff0000" />

</RelativeLayout>

Ở đây gravity thiết lập vị trí của text nhập vào:trung tâm,bên trái,bên phải...
inputType.:quy định kiểu dữ liệu được nhập vào.Trong trường hợp này là số.


-class MainActivity có nội dung như sau:

package com.example.edittext;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
  
    private EditText a,b;
    private TextView KQ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        KQ=(TextView)
                findViewById(R.id.textView5);
  
        a=(EditText)
                findViewById(R.id.editText1);
      
        b=(EditText)
                findViewById(R.id.editText2);
      
        //Bắt sự kiện thay đổi số b
        a.addTextChangedListener(new TextWatcher() {
                  
                    //Đang thay đổi
                    @Override
                    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                        // TODO Auto-generated method stub
                        if(b.getText().toString().equals("")==false){ //Kiểm tra nếu edittext 2 khống trống thì tính nếu trống thì thôi
                            //nếu ko check sẽ gây lỗi khi edittext 2 trống
                          
                        //ép kiểu về String

                        String text=arg0.toString();
                         double so_a=Double.parseDouble(text);    //java căn bản tôi ko giải thích
                      
                         String text_b=b.getText().toString();   //lấy text trong edittext 2
                      
                         double so_b=Double.parseDouble(text_b);
                      
                         //thực hiện tính và đưa ra kết quả
                      
                         double ketqua=so_a+so_b;
                         KQ.setText(ketqua+"");
                    }
                        else{
                            KQ.setText("0.0");
                        }
                      
                    }
                    //Trước khi thay đổi

                    @Override
                    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                            int arg3) {
                        // TODO Auto-generated method stub
                      
                    }
                    //Sau khi thay đổi
                    @Override
                    public void afterTextChanged(Editable arg0) {
                        // TODO Auto-generated method stub
                      
                    }
                });
              
              
                //Bắt sự kiện thay đổi số b
                b.addTextChangedListener(new TextWatcher() {
                  
                    @Override
                    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                        // TODO Auto-generated method stub
                        if(a.getText().toString().equals("")==false){
                      
                         String text_a=a.getText().toString();
                         double so_a=Double.parseDouble(text_a);
                      
                         String text=arg0.toString();
                         double so_b=Double.parseDouble(text);
                      
                         //thực hiện tính và đưa ra kết quả
                      
                         double ketqua=so_a+so_b;
                         KQ.setText(ketqua+"");
                        }
                        else{
                            KQ.setText("0.0");
                        }
                      
                    }
                  
                    @Override
                    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                            int arg3) {
                        // TODO Auto-generated method stub
                      
                    }
                  
                    @Override
                    public void afterTextChanged(Editable arg0) {
                        // TODO Auto-generated method stub
                      
                    }
                });
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

-cuối cùng là chạy thử xem và kết quả

Chỉ định các hành động của bàn phím 
Trước tiên chúng ta xem một số hình ảnh bàn phím và EditText và xem chúng khác nhau ở đâu:
-EditText thông thường:

-EditText của Web Brower:
-EditText của google search:


Như chúng ta thấy chúng khác nhau ở chỗ phím carriage return.Đối với EditText thông thường đơn giản nó chỉ là phím xuống dòng nhưng ở Web brower google search thì nó lại là 2 action "Đến" và "Tìm Kiếm".
Tại sao lại cần làm vậy? Bởi đơn giản nó tiện cho user hơn.
-Để chỉ định action cho EditText ta sử dụng thuộc tinh android:imeOptions:
<EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:imeOptions="actionSearch"   <!-- Action tìm kiếm -->
        android:ems="10" />
Ngoài actionSearch chúng ta còn rất nhiều action khác như:actionSend,actionGo,actionNext...Mặc định khi có từ 2 EditText trở lên nó sẽ là actionNext,để loại bỏ action mặc định chúng ta có thể sử dụng actionNonr
Phản hồi lại action của sự kiến nút ấn
Nếu bạn chỉ định một action bàn phím cho phương thức đầu vào sử dụng attribute android:imeOptions (chẳng hạn “actionSend”), bạn có thể lắng nghe sự kiện hành động cụ thể sử dụng một TextView.OnEditorActionListener. Interface TextView.OnEditorActionListener cung cấp một hàm hồi quy gọi hàm onEditorAction() cho biết loại hành động nào được triệu gọi với một action ID chẳng hạn IME_ACTION_SEND hoặc IME_ACTION_SEARCH. 
EditText editText = (EditText) findViewById(R.id.search);
editText.setOnEditorActionListener(new OnEditorActionListener() {
 @Override
 public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
 boolean handled = false;
 if (actionId == EditorInfo.IME_ACTION_SEND) {
 // Send the user message
 handled = true;
 }
 return handled;
 }
});

Tôi xin tạm dừng vấn đề về EditText ở đây!
Bài tập dành cho các bạn trong phần này:
-Tạo một app như sau:

+Thiết lập actionSearch cho EditText (1),actionSend cho EditText (2) như tôi đã đánh dấu trên ảnh
+Khi nhấn action của EditText (1) thì thực hiện phép "+", action của EditText (2) thì thực hiện phép "x".Và xuất kêt quả lên TextView.

Download source code:EditText

Mọi thắc mắc,góp ý xin vui lòng comment tại fan page:android

Sunday, July 20, 2014

Bài 12:Sử dụng TextView, EditText và Button trong Android


- TextView, EditText, Button là 3 control cơ bản nhất của Android. Trong các bài tập trước bạn đã được làm quen với 3 control này rồi. Bài tập này Tôi sẽ làm lại mục đích giúp các bạn ôn tập lại đồng thời giúp hiểu thêm được một số thuộc tính mới của nó (trong Android người ta thường gọi một số các control là  Form Widgets).
1) TextView:
- Bạn chỉ muốn hiển thị thông tin mà không cho phép người dùng chỉnh sửa thì nên sử dụng control này.
- TextView tương tự như  JLabel bên Java, và như Label bên C#
- Dưới này Tôi chụp một số thuộc tính của TextView mà chúng ta thường xuyên sử dụng nhất:
10_common_control_0
-Tôi nói sơ qua chút về mấy cái thuộc tính trên:
    +textStyle: thiết lập kiểu của chữ như: normal,bold (Kiểu chữ đậm),italic (Kiểu chữ nghiêng).Ta có thể kết hợp cả 2 kiểu để tạo ra đoạn text có kiểu vừa đậm vừa nghiêng bằng cách sử dụng " | ": bold|italic
    +textSize: thiết lập kich cỡ chữ
    +fontFamily: thiết lập font
- Ta nên thiết lập id cho control để tiện bề xử lý.
- layout_width, layout_height nên thiết lập cho control(bắt buộc)
- Để thay đổi màu nền dùng background, thay đổi màu chữ dùng textColor…
- Để trợ giúp các bạn thay đổi màu nền và màu chữ của các control trong Android (dùng hex color), Tôi đã viết chương trình lấy màu theo mã hex color, các bạn có thể tải về tại : http://www.mediafire.com/?ujj2pyppdwemx69 . Giao diện như sau:
10_common_control_1
Chương trình này bạn có thể chọn button “…” để chọn custom color. Ứng với mỗi bảng màu khác nhau thì sẽ có mã Hex color khác nhau. Bạn copy mã này dán vào Ứng dụng Android của bạn thì sẽ có màu như ý muốn.
Thí dụ, ở màn hình trên Hex là “#3F8020“, bạn copy hex này và dán vào background của TextView (xem hình):
10_common_control_2-Như bên trên Tôi nói là nên đặt tên Id cho control, mục đích để xử lý một số công việc theo yêu cầu. Dựa vào Id ta sẽ lấy được control theo đúng Id này, xem code bên dưới để biết cách lấy control theo Id:
TextView txt1= (TextView) findViewById(R.id.textView1);
- Mọi control đều kế thừa từ View, và hàm findViewById cũng trả về 1 View theo đúng Id truyền vào, đó là lý do ta ép kiểu về cho đúng với TextView (cách làm nhanh: ngay dòng lệnh này nhấn tổ hợp phím Ctrl +1 là nó sẽ tự ép kiểu nhanh cho bạn)
- Để hiển thị thông tin lên control TextView ta dùng lệnh dưới đây:
txt1.setText(“Hello tèo”);
- Đẩy lấy thông tin bên trong control TextView ta dùng lệnh dưới đây:
String msg=txt1.getText().toString();
2) EditText:
- Control này kế thừa từ TextView và cho phép chỉnh sửa dữ liệu (dĩ nhiên bạn có thể cấm chỉnh sửa dữ liệu bằng coding hay trong xml)
- Để sử dụng EditText rất đơn giản, bạn chỉ việc kéo thả control này vào giao diện và tiến hành thiết lập một số thuộc tính:
10_common_control_3-
Như hình bên trên thì bạn chỉ cần kéo loại EditText mà bạn cần (vùng số 1) rồi thả vào giao diện (vùng số 2)
- Bạn xem Tôi chụp một số thuộc tính của EditText trong hình dưới này:
10_common_control_4
-Tương tự như TextView bạn cần thiết lập Id, các layout_width, layout_height
- Thuộc tính hint : để hiển thị thông tin gợi ý trong vùng nhập dữ liệu khi bạn chưa nhập bất kỳ dữ liệu nào vào, chỉ cần có dữ liệu là phần hint sẽ tự động mất đi.
-textSize để thiết lập kích cỡ font chữ cho EditText
- Trong inputType bạn thấy Tôi kết hợp nhiều giá trị lại với nhau bằng cách dùng toán tử “|”, tức là EditText này sẽ có đầy đủ các đặc tính ở bên vế phải mà ta truyền vào, ví dụ:
+textAutoCorrect : Tự động sửa đúng chính tả, giả sử bạn nhập “teh” thì nó sẽ tự động sửa thành “the
+ vân vân… bạn tự tìm hiểu thêm trên mạng
- Ta cũng có thể dùng cửa sổ Properties để thiết lập thuộc tính cho dễ dàng hơn (click chuột vào EditText muốn đổi thuộc tính):
10_common_control_5
-Màn hình trên cho phép ta thay đổi thuộc tính của control một cách dễ dàng.
- Tương tự như TextView, ta cũng phải lấy được control thông qua Id, thao tác với dữ liệu bên trong EditText:
+Lấy control theo Id:
EditText txtbox=(EditText) findViewById(R.id.editText1);
+Thiết lập giá trị cho EditText
txtBox.setText(“nhập bất cứ cái gì vào đây xem sao”)
+Lấy dữ liệu bên trong EditText:
String msg=txtBox.getText().toString()
-Một số thuộc tính cần biết:
+lines: thiết lập số dòng
+maxLeght: thiết lập số kí tự có thể nhập
+gravity:xác định vị trí của text
+ <requestFocus/>: nhận focus khi start activity
Tôi xin tạm dừng vấn đề về EditText tại đây.Trong bài sau tôi sẽ hướng dẫn cách bắt sự kiện EditText rất quan trọng.
3) Button:
- Dùng để thiết lập sự kiện khi người dùng chọn lựa.
- Cũng kế thừa từ TextView
- Có 2 sự kiện mà người sử dụng thường xuyên thao tác:
10_common_control_6
- Bây giờ Tôi sẽ làm một ví dụ về cách sử dụng 3 control này (bạn có thể xem lại bài tập các kiểu lập trình sự kiện trong Android):
- Ví dụ đơn giản là tính cộng trừ nhân chia, giao diện như bên dưới (nhấn nút nào thì thực hiện phép toán cho nút đó):
10_common_control_8
- Bạn xem Layout để dễ thiết kế:
10_common_control_7
- Coding mẫu:
package tranduythanh.com;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
Button btncong,btntru,btnnhan,btnchia;
EditText editsoa,editsob;
TextView txtkq;
OnClickListener myclick=new OnClickListener() {
@Override
public void onClick(View arg0) {
switch(arg0.getId())
{
case R.id.btncong:
String sa=editsoa.getText()+””;
String sb=editsob.getText().toString();
int a=Integer.parseInt(sa);
int b=Integer.parseInt(sb);
txtkq.setText(a+” + “+b +” = “+(a+b));
break;
case R.id.btntru:
break;
case R.id.btnnhan:
break;
case R.id.btnchia:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btncong=(Button) findViewById(R.id.btncong);
btntru=(Button) findViewById(R.id.btntru);
btnnhan=(Button) findViewById(R.id.btnnhan);
btnchia=(Button) findViewById(R.id.btnchia);
editsoa=(EditText) findViewById(R.id.editsoa);
editsob=(EditText) findViewById(R.id.editsob);
txtkq=(TextView) findViewById(R.id.txtketqua);
btncong.setOnClickListener(myclick);
btntru.setOnClickListener(myclick);
btnnhan.setOnClickListener(myclick);
btnchia.setOnClickListener(myclick);
}
}
Bạn hãy trả lời cho Tôi: Hiện giờ đoạn code trên Tôi sử dụng loại Sự Kiện nào?
- Như vậy bạn đã hiểu được cách sử dụng TextView, EditText, Button.
-Bài sau sẽ nói về bắt sự kiện trên EditText:làm thế nào để biết người dùng bắt đầu nhập dữ liệu,đang nhập,và kết thúc,các action khi nhấn enter...
- Bạn phải hiểu thật tốt về 3 Control Tôi vừa nêu ở trên, nó rất là cơ bản và quan trọng, đa phần ứng dụng Android nào cũng sử dụng tối thiểu 3 Control này.
Chúc các bạn thành công.

Bài 11: Hướng dẫn import project vào Eclispe

Tôi xin lỗi hôm trước tôi có đưa cho bạn project mẫu mà không hướng dẫn các bạn import Eclipse.Nên hôm nay tôi xin hướng dẫn các bạn vì tôi biết những người mới học chưa chắc biết được vấn đề này

Bạn mở Eclicpse chọn File-->import:


 +Khi chọn import sẽ xuất hiện cửa sổ import--->Existing Project into Workspace:

+Nhấn next để tiếp tục.Ở mục Select root directory chọn Brower:
 
+Xuất hiện cửa sổ:



+Chọn project cần import.Nhấn ok 2 lần.Vậy là xong!


Chúc bạn thành công!


Mọi thắc mắc,góp y xin vui lòng comment bên dưới hoặc tại fan page:android



Saturday, July 19, 2014

Bài 10:Custom Toast và Aler Dialog trong android



   Chào các bạn! Trong bài trước tôi có giới thiệu cho các bạn 2 cách để thông báo tới người dùng là Toast Notification và Aler Dialog.Nếu bạn thấy giao diện của nó quá "củ chuối" thì trong bài hôm nay tôi sẽ hướng dẫn các bạn "Custom" nó theo ý của mình.

   CUSTOM TOAST NOTIFICATION

Giao diện chính sẽ như sau:
Khi nhấn từng button sẽ hiện ra các Toast khác nhau.
-Tạo một Project mới có tên ToastCustom
-Trong file activity_main:
<RelativeLayout 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: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=".MainActivity" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="49dp"
        android:text="Custom Toast"
        android:textStyle="bold"
        android:textAppearance="?android:attr/textAppearanceLarge" />
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="58dp"
        android:layout_toLeftOf="@+id/textView1"
        android:text="Kiểu 1" />
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/button1"
        android:layout_toRightOf="@+id/textView1"
        android:onClick="custom_2"
        android:text="Kiểu 2" />
</RelativeLayout>


 -Tạo một file có tên custom_toast trong folder layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="50dp"
    android:orientation="vertical"
    android:padding="10dp"
    android:background="#ff0000" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Custom toast với nền màu đỏ"
        android:textColor="#ffffff"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>

-Cuối cùng trong Class MainActivity:
package com.example.toastcustom;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient.CustomViewCallback;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
    Button btn1;                //custom toast 1
  
    Button btn2;                //custom toast 2
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
      
        btn1=(Button)
                findViewById(R.id.button1);            //lấy id từ file xml
      
        btn1.setOnClickListener(new OnClickListener() {            //Bắt sự  kiện nhấn vào nút thứ nhất
          
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
              
                Toast toast=Toast.makeText(MainActivity.this, "Custom Toast kiểu 1", Toast.LENGTH_LONG);
              
                int gravity=Gravity.BOTTOM;        //Hiển thị ở trên màn hìn,ngoài ra còn left,right....
              
                int xOffset=0;                    //Hiển ở vị trí 0 theo chiều ngang màn hình (Chấp nhận giá trị âm)
              
                int yOffset=0;                    //Hiển ở vị trí 0 theo chiều dọc màn hình
              
                toast.setGravity(gravity, xOffset, yOffset);  
              
                toast.show();  //Show Toast notification;
            }
        });
    }
      
        //Bắt sự kiện click ở button 2
        public void custom_2(View v){
            //lấy file xml để custom Toast
            LayoutInflater inflater=(LayoutInflater)
                                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view=inflater.inflate(R.layout.custom_toast, null);
          
            Toast toast=new Toast(MainActivity.this);
          
            toast.setView(view);    //custom Toast
          
            toast.show();
          
        }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}
-Cuối cùng nhấn ctrl+F11 để chạy!
Kết quả:


-Khi ta thay giá trị xOffset thành -100 sẽ có:

Dowload source code:custom toast


  Custom AlerDialog

Giao diện chính rất đơn giản:


Khi nhấn button nó đều cho kết quả giố nhau.Nhưng tôi làm theo 2 cách khác nhau:

-Bạn tạo một Project mới có tên Dialog_Custom

-Trong file activity_main:
<RelativeLayout 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: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=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="71dp"
        android:text="Custom Dialog"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="25dp"
        android:text="Cách 1" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="33dp"
        android:text="Cách 2" />

</RelativeLayout>

 -Tạo một file có tên alert_dialog trong folder layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="5dp" />

    <TextView
        android:id="@+id/text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#FFF"
        android:layout_toRightOf="@+id/image"/>/>

     <Button
        android:id="@+id/dialogButtonOK"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text=" Đóng... "
        android:layout_marginTop="5dp"
        android:layout_marginRight="5dp"
        android:layout_below="@+id/image"
        />

</RelativeLayout>

-Cuối cùng trong Class MainActivity:
package com.example.dialog_custom;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {
    Context context=this;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Cách 1
        Button c1=(Button)
                findViewById(R.id.button1);
        c1.setOnClickListener(new OnClickListener() {
          
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
            showDialog1();  
            }
        });
      
        //Cách 2
                Button c2=(Button)
                        findViewById(R.id.button2);
                c2.setOnClickListener(new OnClickListener() {
                  
                    @Override
                    public void onClick(View arg0) {
                        // TODO Auto-generated method stub
                    showDialog2();  
                    }
                });
    }
  
    public void showDialog1(){
         final AlertDialog dialog=new AlertDialog.Builder(context).create();//Tạo dialog
      
        //lấy file xml từ folder layout
        LayoutInflater inflater=(LayoutInflater)
                                getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view=inflater.inflate(R.layout.alert_dialog, null);
      
        dialog.setView(view);        //set giao diện
      
        TextView text = (TextView) view.findViewById(R.id.text);            //Bạn chú ý view.findViewById()...Xác định nó là của dialog
        text.setText("Xin chào các bạn đến với lập trình Android!");
        ImageView image = (ImageView) view.findViewById(R.id.image);
        image.setImageResource(R.drawable.ic_launcher);

        Button dialogButton = (Button)    view.findViewById(R.id.dialogButtonOK);
        // if button is clicked, close the custom dialog
        dialogButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                dialog.dismiss();   //Ẩn dialog
            }
        });
      
        dialog.show();
    }
  
    public void showDialog2(){
        // custom dialog
        final Dialog dialog = new Dialog(context);
        dialog.setContentView(R.layout.alert_dialog);     //set giao diện cho dialog
        dialog.setTitle("Lập trình Android...");

        // set the custom dialog components - text, image and button
        TextView text = (TextView) dialog.findViewById(R.id.text);            //Bạn chú ý dialog.findViewById()...Xác định nó là của dialog
        text.setText("Xin chào các bạn đến với lập trình Android!");
        ImageView image = (ImageView) dialog.findViewById(R.id.image);
        image.setImageResource(R.drawable.ic_launcher);

        Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
        // if button is clicked, close the custom dialog
        dialogButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                dialog.dismiss();   //Ẩn dialog
            }
        });

        dialog.show();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}
-Cuối cùng nhấn ctrl+F11 để chạy!
Kết quả:

Dowload source code:custom dialog

Mọi thắc mắc,góp y xin vui lòng comment bên dưới hoặc tại fan page:android

.