[ Android ] Sử dụng hộp thoại Alert Dialog trong Android [Android Alert Dialog]

Một số lần trong ứng dụng của bạn, nếu bạn muốn yêu cầu người dùng đưa ra quyết định lựa chọn giữa Yes hoặc No đáp ứng của bất kỳ hành động cụ thể thực hiện bởi người sử dụng, bởi còn lại trong các hoạt động tương tự và không có thay đổi màn hình, bạn có thể sử dụng Alert Dialog.

Để sử dụng Alert Dialog bạn cần khai báo đối tượng AlertDialogBuilder. Cú pháp như sau:

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

Bây giờ bạn phải thiết lập các nút Yes hoặc No bằng cách sử dụng đối tượng của lớp AlertDialogBuilder. Cú pháp như sau:

alertDialogBuilder.setPositiveButton(CharSequence text, DialogInterface.OnClickListener listener) alertDialogBuilder.setNegativeButton(CharSequence text, DialogInterface.OnClickListener listener)

Ngoài ra, bạn có thể sử dụng các chức năng khác được cung cấp bởi các lớp xây dựng để tùy chỉnh các hộp thoại cảnh báo. Dươi đây là những thuộc tính hay sử dụng:

Phương thức - mô tả

1- setIcon(Drawable icon)
Phương thức này để đặt icon cho hộp thoại.

2- setCancelable(boolean cancelable)
Phương thức này thiết lập thuoocjt ính cho hộp thoại có thể hủy bỏ học không

3- setMessage(CharSequence message)
Phương thức này thiết lập thông báo hiển thị trên hộp thoại.

4- setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems, DialogInterface.OnMultiChoiceClickListener listener)
Phương thức này thiết lập danh sách các phần tử để hiển thị trong hộp thoại

5- setOnCancelListener(DialogInterface.OnCancelListener onCancelListener)
Phương thức này thiết lập gọi trở lại nếu cancel

6- setTitle(CharSequence title)
Phương thức này thiết lập tiêu đề của hộp thoại

Cú pháp để tạo ra và hiển thị một hộp thoại
AlertDialog alertDialog = alertDialogBuilder.create(); 
alertDialog.show();

Ví dụ:
Ví dụ sau đây cho thấy việc sử dụng các AlertDialog trong Android. Sử dụng 3 active khác nhau.


1. Tạo Project như hình vẽ:




2. Viết code cho các file
*Code: src/com.example.alertdialog/MainActivity.java

package com.example.alertdialog; 
 import com.example.alertdialog.*; 
 import android.os.Bundle; 
 import android.app.Activity; 
 import android.app.AlertDialog; 
 import android.content.DialogInterface; 
 import android.content.Intent; 
 import android.view.Menu; 
 import android.view.View; 

 public class MainActivity extends Activity 
  @Override 
  protected void onCreate(Bundle savedInstanceState) 
  { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
  } 
public void open(View view)
{  
  AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);    
  alertDialogBuilder.setMessage(R.string.decision); 
  alertDialogBuilder.setPositiveButton(R.string.positive_button, new   DialogInterface.OnClickListener() 
  @Override 
 public void onClick(DialogInterface arg0, int arg1) 
 { 
    Intent positveActivity = new Intent(getApplicationContext(),com.example.alertdialog.PositiveActivity.class);
 startActivity(positveActivity); 
 } 
 }); 
 alertDialogBuilder.setNegativeButton(R.string.negative_button, new DialogInterface.OnClickListener() 
 @Override 
 public void onClick(DialogInterface dialog, int which) 
  Intent negativeActivity = new Intent(getApplicationContext(),com.example.alertdialog.NegativeActivity.class);
 startActivity(negativeActivity); } }); AlertDialog alertDialog = alertDialogBuilder.create(); 
 alertDialog.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; 
 } 
}
*Code: src/com.example.alertdialog/PositiveActivity.java

package com.example.alertdialog; 
 import android.os.Bundle; 
 import android.app.Activity; 
 import android.view.Menu; 
 public class PositiveActivity extends Activity 
 @Override 
protected void onCreate(Bundle savedInstanceState) 
 super.onCreate(savedInstanceState); 
 setContentView(R.layout.activity_positive); 
 } 
 @Override 
 public boolean onCreateOptionsMenu(Menu menu) 
{
 // Inflate the menu; this adds items to the action bar if it is present. //getMenuInflater().inflate(R.menu.positive, menu); 
 getMenuInflater().inflate(R.menu.main, menu); 
 return true; 
 } 
 }

*Code: src/com.example.alertdialog/NegativeActivity.java

package com.example.alertdialog;
 import android.os.Bundle;
 import android.app.Activity;
 import android.view.Menu;
 public class NegativeActivity extends Activity
 { 
 @Override 
protected void onCreate(Bundle savedInstanceState) 
 super.onCreate(savedInstanceState); 
 setContentView(R.layout.activity_negative); 
 } 
 @Override 
 public boolean onCreateOptionsMenu(Menu menu) 
// Inflate the menu; this adds items to the action bar if it is present.
 //getMenuInflater().inflate(R.menu.negative, menu);
 getMenuInflater().inflate(R.menu.main, menu); 
 return true; 
 } 
 }

*Code: res/layout/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="170dp"
     android:onClick="open"
     android:text="@string/hello_world" />

</RelativeLayout>


*Code: res/layout/activity_negative.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=".NegativeActivity" >

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:layout_alignParentTop="true"
      android:layout_marginLeft="14dp"
      android:layout_marginTop="17dp"
      android:text="@string/negative"
      android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

*Code: res/layout/activity_positive.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=".PositiveActivity" >

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:layout_alignParentTop="true"
      android:layout_marginLeft="14dp"
      android:layout_marginTop="20dp"
      android:text="@string/positive"
      android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

*Code: Strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

   <string name="app_name">AlertDialog</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello world!</string>
   <string name="title_activity_positive">PositiveActivity</string>
   <string name="title_activity_negative">NegativeActivity</string>
   <string name="positive">Positive Activity</string>
   <string name="negative">Negative Activity</string>
   <string name="decision">Are you sure, you wanted to make this decision</string>
   <string name="positive_button">+ive</string>
   <string name="negative_button">-ive</string>

</resources>

*Code: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.alertdialog"
   android:versionCode="1"
   android:versionName="1.0" >

   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="17" />

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      <activity
         android:name="com.example.alertdialog.MainActivity"
         android:label="@string/app_name" >
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
      <activity
         android:name="com.example.alertdialog.PositiveActivity"
         android:label="@string/title_activity_positive" >
      </activity>
      <activity
         android:name="com.example.alertdialog.NegativeActivity"
         android:label="@string/title_activity_negative" >
      </activity>
</application>

</manifest>

Kết quả:






*******

Một số tài liệu và khoá học bổ ích dành cho bạn: 

# Giáo trình: Lập Trình Android [Click để xem]

# Khoá học online:  Lập trình Android toàn tập [Click để xem]


Tham khảo tutorialspoint.com

[ Java ] Sử dụng Interface trong Java

Ví dụ sử dụng Interface trong lập trình Java: 
  - Xây dựng interface Tinh1, Tinh2 như sau:
    interface Tinh1 {
        void Nhap();
        long GiaiThua(int n);
    }
   // interface Tinh2 kế thừa Tính1
   interface Tinh2 extends Tinh1 {
     float S1(int n);
     float S2(int n);
     float S3(int n, float x);
   }
  - Xây dựng class TinhTong implements Tinh2, trong đó:
    S1 = 1!+2!+3!+...+n!
    S2 = 2!+4!+6!+...+(2n)!
    S3 = x^1 / 1 + x^2 / 2 + x^3 / 3 +...+ x^n / n
   (1 < x < 5; 1 < n < 100, nhập vào từ bàn phím)
   
  
[Code Java]
/* Sử dụng interface */
package interface_vd1;
import java.util.Scanner;

/************interface Tinh1****************/

interface Tinh1 {
  void Nhap();
  long GiaiThua(int n);
}

/***********interface Tinh2****************/

interface Tinh2 extends Tinh1 {
  float S1(int n);
  float S2(int n);
  float S3(int n, float x);
}

/************class TinhTong*****************/

class TinhTong implements Tinh2 {
  private int n;
  private float x;
// Set x (thiet lap x)
public void Set_x(float x) {
  this.x = x;
 }

// get x (lay gia tri x)
public float Get_x() {
  return x;
}

// Set n (thiet lap n)
public void Set_n(int n) {
 this.n = n;
}

// get n (lay gia tri n)
public int Get_n() {
  return n;
}
// Nhap
public void Nhap() {
  Scanner in = new Scanner(System.in);
  // nhap n
  int t = 0;
  System.out.print("\n - Nhap n: ");
 try {
   do {
      System.out.print("\n n = ");
      t = in.nextInt();
      if (t < 1 || t > 100) {
         System.out.print("\n Nhap lai n!");
      }
    } while (t < 1 || t > 100);
   } catch (Exception ex) {
     System.out.print("\n *** Da co loi " + ex.toString() + " khi nhap n!");
  }
  Set_n(t);
 // nhap x
 float m = 0;
 System.out.print("\n - Nhap x: ");
 try {
   do {
       System.out.print("\n x = ");
       m = in.nextFloat();
       if (m < 1 || m > 5) {
          System.out.print("\n Nhap lai x!");
       }
    } while (m < 1 || m > 5);
   } catch (Exception ex) {
   System.out.print("\n *** Da co loi " + ex.toString() + " khi nhap x!");
  }
  Set_x(m);
}

// GiaiThua
public long GiaiThua(int n) {
   long gt = 1;
   n = Get_n();
   for (int i = 1; i <= n; i++) {
      gt += i;
   }
  return gt;
}

// S1
public float S1(int n) {
 float s1 = 0;
 n = Get_n();
 for (int i = 1; i <= n; i++) {
    s1 += GiaiThua(i);
  }
  return s1;
}

// S2
public float S2(int n) {
  float s2 = 0;
  n = Get_n();
  for (int i = 2; i <= (2 * n); i = i + 2) {
   s2 += GiaiThua(i);
  }
  return s2;
}

// S3
public float S3(int n, float x) {
 float s3 = 0, tu = 1;
 n = Get_n();
 x = Get_x();
 for (int i = 1; i <= n; i++) {
   tu *= x;
   s3 += tu / i;
  }
  return s3;
}

// In ket qua
void InKQ() {
    System.out.print("\n * KET QUA: ");
    System.out.print("\n + S1= " + S1(n));
    System.out.print("\n + S2= " + S2(n));
    System.out.print("\n + S3= " + S3(n, x));
 }
}

/************class main*************************/
public class Interface_vd1 {
public static void main(String[] args) {
  TinhTong t = new TinhTong();
  t.Nhap();
  t.InKQ();
 }
}

[Download Project Tại đây]

Một số tài liệu và khoá học bổ ích dành cho bạn: 

# Tài liệu: Lập trình hướng đối tượng JAVA core dành cho người mới bắt đầu học lập trình [Click để xem]

# Khoá học online: Lập trình Java trong 4 tuần [Click để xem]

[ XML ] Cú pháp căn bản trong XML [ XML syntax rules ]

Nói chung các quy tắc của XML rất đơn giản hợp lý, dễ học và dễ sử dụng.


1. Tất cả các yếu tố của XML phải có thẻ đóng (closing tag).
- Các yếu tố trong HTML không cần phải có thẻ đóng.
  <p>This is a paragraph
  <p>This is another paragraph

- Trong XML, việc bỏ qua thẻ đóng là không hợp lệ. Tất cả các yếu tố phải có thẻ đóng. Do dó với ví dụ trên trong XML sẽ là:
  <p>This is a paragraph</p>
  <p>This is another paragraph</p>

* Lưu ý: Những phần khai báo ở đầu tài liệu XML không có thẻ đóng. Đó không phải là lỗi. Khai báo đó không phải là một phần trong chính tài liệu XML đó, và nó không có thẻ đóng.

2. Yếu tố chính xác các thẻ của XML.
- Các thẻ trong XML yêu cầu một sự chính xác. Ví dụ thẻ <Letter> sẽ khác với thẻ <letter>.

- Thẻ đóng và thẻ mở phải được viết cùng một trường hợp.
   <message>This is incorrect</message>
   <message>This is correct</message>

* Lưu ý: thẻ mở và thẻ đóng cũng thường được gọi là thẻ bắt đầu và thẻ kết thúc. Bạn có thể sử dụng nó theo ý thích của bạn, nhưng nó phải chính xác.

3. Các yếu tố trong XML phải được lồng nhau đúng cách

- Trong HTML các bạn có thể thấy các yếu tố không đúng cách viết lông nhau
   <b><i>This text is bold and italic</b></i>
- Trong XML tất cả các yếu tố phải được lồng nhau đúng quy định:
  <b><i>This text is bold and italic</i></b>

Trong ví dụ trên, lồng nhau đúng cách ở đây được hiểu là kể tử khi phần tag <i> được mở trong tag <b>. Thì nó phải được đóng bên trong tag <b>.

4. Tài liệu XML phải có một phần tử gốc

Tài liệu XML phải có một yếu tố chứa tất cả các yếu tố khác. Yếu ôố này được gọi là phần tử gốc.
 <root>
  <child>
     <subchild>.....</subchild>
  </child>
 </root>

5. Các giá trị thuộc tính trong XML phải trích dẫn

- Các yếu tố trong XML có thể có các thuộc tính trong cặp tên/giá trị giống như trong HTML.

- Trong XML các giá trị thuộc tính luôn luôn phải được trích dẫn(quoted).

- Chúng ta hãy xem 2 ví dụ dưới đây về cách sử dụng thuộc tính trong XML, ví dụ 1 là sai, ví dụ 2 là đúng.

Ví dụ 1: sai.
<note date=12/11/2007>
  <to>Love</to>
  <from>Jani</from>
</note>

Ví dụ 2: sử dụng đúng
<note date="12/11/2007">
  <to>Tove</to>
  <from>Jani</from>
</note>

Lỗi trong ví dụ 1 là thuộc tính ngày trong phần tử node không trích dẫn.

6. Tham chiếu thực thể (Entity Reference).

- Một số ký tự có ý nghĩa đặc biệt trong XML.

- Nếu như bạn đặt ký tự “<” bên trong một phần tử của XML nó sẽ tạo ra một lỗi bởi vì phân tích các giải thích đó là khởi đầu của một phần tử mới.

- Điều này sẽ tạo ra một lỗi XML:
<message>if salary < 1000 then</message>
Vậy làm sao để sử dụng ký tự “<” trong một phần tử của XML. Câu trả lời là thay thế ký tự “<” bằng một tham chiếu thực thể &lt;
<message>if salary &lt; 1000 then</message>

- Chúng ta có 5 tham chiếu thực thể được định nghĩa trước trong XML:



* Lưu ý: Chỉ có ký tự “<” và “&” là không hợp lệ nghiêm ngặt trong XML. Các ký tự “>” là hợp pháp, nhưng sử dụng tham chiếu thực thể &gt; để thay thế cho nó sẽ tạo một thói quen tốt.

7. Chú thích trong XML (Comments in XML)

Cú pháp các chú thích trong XML là tương tự HTML.

<!– This is a comment –>

8. Khoảng trắng (white-space) được giữ lại trong XML

HTML cắt bỏ nhiều ký tự trắng trắng thành một ký tự trắng đơn.



- Với XML, ký các ký tự trắng trong tài liệu không được cắt bỏ.

9. XML lưu trữ một dòng mới như LF(Line Feed)

Trong các ứng dụng của Windows, một dòng mới là một lưu trữ bình thường như một cặp ký tự: carriage return (CR) và chuyển dòng(LF – Line Feed). Trong các ứng dụng của Unix, một dòng mới là bình thường được lưu trữ như một ký tự LF. XML lưu trữ một dòng mới như LF.

Tham khảo thanhcuong

[ Java ] Code Java tải website về máy tính [ Download URL ]

Chương trình Java download URL:
- Nhập địa chỉ URL cần download
- Kết quả download được lưu tại output.htm, trong thư mục chứa Project

* Để download từ địa chỉ URL cần sử dụng 2 thư viện:
    + java.net.URL
    + java.net.URLConnection

[Code Java]

/******************************************************************************
 http://lap-trinh-may-tinh.blogspot.com/
******************************************************************************/

package download_java;
import java.util.Scanner;

public class  Download_java
{
  public static void main(String[] args) throws Exception
  {
    // Nhập địa chỉ URL cần download
      Scanner in=new Scanner(System.in);
    System.out.print("\n Nhập URL: ");
    String str_url=in.nextLine();
    // Địa chỉ URL cần download
    java.net.URL url = new java.net.URL(str_url);
    java.net.URLConnection con = url.openConnection();

    java.io.InputStream is=con.getInputStream();

    // Kết quả được lưu trên output.htm trong thư mục chứa Project
    String output_file="output.htm";
    java.io.FileOutputStream os=new java.io.FileOutputStream(output_file);

    int BUF_SIZE=1024; // KB
    byte[] buffer = new byte[BUF_SIZE];
   
    while (true)
    {
      int n = is.read(buffer);  // đọc data URL
      if (n>0) os.write(buffer,0,n);     // ghi vào file
      if (n<0) break;    // kế thúc đọc
    }
  }
}

[Download Project tại đây]

Một số tài liệu và khoá học bổ ích dành cho bạn: 

# Tài liệu: Lập trình hướng đối tượng JAVA core dành cho người mới bắt đầu học lập trình [Click để xem]

# Khoá học online: Lập trình Java trong 4 tuần [Click để xem]

[Thuật toán Tìm kiếm tuần tự] Ví dụ sử dụng thuật toán tìm kiếm tuần tự [C\C++]

Thuật toán tìm kiếm tuần tự 

Ví dụ sử dụng thuật toán tìm kiếm tuần tự: Viết các hàm thực hiện
 1. Nhập dãy số nguyên có n số (1<n<100).
 2. In dãy vừa nhập
 3. Tìm giá trị x trong dãy số (x nhập từ bàn phím)
 4. Đếm số lần xuất hiện của y (y nhập từ bàn phím)
 5. Tính giá trị phần trăm các số >=5.
 6. In ra vị trí xuất hiện các số nguyên tố có trong dãy.


[Code Turbo C++]

/*

http://lap-trinh-may-tinh.blogspot.com/

*/
#include<iostream.h>
#include<conio.h>
#include<stdio.h>

// khai bao
int a[100],n;

// Nhap mang
void Nhap(){
  cout<<"\n + NHAP MANG : ";
  cout<<"\n - Nhap so phan tu: ";
  do{
       cout<<"\n n= "; cin>>n;
       if(n<1||n>100)
             cout<<"\n Nhap lai n!";
  } while (n<1||n>100);

  // Nhap mang
  cout<<"\n - Nhap mang : ";
  for (int i=0;i<n;i++)
   {
       cout<<"\n a["<<i<<"]= ";
       cin>>a[i];
    }
   }

// In day
void InDay(int a[],int n){
  cout<<"\n + IN DAY \n";
  for(int i=0;i<n;i++)
      cout<<a[i]<<"; ";
 }

// Tim x trong day
void Tim_x(int x, int a[], int n){
   cout<<"\n + TIM KIEM "<< x <<" TRONG DAY:";
   int t=0;
   for(int i=0;i<n;i++)
     if(x==a[i])
        t=1;
   if(t==1)
      cout<<"\n Tim thay "<<x<<" trong day ";
   else
      cout<<"\n Khong tim thay "<<x<<" trong day ";
}

// Dem so lan xuat hien cua y trong day
int Dem_y(int y, int a[], int n){
    int dem=0;
   for(int i=0;i<n;i++)
      if(y==a[i]) dem++;
  return dem;
}

// Tinh ty le % cac so lon hon 5
void PhanTram(int a[],int n){
   float pt;
   int count=0;
   for(int i=0;i<n;i++)
     if(a[i]>=5) count++;
        pt=((float)count/n)*100;
        cout<<"\n + TY LE % CAC SO >= 5 :"<<pt<<"%";
 }

// Dem so lan xuat hien cua so nguyen to trong day
void DemSNT(int a[],int n){
   cout<<"\n + IN RA VI TRI SO NGUYEN TO: ";
   for(int i=0;i<n;i++)
   {
      int test=0;
      for(int t=2;t<a[i];t++)
          if(a[i]%t==0) test=1;
      if (test==0) cout<<i<<" ; ";
    }

}

//////////////////////
void main(){
// Nhap day
  Nhap();
// In day
 InDay(a,n);

// tim x
 int x;
 cout<<"\n Nhap gia tri can tim x= ";
 cin>>x;
 Tim_x(x,a,n);
// Dem y trong day
 int y;
 cout<<"\n Nhap gia tri can dem y= ";
 cin>>y;
 cout<<"\n + SO LAN XUAT HIEN SO "<<y<<" LA: "<<Dem_y(y,a,n);
 // Tinh ty le phan tram cac so >=5
 PhanTram(a,n);

 // Dem so nguyen to trong day
 DemSNT(a,n);

 getch();
}

[C#] Ý nghĩa của ký tự @ trong C#

Ký tự @ có một số ý nghĩa đặc biệt trong một chương trình được viết bằng C#. 

Có hai ý nghĩa cơ bản:

1. Cho phép sử dụng các từ khóa (keyword) trong C# như là tên biến hoặc kiểu dữ liệu
       
      Khi viết một ứng dụng bằng C#, không phải lúc nào chúng ta cũng tự tạo ra một thành phần nào đó để sử dụng mà chúng ta có thể sử dụng các thư viện, lớp có sẵn. Tuy nhiên, các thành phần này có thể đã được viết bằng một ngôn ngữ lập trình khác (như VB, C++…) dẫn đến việt một số tên kiểu dữ liệu trong thành phần đó trùng với từ khóa của C#. Khi đó, chúng ta phải sử dụng ký tự @ để đặt phía trước tên kiểu dữ liệu đó. Ví dụ như chúng ta đang viết một chương trình C# có sử dụng một lớp chứa trong thư viện được viết bằng ngôn ngữ khác, và lớp này có tên là “public”. 
 
      Vậy làm thế nào để sử dụng khai báo được một đối tượng của lớp đó. Cú pháp cần sử dụng của chúng ta sẽ là: 
    @public P = new @public(); 

2. Đặt tên cho biến bằng cách đặt ký hiệu @ phía trước tên biến đó. 

Ví dụ: 
 
       int @new = 10; // @new là một biến kiểu số nguyên

Cho phép một chuỗi thô không có xử lý cho các ký tự phía sau dấu \ bên trong
Giả sử như bạn muốn lưu chuỗi đường dẫn đến thư mục New trong ổ đĩa F thì chuỗi chúng ta cần phải được gán cho biến kiểu string như sau:
       
      String path = “F:\\New”;
Bởi vì các ký tự \ trong một chuỗi có chức năng đặc biệt khi có ký tự đi kèm phía sau nó (ví dụ \n, \t, \r), cho nên chúng ta phải sử dụng hai dấu \\ trong đường dẫn này nhằm báo cho trình biên dịch biết là chúng ta thực sự muốn có ký tự \ trong chuỗi.
Nếu như sử dụng ký tự @, chúng ta không cần phải sử dụng hai ký tự \\ bởi vì trình biên dịch sẽ biết rằng chuỗi này không cần phải xử lý với các ký tự đặc biệt bên trong
string path = @”F:\New”;

Tham khảo chienuit

[Đồ họa máy tính] Code: Vẽ ÔTÔ sử dụng thuật toán Bresenham và Midpoint [C\C++]

Ví dụ: Sử dụng thuật toán Bresenham và Midpoint vẽ các đường tròn và đoạn thẳng


Viết chương trình C\C++ vẽ hình OTO:

[Đồ họa máy tính] Code: Vẽ ÔTÔ sử dụng thuật toán Bresenham và Midpoint [C\C++]
[Đồ họa máy tính] Code: Vẽ ÔTÔ sử dụng thuật toán Bresenham và Midpoint [C\C++]


[Code Turbo C++]

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<graphics.h>
#include<math.h>

/***** VE DUONG THANG ****/

// Ve duong doc (// 0y)

void Line_OY(int y1, int y2, int x,int c){
  for(int y=y1;y<=y2;y++)
   putpixel(x,y,c);
 }

// Ve duong ngang (// 0x)
void Line_OX(int x1, int x2, int y,int c){
for(int x=x1;x<=x2;x++)
   putpixel(x,y,c);
}

// Bresenham_Line
void Bre_Line(int x1, int y1, int x2, int y2, int c)
{
   int x, y, dx, dy,p,const1,const2;
   y = y1;
  dx = x2 - x1;
  dy = y1 - y2;
  p = 2*dy - dx;
  const1 = 2*dy;
  const2 = 2*(dy-dx);
  for (x=x1; x<=x2; x++) {
   putpixel(x, y, c);
   if (p<0)
     p += const1; // p=p + 2dy
   else {
     p +=const2; //p=p+2dy-2dx
     y--;
  }
 }
}

// ve duong than voi Midpoint
void Mid_line(int x1, int y1, int x2, int y2, int c)
{
  int x, y, dx, dy,d;
  y = y1;
  dx = x2 - x1;
  dy = y2 - y1;
  d= dy - dx/2;
  for (x=x1; x<=x2; x++)
  {
    putpixel(x, y, c);
    if (d <= 0)
      d = d + dy;
    else
   {
      y ++;
      d = d + dy - dx;
   }
 }
}

/***** VE DUONG TRON ****/

// ham pc
void pc(int xc,int yc, int x, int y, int c){
 putpixel(xc + x, yc + y, c);
 putpixel(xc - x, yc - y, c);
 putpixel(xc -y, yc +x, c);
 putpixel(xc +y, yc -x, c);
}

// Ve duong tron voi Bresenham
void Bresenham_Circle(int xc, int yc, int r, int c)
{
  int x, y, p;
  x = 0;
  y = r;
  p = 3 - 2 * r;
  pc(xc,yc, r,0,c); //ve 4 diem dac biet
  while (x < y){
   if (p < 0)
     p += 4 * x + 6;
   else{
     p += 4 * (x-y) + 10;
     y--;
   }
   x++;
   pc(xc,yc, x,y,c);
   pc(xc,yc, y,x,c);
 }
 pc(xc,yc, y,y,c); // ve 4 diem phan giac x=y
}

// Ve duong tron voi MidPoint
void Mid_circle(int xc, int yc, int r, int c)
{
  int x, y, d;
  x = 0;
  y = r;
  d = 1- r;
  pc(xc,yc, r,0,c); //ve 4 diem dac biet
  while (x <= y)
  {
    pc(xc,yc, x,y,c);
    pc(xc,yc, y,x,c);
    if (d< 0)
       d +=2 * x + 3;
    else
   {
      d += 2 * (x-y) + 5;
      y--;
   }
   x++;
 }
 pc(xc,yc, y,y,c); // ve 4 diem phan giac x=y
}

/*****************************/
// ham main

void main(){
clrscr();
int driver=DETECT, mode;
initgraph(&driver,&mode,"C:\\TC\\BGI"); // Ban co the thay doi Path tuy vao may cua ban

// AB
Line_OX(10,90,40,4);

// FE
Line_OX(30,70,20,4);

// DC
Line_OX(80,90,30,4);

// AG
Line_OY(30,40,10,4);

// BC
Line_OY(30,40,90,4);

// O1
Bresenham_Circle(30,40, 10,5);

//O2
Mid_circle(60, 40,10, 5);

// Kinh sau (GF)
Bre_Line(10,30,30,20,4) ;

// Kinh truoc (DE)
Mid_line(70,20, 80, 30,4) ;

getch();
}

/***************/
KẾT QUẢ:


[Java] Xử lý mảng 2 chiều trên Java [Kế thừa trong Java]

Bài tâp: Xây dựng class theo mô hình




[Code Java]

// Class Matran.java
package xuly_matran;
import java.util.Scanner;
public class Matran {
    int [][] a=new int[7][7];
    int n;
 
    // nhap ma tran
    void NhapMT(){
        Scanner t=new Scanner(System.in);
        // nhap kich thuc mang
        System.out.print("\n + Nhap kich thuoc ma tran: \n");
        do{
            System.out.print("\n n= ");
            n=t.nextInt();
            if((n<2||n>7))
                System.out.print("\n Nhap lai n! ");
        }while(n<2||n>7);
        System.out.print("\n + Nhap ma tran: \n");
        for (int i=0;i<n;i++)
            for (int j=0;j<n;j++)
            {
                System.out.print("\n a["+i+"]["+j+"]= ");
                a[i][j]=t.nextInt();
            }
    }
    // In ma tran
    void InMT(){
        System.out.print("\n + In ma tran \n");
        for (int i=0;i<n;i++){
            for (int j=0;j<n;j++)
                System.out.print(a[i][j]+"\t");              
            System.out.print("\n");              
            }
    }
}

// Class SapXep.java
/*
 * Sắp xếp từng dòng của ma trận tăng dân (bubble sort)
 * Sắp xếp từng cột của ma trận giản dần (Insert sort)
 */
package xuly_matran;

public class SapXep extends Matran {
    public SapXep(){
        System.out.print("\n * SAP XEP MA TRAN \n ");
    }
    // sap xep dong tang dan
    void Bubble_sort(){
        System.out.print("\n + In ma tran da sap xep dong tang dan \n");
        for(int i=0;i<n;i++)
            for(int j=0;j<n;j++)
                for(int k=n-1;k>j;k--)
                    if(a[i][k]<a[i][k-1])
                    {
                        int temp=a[i][k];
                        a[i][k]=a[i][k-1];
                        a[i][k-1]=temp;
                     
                    }
        super.InMT();
    }
    // sap xep cot giam gan
    void Insert_sort(){
       System.out.print("\n + In ma tran da sap xep cot giam dan \n");
     
       for(int j=0;j<n;j++)
       {
           for(int i=1;i<n;i++)        
           {
           int pos=i-1;
           int t=a[i][j];
           while(pos>=0&&a[pos][j]<t)
           {
               a[pos+1][j]=a[pos][j];
               pos--;
           }
           a[pos+1][j]=t;
           }
       }
       super.InMT();
    }
 
}

// Class Tim_Dem.java
/*
 * Tìm vị trí xuất hiện các số chẵn trong ma trận
 * Đếm số nguyên tố có trong ma trận
 */
package xuly_matran;

public class Tim_Dem extends Matran {
    public Tim_Dem(){
        System.out.print("\n * TIM SO CHAN - DEM SO NGUYEN TO \n");
    }
    // In vi tri so chan trong ma tran
    void InViTRiSoChan(){
        System.out.print("\n + In vi tri so chan trong ma tran:\n");
        for(int i=0;i<n;i++)
            for(int j=0;j<n;j++)
                if(a[i][j]%2==0) System.out.print("["+i+"]["+j+"]; ");
    }
    // ham kiem tra so nguyen to
    boolean TestNT(int a){
        for(int i=2;i<a;i++)
            if(a%i==0)
                return false;
        return true;
    }
    // Dem so nguyen to trong ma tran
    void DemSoNT(){      
        int dem=0;
        for(int i=0;i<n;i++)
            for(int j=0;j<n;j++)
                if(TestNT(a[i][j])) dem++;
        System.out.print("\n + So nguyen to co trong ma tran la: "+dem);
    }
}

// Class Tach.java
/*
 * Tách đường chéo chính thành ma trận
 */
package xuly_matran;

public class Tach_DCheo extends Matran{
    int[] m=new int [7];
    public Tach_DCheo(){
        System.out.print("\n * TACH DUONG CHEO CHINH THANH MA TRAN");
    }
    // Tach duong cheo
    void Tach(){
        for(int i=0;i<n;i++)
            m[i]=a[i][i];      
        System.out.print("\n + Mang  vua tach: \n");
        for(int i=0;i<n;i++)
            System.out.print(m[i]+"; ");
    }
    // sap xep tang dan
    void SapXep()
    {
        for(int i=0;i<n;i++)
            for(int j=i+1;j<n;j++)
                if(m[i]>m[j])
                {
                    int t=m[i]; m[i]=m[j]; m[j]=t;
                }
        System.out.print("\n + Sap xep mang \n");
        for(int i=0;i<n;i++)
            System.out.print(m[i]+"; ");
    }
 
}

// Class XuLy_Matran.java (class main)

/*
http://lap-trinh-may-tinh.blogspot.com/
*/
package xuly_matran;

public class Xuly_matran {

    public static void main(String[] args) {
        Matran t=new Matran();
        t.NhapMT();
        t.InMT();
     
        // Sap xep
        SapXep t1=new SapXep();
        t1.NhapMT();
        t1.Bubble_sort();
        t1.Insert_sort();
     
        // Tìm - đếm
        Tim_Dem t2=new Tim_Dem();
        t2.NhapMT();
        t2.InViTRiSoChan();
        t2.DemSoNT();
     
        // Tách đường chéo chính
        Tach_DCheo t3=new Tach_DCheo();
        t3.NhapMT();
        t3.Tach();
        t3.SapXep();
    }
}

Một số tài liệu và khoá học bổ ích dành cho bạn: 

# Tài liệu: Lập trình hướng đối tượng JAVA core dành cho người mới bắt đầu học lập trình [Click để xem]

# Khoá học online: Lập trình Java trong 4 tuần [Click để xem]


Đoc thêm các bài khác

Bài 1: Chương trình JAVA đầu tiên
Bài 2: Các kiểu dữ liệu và toán tử trong
Bài 3: Các cấu trúc điều khiển trong Java
Bài 4 : Mảng và chuỗi trong Java
Bài 5: Lớp (class) và đối tượng (object) trong Java
Bài 6:Thừa kế (Inheritance) và đa hình (Polymorphism)
Ví dụ lập trình giao diện đồ họa với Java (GUI)
Ví dụ lập trình kết nối dữ liệu với Java (JDBC)
Ví dụ về lập trình Android 

[ C\C++ ] Bài toán người đưa thư sử dụng giải thuật Heuristic [ Giải thuật - Trí tuệ nhân tạo ]

1. Phát biểu bài toán:

Bài toán: Để tiết kiệm thời gian đi đưa thư trong một địa phương. Người đưa thư phải đi qua tất cả các điểm cần phát thư rồi trở về vị trí ban đầu với đường đi ngắn nhất.

Bài toán có thể phát biểu lại như sau: Giả sử có một đồ thị có trọng số dương, tìm đường đi ngắn nhất qua tất cả các đỉnh của đồ thị rồi trở về đỉnh ban đầu.

2. Hạn chế khi sử dụng thuật toán tối ưu:

Đồ thị có n đỉnh, khi đó thuật toán tối ưu cho bài toán này sẽ là thuật toán tìm đường đi ngắn nhất cho chu trình Haminton. Do đó thuật toán tối ưu sẽ có độ phức tạp là O(n!).

ĐI TÌM một thuật giải Heuristic cho bài toán này.

3. Sử dụng thuật toán Heuristic cho bài toán người đưa thư:

- Theo kinh nghiệm của con người trong thực tế thì khi ta đi trên những đoạn đường ngắn nhất thì cuối cùng ta sẽ có một hành trình ngắn nhất à sử dụng nguyên lý tham lam.

- Thuật giải bài toán sử dụng nguyên lý tham lam:


- Ví dụ về thuật giải trên:

Với một đồ thị trọng số dương như hình bên. Nếu ta xuất phát từ đỉnh sổ 1, thì đỉnh tiếp theo phải đến là 2 (vì cạnh 1-2 có trọng số nhỏ nhất so với các đỉnh chưa đến của 1), như vậy tiếp theo ta sẽ đến các đỉnh theo thứ tự là 5, 3, 4, và trở về 1.

Như vậy đường đi ngắn nhất theo giải thuật trình bày trên tìm được là: 1 + 3 + 2 + 1+ 7 = 14

4. Cài đặt thuật toán.
(ma trận trọng số, kích thước 5x5)

- Ta có dạng ma trận hóa của đồ thị trong ví dụ ở mục 3, như hình bên:

- Chương trình được viết trên môi trường Turbo C++ 3.0.

- Input: một ma trận vuông bằng file “graph.txt “ có dạng như hình bên (tài về tại đây), hay nhập ma trận bằng tay.

- Output: đường đi theo thuật giải Heuristic, và chi phí của đường đi đó.

- Tổ chức dữ liệu chương trình: (hình dưới)

Trong đó:
  + n: là biến cho biết số đỉnh của đồ thị.

  + G: dùng để trỏ tới các giá trị của ma trận.

  + v[Gr.n + 1]: dùng để lưu trữ đường đi theo thuật giải Heuristic.

  + Gr.G[ i][j ]: đồ thị dưới dạng ma trận.

  + x: là đỉnh đầu tiên xuất phát.

  + initGraph(Graph &Gr): Hàm dùng để khởi tạo một đồ thị mới từ cấu trúc đã tổ chức.

  + ReadGraph(Graph &Gr): dùng để đọc đồ thị từ file .txt

  + inputHandle( Graph &Gr): dùng để nhập đồ thị bằng tay.

  + outputGraph(Graph Gr): dùng để xuất đồ thị đã được nhập ra màn hình.

  + testGraph(int a, int* v, Graph Gr): Kiểm tra điểm đang duyệt có trùng với điểm đã duyệt trên ma trận không. Được gọi trong hàm topNear(…).


  + topNear(int a, Graph Gr, int* v) : Hàm tìm đỉnh kế tiếp theo thuật giải Heuristic. Được gọi lại trong hàm FindWay(…) .


+ FindWay(int x, Graph Gr, int* v): Hàm tìm đường đi theo giải thuật Heuristic. Dựa theo cách tìm đường đi có trọng số nhỏ nhất để đi bước tiếp theo.

- Giao diện chương trình: console Aplication.


Khi thực thi, chương trình sẽ yêu cầu chọn nhập ma trận đồ thị bằng tay hay bằng file “graph.txt”. Ví dụ như hình trên chọn nhập ma trận bằng file txt. Ta nhập tiếp đỉnh bắt đầu (ở đây nhập 1), thì chương trình sẽ cho ra đáp án cho ví dụ trên:

=> Đường đi là: 1 – 2 – 5 – 3 – 4 – 1

=> Chi phí cho đường đi này theo giải thuật Heuristic là: 14.

Nếu như chọn cách nhập ma trận bằng tay thì ta phải nhập từng giá trị của ma trận vào.

- Nhấn ESC để thoát khỏi chương trình, Phím bất kỳ để tiếp tục chương trình với cách duyệt từ đỉnh khác.[Tài toàn bộ code chương trình - Turbo C++ tại đây]

5. Đánh giá thuật giải Heuristic của bài toán:

* Ưu điểm: Thuật giải Heuristic cho bài toán người đưa thư có độ phức tạp O(n2 ) tốt hơn rất nhiều so với thuật toán tối ưu (có độ phức tạp O( n!) ).

* Nhược điểm: thuật giải có những hạn chế, chưa cho ra lời giải chính xác.

>> Kết luận: Thuật giải Heuristic cho bài toán người đưa thư tuy chưa đưa ra được lời giải chính xác cho bài toán, nhưng nó cho ra một lời giải có thể chấp nhận được với độ phức tạp thấp hơn nhiều so với thuật toán tối ưu.

>>> Tải code chương trình tại đây.
Lưu ý: 
  - Sau 5s, click BỎ QUA QUẢNG CÁO (SKIP AD)
  - File grapt.txt đặt tại cùng thư mục với code chương trình.

Nguồn: thanhcuong

[ Lập trình Android ] Ví dụ: Xây dựng ứng dụng MÁY TÍNH ĐIỆN TỬ [ ứng dụng Android cơ bản ]

Xây dựng ứng dụng mô phỏng máy tính điện tử đơn giản trên Android:


Để xây dựng ứng dụng trên, chúng ta tiến hành như sau (Cài đặt trên môi trường Eclipse đã plugin SDK, xem thêm tại đây):

Bước 1: Tạo Project Vidu1 với các thành phần như hình vẽ


 Bước 2: Viết nội dung các file:  PhepTinh.java (chứa các xử lý tính toán); Vidu1.Activity.java (file chạy Android); main.xml (thiết kế giao diện); color.xml (thiết lập màu sắc); string.xml (thiết lập các giá trị cho string). Nội dung cụ thể:

+ color.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="title_color">#0000FF</color>
<color name="text_color">#DC143C</color>
<color name="resul_color">#FFD700</color>
<color name="backg_color">#F0F8FF</color>
<color name="btn_color">#FF0000</color>

</resources>

+ string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="str1">MÁY TÍNH ĐIỆN TỬ</string>
    <string name="app_name">Vd1</string>
    <string name="a">a: </string>
    <string name="b">b: </string>
    <string name="kq">Kết quả: </string>
    <string name="cong">+</string>
    <string name="tru">-</string>
    <string name="nhan">x</string>
    <string name="chia">/</string>
    <string name="xoa">Xóa</string>
    <string name="thoat">Thoát</string>
    <string name="tb1">Nhập số thứ nhất</string>
    <string name="tb2">Nhập số thứ hai</string>
     <string name="chao">http://lap-trinh-may-tinh.blogspot.com</string>
</resources>

+ main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation ="vertical"
    android:background="@color/backg_color"
    >
   
       
   <TextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"     
     android:textColor="@color/title_color"
     android:text="@string/str1"       
     android:textSize="30dp"
     />

   
   <LinearLayout
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:orientation="horizontal"
       >
       
   <TextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"     
     android:textColor="@color/text_color"
     android:text="@string/a"       
     android:textSize="30dp"
     />
   
   <EditText
android:layout_width="200dp"
     android:layout_height="50dp"
     android:textColor="@color/text_color"
     android:id="@+id/so1"
android:hint="@string/tb1"
              
   />
   
   </LinearLayout>
   
   <LinearLayout
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:orientation="horizontal"
       >
   <TextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:textColor="@color/text_color"
     android:text="@string/b"       
     android:textSize="30dp"
     />
    <EditText
android:layout_width="200dp"
     android:layout_height="50dp"
     android:textColor="@color/text_color"
     android:id="@+id/so2"
android:hint="@string/tb2"
              
   />
   
   </LinearLayout>
   
   <LinearLayout
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:orientation="horizontal"
       >
   <TextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:textColor="@color/resul_color"
     android:text="@string/kq"       
     android:textSize="30dp"
     />
   <EditText
android:layout_width="200dp"
     android:layout_height="50dp"
     android:textColor="@color/resul_color"
     android:id="@+id/ketqua"              
   />   
   </LinearLayout>
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
 <Button   
     android:layout_width="80dp"
     android:layout_height="40dp"
     android:text="@string/cong"
     android:textColor="@color/btn_color"
     android:id="@+id/phepCong"
    />
    <Button   
     android:layout_width="80dp"
     android:layout_height="40dp"
     android:text="@string/tru"
     android:textColor="@color/btn_color"
     android:id="@+id/phepTru"
    />
    <Button   
     android:layout_width="80dp"
     android:layout_height="40dp"
     android:text="@string/nhan"
     android:textColor="@color/btn_color"
     android:id="@+id/phepNhan"
    />
    <Button   
     android:layout_width="80dp"
     android:layout_height="40dp"
     android:text="@string/chia"
     android:textColor="@color/btn_color"
     android:id="@+id/phepChia"
    />
 </LinearLayout>
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
 <Button   
     android:layout_width="80dp"
     android:layout_height="40dp"
     android:text="@string/xoa"
     android:textColor="@color/btn_color"
     android:id="@+id/delete"
    />
    <Button   
     android:layout_width="80dp"
     android:layout_height="40dp"
     android:text="@string/thoat"
     android:textColor="@color/btn_color"
     android:id="@+id/cancel"
    />
 </LinearLayout>
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
  <TextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"     
     android:textColor="@color/text_color"
     android:text="@string/chao"       
     android:textSize="12dp"
     />
 </LinearLayout>

</LinearLayout>

+ PhepTinh.java:

package txt.vidu1.vidu;

public class PhepTinh {
 public float a,b;
 // khoi tao
 public PhepTinh(float a,float b){
this.a=a;this.b=b;
 }
 // tinh tong
 public float Tong(){
return a+b;
 }
 // tinh hieu
 public float Hieu(){
return a-b;
 }
 public float Nhan(){
return a*b;
 }
 public float Chia(){
if (b==0)
return 0;
return a/b;
 
 }
}

Vidu1.Activity.java

package txt.vidu1.vidu;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Vidu1Activity extends Activity {
    
    protected AlertDialog AlertDialog;

@Override
    public void onCreate(Bundle savedInstanceState) {
        
    super.onCreate(savedInstanceState);
        
        setContentView(R.layout.main);
        // khai bao cac button
        final Button btnCong= (Button) findViewById(R.id.phepCong);
        final Button btnTru=(Button) findViewById(R.id.phepTru);
        final Button btnNhan=(Button) findViewById(R.id.phepNhan);
        final Button btnChia=(Button) findViewById(R.id.phepChia);
        final Button btnXoa=(Button) findViewById(R.id.delete);
        final Button btnThoat=(Button) findViewById(R.id.cancel);
        // khai bao textView
        final TextView txvKQ=(TextView) findViewById(R.id.ketqua);
        
        // Su kien click Phep Cong
        btnCong.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View v) {
         float a= Float.valueOf(((EditText) findViewById(R.id.so1)).getText().toString());
         float b= Float.valueOf(((EditText) findViewById(R.id.so2)).getText().toString());
         PhepTinh c=new PhepTinh(a,b);
         String s=String.valueOf(c.Tong());
         txvKQ.setText(s);
        }                
        });
        // Su kien click Phep tru
        btnTru.setOnClickListener(new Button.OnClickListener() {
          public void onClick(View v){
         float a,b;
         a=Float.valueOf(((EditText) findViewById(R.id.so1)).getText().toString());
         b=Float.valueOf(((EditText) findViewById(R.id.so2)).getText().toString());
         PhepTinh t=new PhepTinh(a,b);
         txvKQ.setText(String.valueOf(t.Hieu()));          
          }
        }        
        );
        // Su kien click Phep nhan
        btnNhan.setOnClickListener(new Button.OnClickListener(){
        public void onClick(View v){
        float a,b;
        a=Float.valueOf(((EditText) findViewById(R.id.so1)).getText().toString());
        b=Float.valueOf(((EditText) findViewById(R.id.so2)).getText().toString());
        PhepTinh n=new PhepTinh(a,b);
        txvKQ.setText(String.valueOf(n.Nhan()));
        }
        }
       
        );
        
        // Su kien click Phep chia       
        btnChia.setOnClickListener(new Button.OnClickListener(){
        public void onClick(View v){
        float a,b;
        a=Float.valueOf(((EditText) findViewById(R.id.so1)).getText().toString());
        b=Float.valueOf(((EditText) findViewById(R.id.so2)).getText().toString());
        PhepTinh m=new PhepTinh(a,b);
        txvKQ.setText(String.valueOf(m.Chia()));
        }
        }
       
        );
        // Su kien click Xoa
        btnXoa.setOnClickListener(new Button.OnClickListener(){
        public void onClick(View v){
        final EditText edtSo1 = (EditText) findViewById(R.id.so1);
        edtSo1.setText("");
        final EditText edtSo2 = (EditText) findViewById(R.id.so2);
        edtSo2.setText("");
        txvKQ.setText("");
       
        }
        }        
        );
        // su kien click Thoat
        btnThoat.setOnClickListener(new Button.OnClickListener(){
        public void onClick(View v){
        AlertDialog.Builder atd = new AlertDialog.Builder(Vidu1Activity.this);
        atd.setTitle("Thong bao");
        atd.setMessage("Bạn muốn thoát ?");
        atd.setPositiveButton("Đồng ý", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        finish();        
        }
        });
        atd.show();
        }
        }        
        );
    }

}

*******

Một số tài liệu và khoá học bổ ích dành cho bạn: 

# Giáo trình: Lập Trình Android [Click để xem]

# Khoá học online:  Lập trình Android toàn tập [Click để xem]

Tìm kiếm nội dung khác: