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