Thứ Tư, 29 tháng 8, 2018

Android - Hộp thoại cảnh báo

Hộp thoại là cửa sổ nhỏ nhắc người dùng đưa ra quyết định hoặc nhập thông tin bổ sung.

Học lập trình Android một số lần trong ứng dụng của bạn, nếu bạn muốn hỏi người dùng về quyết định giữa có hoặc không trả lời bất kỳ hành động cụ thể nào do người dùng thực hiện, bằng cách giữ nguyên hoạt động đó và không thay đổi màn hình, bạn có thể sử dụng Hộp thoại thông báo.

Để tạo một hộp thoại cảnh báo, bạn cần tạo một đối tượng của AlertDialogBuilder, một lớp bên trong của AlertDialog. Cú pháp của nó được đưa ra dưới đây
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
Bây giờ bạn phải đặt nút tích cực (có) hoặc âm (không) bằng cách sử dụng đối tượng của lớp AlertDialogBuilder. Cú pháp của nó là
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 lớp trình xây dựng để tùy chỉnh hộp thoại cảnh báo. Chúng được liệt kê dưới đây

Sr.NoLoại phương thức & mô tả
1setIcon (Biểu tượng có thể vẽ)

Phương thức này đặt biểu tượng của hộp thoại cảnh báo.
2setCancelable (boolean cancel có thể)

Phương thức này đặt thuộc tính mà hộp thoại có thể bị hủy bỏ hay không
3setMessage (thông báo CharSequence)

Phương thức này đặt thông điệp được hiển thị trong hộp thoại cảnh báo
4setMultiChoiceItems (CharSequence [] items, boolean [] checkedItems, DialogInterface.OnMultiChoiceClickListener listener)

Phương thức này thiết lập danh sách các mục được hiển thị trong hộp thoại dưới dạng nội dung. Tùy chọn đã chọn sẽ được người nghe thông báo
5setOnCancelListener (DialogInterface.OnCancelListener onCancelListener)

Phương thức này Đặt callback sẽ được gọi nếu hộp thoại bị hủy.
6setTitle (Tiêu đề CharSequence)

Phương thức này đặt tiêu đề xuất hiện trong hộp thoại
Sau khi tạo và thiết lập trình tạo hộp thoại, bạn sẽ tạo một hộp thoại cảnh báo bằng cách gọi phương thức create () của lớp trình tạo. Cú pháp của nó là
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
Điều này sẽ tạo ra hộp thoại cảnh báo và sẽ hiển thị nó trên màn hình.

Đoạn hộp thoại

Trước khi nhập vào một ví dụ, chúng ta cần phải biết phân đoạn hộp thoại.Dialog fragment là một đoạn có thể hiển thị đoạn trong hộp thoại
public class DialogFragment extends DialogFragment {
   @Override
   public Dialog onCreateDialog(Bundle savedInstanceState) {
      // Use the Builder class for convenient dialog construction
      AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
      builder.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int id) {
            toast.makeText(this,"enter a text here",Toast.LENTH_SHORT).show();
         }
      })
      .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int id) {
            finish();
         });
         // Create the AlertDialog object and return it
         return builder.create();
      }
   }
}

Hộp thoại danh sách

Nó đã được sử dụng để hiển thị danh sách các mục trong một hộp thoại. Giả sử, người dùng cần phải chọn một danh sách các mục hoặc người nào khác cần phải bấm vào một mục từ nhiều danh sách các mục. Trong trường hợp này chúng ta có thể sử dụng hộp thoại danh sách.
public Dialog onCreateDialog(Bundle savedInstanceState) {
   AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
   builder.setTitle(Pick a Color)
   
   .setItems(R.array.colors_array, new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int which) {
         // The 'which' argument contains the index position
         // of the selected item
      }
   });
   return builder.create();
}

Hộp thoại danh sách lựa chọn một lần

Nó đã được sử dụng để thêm danh sách lựa chọn duy nhất để hộp thoại. Chúng tôi có thể kiểm tra hoặc bỏ chọn theo sự lựa chọn của người dùng.
public Dialog onCreateDialog(Bundle savedInstanceState) {
   mSelectedItems = new ArrayList();
   AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
   
   builder.setTitle("This is list choice dialog box");
   .setMultiChoiceItems(R.array.toppings, null,
      new DialogInterface.OnMultiChoiceClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which, boolean isChecked) {
         
         if (isChecked) {
            // If the user checked the item, add it to the selected items
            mSelectedItems.add(which);
         }
         
         else if (mSelectedItems.contains(which)) {
            // Else, if the item is already in the array, remove it 
            mSelectedItems.remove(Integer.valueOf(which));
         }
      }
   })
   
   // Set the action buttons
   .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int id) {
         // User clicked OK, so save the mSelectedItems results somewhere
         // or return them to the component that opened the dialog
         ...
      }
   })
   
   .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int id) {
         ...
      }
   });
   return builder.create();
}

Thí dụ

Ví dụ sau minh họa việc sử dụng AlertDialog trong Android.

Để thử nghiệm với ví dụ này, bạn cần chạy trên trình mô phỏng hoặc thiết bị thực tế.

Các bướcSự miêu tả
1Bạn sẽ sử dụng Android studio để tạo ứng dụng Android và đặt tên ứng dụng là Ứng dụng của tôi theo gói com.example.sairamkrishna.myapplication.
2Sửa đổi tệp src / MainActivity.java để thêm mã cảnh báo để khởi chạy hộp thoại.
3Sửa đổi tệp XML bố trí res / layout / activity_main.xml thêm bất kỳ thành phần GUI nào nếu cần.
4Không cần phải thay đổi hằng số chuỗi mặc định. Android studio sẽ xử lý các chuỗi mặc định ở các giá trị / string.xml
5Chạy ứng dụng và chọn một thiết bị Android đang chạy và cài đặt ứng dụng trên đó và xác minh kết quả.
Đây là mã được sửa đổi của src / MainActivity.java
package com.example.sairamkrishna.myapplication;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
   @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("Are you sure,
         You wanted to make decision");
      alertDialogBuilder.setPositiveButton("yes", 
         new DialogInterface.OnClickListener() {
         @Override
         public void onClick(DialogInterface arg0, int arg1) {
            Toast.makeText(MainActivity.this,"You clicked yes 
               button",Toast.LENGTH_LONG).show();
         }
      });

      alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
         Override
         public void onClick(DialogInterface dialog, int which) {
            finish();
         }
      });

      AlertDialog alertDialog = alertDialogBuilder.create();
      alertDialog.show();
   }
}
Đây là mã được sửa đổi của res / layout / activity_main.xml

Trong đoạn mã dưới đây abc cho biết logo của tutorialspoint.com
<?xml version="1.0" encoding="utf-8"?>
<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:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" 
   tools:context=".MainActivity">
   
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Alert Dialog"
      android:id="@+id/textView"
      android:textSize="35dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorialspoint"
      android:id="@+id/textView2"
      android:textColor="#ff3eff0f"
      android:textSize="35dp"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true" />
      
   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView2"
      android:layout_alignRight="@+id/textView2"
      android:layout_alignEnd="@+id/textView2"
      android:layout_alignLeft="@+id/textView"
      android:layout_alignStart="@+id/textView" />
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Alert dialog"
      android:id="@+id/button"
      android:layout_below="@+id/imageView"
      android:layout_alignRight="@+id/textView2"
      android:layout_alignEnd="@+id/textView2"
      android:layout_marginTop="42dp"
      android:onClick="open"
      android:layout_alignLeft="@+id/imageView"
      android:layout_alignStart="@+id/imageView" />
      
</RelativeLayout>
Đây là Strings.xml
<resources>
    <string name="app_name">My Application</string>
</resources>
Đây là mã mặc định của AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sairamkrishna.myapplication" >

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name="com.example.sairamkrishna.myapplication.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>
      
   </application>
</manifest>
Hãy thử chạy ứng dụng của bạn. Tôi cho rằng bạn đã kết nối thiết bị Android Mobile thực tế với máy tính của mình.

Để chạy ứng dụng từ Android studio, hãy mở một trong các tệp hoạt động của dự án của bạn và nhấp vào biểu tượng Chạy từ thanh công cụ.

Trước khi bắt đầu ứng dụng của bạn,] Android studio sẽ hiển thị cửa sổ sau để chọn tùy chọn nơi bạn muốn chạy ứng dụng lập trình Android của mình.

học lập trình Android
Chọn một tùy chọn của bạn và sau đó nhấp vào nó. Giả sử, nếu bạn đã nhấp vào nút có, thì kết quả sẽ như sau

học lập trình Android
nếu bạn bấm vào nút không có nó sẽ gọi kết thúc () và nó sẽ đóng ứng dụng của bạn.

Không có nhận xét nào:

Đăng nhận xét

Lập trình Android - RenderScript

Trong chương này, chúng ta sẽ tìm hiểu về Android RenderScript. Thông thường các ứng dụng trên Android được thiết kế để tiêu thụ tài nguyên ...