Thứ Năm, 27 tháng 9, 2018

Android - Google Maps

Lập trình Android cho phép chúng tôi tích hợp bản đồ google trong ứng dụng của chúng tôi. Bạn có thể hiển thị bất kỳ vị trí nào trên bản đồ hoặc có thể hiển thị các tuyến đường khác nhau trên bản đồ, vv Bạn cũng có thể tùy chỉnh bản đồ theo lựa chọn của mình.

Google Map - Tệp bố cục

Bây giờ bạn phải thêm mảnh bản đồ vào tệp bố cục xml. Cú pháp của nó được đưa ra dưới đây
<fragment
   android:id="@+id/map"
   android:name="com.google.android.gms.maps.MapFragment"
   android:layout_width="match_parent"
   android:layout_height="match_parent"/>

Google Map - Tệp AndroidManifest

Điều tiếp theo bạn cần làm là thêm một số quyền cùng với khóa API Google Map trong tệp AndroidManifest.XML. Cú pháp của nó được đưa ra dưới đây
<!--Permissions-->

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.
   READ_GSERVICES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<!--Google MAP API key-->

<meta-data
   android:name="com.google.android.maps.v2.API_KEY"
   android:value="AIzaSyDKymeBXNeiFWY5jRUejv6zItpmr2MVyQ0" />        

Tùy chỉnh Google Map

Bạn có thể dễ dàng tùy chỉnh bản đồ google từ chế độ xem mặc định của nó và thay đổi nó theo nhu cầu của bạn.

Thêm điểm đánh dấu

Bạn có thể đặt một nhà sản xuất với một số văn bản trên nó hiển thị vị trí của bạn trên bản đồ. Nó có thể được thực hiện bằng phương thức addMarker () . Cú pháp của nó được đưa ra dưới đây
final LatLng TutorialsPoint = new LatLng(21 , 57);
Marker TP = googleMap.addMarker(new MarkerOptions()
   .position(TutorialsPoint).title("TutorialsPoint")); 

Thay đổi loại bản đồ

Bạn cũng có thể thay đổi loại MAP. Có bốn loại bản đồ khác nhau và mỗi loại cung cấp một cái nhìn khác nhau về bản đồ. Các loại này là Bình thường, Lai, Vệ tinh và địa hình. Bạn có thể sử dụng chúng như bên dưới
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);

Bật / Tắt thu phóng

Bạn cũng có thể bật hoặc tắt cử chỉ thu phóng trên bản đồ bằng cách gọi phương thức setZoomControlsEnabled (boolean) . Cú pháp của nó được đưa ra dưới đây
googleMap.getUiSettings().setZoomGesturesEnabled(true);
Ngoài các tùy chỉnh này, còn có các phương pháp khác có sẵn trong lớp GoogleMap, giúp bạn tùy chỉnh bản đồ hơn. Chúng được liệt kê dưới đây

Sr.NoPhương pháp & mô tả
1addCircle (tùy chọn CircleOptions)

Phương pháp này thêm vòng tròn vào bản đồ
2addPolygon (Các tùy chọn PolygonOptions)

Phương thức này thêm một đa giác vào bản đồ
3addTileOverlay (Tùy chọn TileOverlayOptions)

Phương pháp này thêm lớp phủ lát gạch vào bản đồ
4animateCamera (Cập nhật CameraUpdate)
Phương thức này Di chuyển bản đồ theo bản cập nhật bằng một hoạt ảnh
5thông thoáng()
Phương pháp này xóa mọi thứ khỏi bản đồ.
6getMyLocation ()
Phương thức này trả về vị trí người dùng hiện đang được hiển thị.
7moveCamera (Cập nhật CameraUpdate)

Phương pháp này định vị lại máy ảnh theo hướng dẫn được xác định trong bản cập nhật
số 8setTrafficEnabled (kích hoạt boolean)

Phương pháp này Bật hoặc tắt lớp giao thông.
9ảnh chụp nhanh (GoogleMap.SnapshotReadyCallback gọi lại)
Phương pháp này Chụp nhanh bản đồ
10stopAnimation ()

Phương pháp này dừng hoạt ảnh của máy ảnh nếu có

Thí dụ

Dưới đây là ví dụ minh họa việc sử dụng lớp GoogleMap. Nó tạo ra một ứng dụng M cơ bản cho phép bạn điều hướng thông qua bản đồ.

Để thử nghiệm với ví dụ này, bạn có thể chạy nó trên một thiết bị thực tế hoặc trong một trình giả lập.

Tạo một dự án với hoạt động bản đồ google như hình dưới đây

Học lập trình Android

Nó sẽ mở ra màn hình sau đây và sao chép url giao diện điều khiển cho Khóa API như hình dưới đây

Sao chép và dán nó vào trình duyệt của bạn. Nó sẽ cung cấp cho màn hình sau đây -

Nhấp vào tiếp tục và nhấp vào Tạo khóa API sau đó nó sẽ hiển thị màn hình sau

Đây là nội dung của activity_main.xml .
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:map="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:id="@+id/map"
   android:name="com.google.android.gms.maps.SupportMapFragment"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context="com.example.tutorialspoint7.myapplication.MapsActivity" />
Đây là nội dung của MapActivity.java .

Trong đoạn mã dưới đây, chúng tôi đã cung cấp các chi tiết về vĩ độ và kinh độ mẫu
package com.example.tutorialspoint7.myapplication;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

   private GoogleMap mMap;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_maps);
      // Obtain the SupportMapFragment and get notified when the map is ready to be used.
      SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
         .findFragmentById(R.id.map);
      mapFragment.getMapAsync(this);
   }
   
   /**
      * Manipulates the map once available.
      * This callback is triggered when the map is ready to be used.
      * This is where we can add markers or lines, add listeners or move the camera.
      * In this case, we just add a marker near Sydney, Australia.
      * If Google Play services is not installed on the device. 
      * This method will only be triggered once the user has installed 
         Google Play services and returned to the app.
   */
  
   @Override
   public void onMapReady(GoogleMap googleMap) {
      mMap = googleMap;
      // Add a marker in Sydney and move the camera
      LatLng TutorialsPoint = new LatLng(21, 57);
      mMap.addMarker(new 
         MarkerOptions().position(TutorialsPoint).title("Tutorialspoint.com"));
      mMap.moveCamera(CameraUpdateFactory.newLatLng(TutorialsPoint));
   }
}
Sau đây là nội dung của tệp AndroidManifest.xml .
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.tutorialspoint7.myapplication">

   <!--
      The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
      Google Maps Android API v2, but you must specify either coarse or fine
      location permissions for the 'MyLocation' functionality. 
   -->
    
   <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
   <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
   <uses-permission android:name="android.permission.INTERNET" />
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">

      <!--
         The API key for Google Maps-based APIs is defined as a string resource.
         (See the file "res/values/google_maps_api.xml").
         Note that the API key is linked to the encryption key used to sign the APK.
         You need a different API key for each encryption key, including the release key 
         that is used to sign the APK for publishing.
         You can define the keys for the debug and 
            release targets in src/debug/ and src/release/. 
      -->
      
      <meta-data
         android:name="com.google.android.geo.API_KEY"
         android:value="AIzaSyAXhBdyKxUo_cb-EkSgWJQTdqR0QjLcqes" />

      <activity
         android:name=".MapsActivity"
         android:label="@string/title_activity_maps">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>

</manifest>
Đầu ra phải như thế này

Học lập trình Android

Thứ Năm, 20 tháng 9, 2018

Android - Cử chỉ

Học lập trình Android cung cấp các loại sự kiện màn hình cảm ứng đặc biệt như pinch, nhấn đúp, cuộn, nhấn và giữ liên tục. Đây là tất cả được gọi là cử chỉ.

Android cung cấp lớp GestureDetector để nhận các sự kiện chuyển động và cho chúng tôi biết rằng các sự kiện này tương ứng với cử chỉ hay không.

Để sử dụng nó, bạn cần phải tạo một đối tượng của Gesture Detector và sau đó mở rộng một lớp khác với Gesture Detector. Simple On Gesture Listener để hoạt động như một trình lắng nghe và ghi đè một số phương thức. Cú pháp của nó được đưa ra dưới đây.
GestureDetector myG;
myG = new GestureDetector(this,new Gesture());
   
class Gesture extends GestureDetector.SimpleOnGestureListener{
   public boolean onSingleTapUp(MotionEvent ev) {
   }
   
   public void onLongPress(MotionEvent ev) {
   }
   
   public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
   float distanceY) {
   }
   
   public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
   float velocityY) {
   }
}

Xử lý cử chỉ chụm

Android cung cấp lớp ScaleGestureDetector để xử lý các cử chỉ như pinch vv Để sử dụng nó, bạn cần khởi tạo một đối tượng của lớp này. Cú pháp của nó như sau:
ScaleGestureDetector SGD;
SGD = new ScaleGestureDetector(this,new ScaleListener());
Tham số đầu tiên là ngữ cảnh và tham số thứ hai là trình nghe sự kiện. Chúng ta phải định nghĩa trình nghe sự kiện và ghi đè lên một hàm OnTouchEvent để làm cho nó hoạt động. Cú pháp của nó được đưa ra dưới đây
public boolean onTouchEvent(MotionEvent ev) {
   SGD.onTouchEvent(ev);
   return true;
}

private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
   @Override
   public boolean onScale(ScaleGestureDetector detector) {
      float scale = detector.getScaleFactor();
      return true;
   }
}
Ngoài cử chỉ chụm, còn có các phương pháp khác có sẵn để thông báo thêm về các sự kiện chạm. Chúng được liệt kê dưới đây

Sr.NoPhương pháp & mô tả
1getEventTime ()

Phương thức này nhận được thời gian sự kiện của sự kiện hiện tại đang được xử lý ..
2getFocusX ()

Phương thức này nhận tọa độ X của tiêu điểm cử chỉ hiện tại.
3getFocusY ()

Phương thức này nhận tọa độ Y của tiêu điểm cử chỉ hiện tại.
4getTimeDelta ()

Phương thức này trả về chênh lệch thời gian tính bằng mili giây giữa sự kiện mở rộng được chấp nhận trước đó và sự kiện mở rộng hiện tại.
5isInProgress ()

Phương thức này trả về true nếu cử chỉ tỷ lệ đang được tiến hành ..
6onTouchEvent (Sự kiện MotionEvent)

Phương thức này chấp nhận MotionEvents và gửi các sự kiện khi thích hợp.

Thí dụ

Đây là một ví dụ minh họa việc sử dụng lớp ScaleGestureDetector. Nó tạo ra một ứng dụng cơ bản cho phép bạn phóng to và thu nhỏ thông qua pinch.

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

Các bướcSự miêu tả
1Bạn sẽ sử dụng Android studio để tạo ứng dụng Android theo gói com.example.sairamkrishna.myapplication.
2Sửa đổi tệp src / MainActivity.java để thêm mã cần thiết.
3Sửa đổi res / layout / activity_main để thêm các thành phần XML tương ứng
4Chạy ứng dụng và chọn thiết bị Android đang chạy và cài đặt ứng dụng trên đó và xác minh kết quả
Sau đây là nội dung của tệp hoạt động chính đã sửa đổi src / MainActivity.java .
package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.graphics.Matrix;
import android.os.Bundle;

import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.widget.ImageView;

public class MainActivity extends Activity {
   private ImageView iv;
   private Matrix matrix = new Matrix();
   private float scale = 1f;
   private ScaleGestureDetector SGD;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      iv=(ImageView)findViewById(R.id.imageView);
      SGD = new ScaleGestureDetector(this,new ScaleListener());
   }

   public boolean onTouchEvent(MotionEvent ev) {
      SGD.onTouchEvent(ev);
      return true;
   }

   private class ScaleListener extends ScaleGestureDetector.
      SimpleOnScaleGestureListener {
      
      @Override
      public boolean onScale(ScaleGestureDetector detector) {
         scale *= detector.getScaleFactor();
         scale = Math.max(0.1f, Math.min(scale, 5.0f));
         matrix.setScale(scale, scale);
         iv.setImageMatrix(matrix);
         return true;
      }
   }
}


Sau đây là nội dung sửa đổi của xml res / layout / activity_main.xml .
Ở đây abc biểu thị logo của hướng dẫn
<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:text="Gestures  
      Example" android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      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="Tutorials point"
      android:id="@+id/textView"
      android:layout_below="@+id/textview"
      android:layout_centerHorizontal="true"
      android:textColor="#ff7aff24"
      android:textSize="35dp" />
      
   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:src="@drawable/abc"
      android:scaleType="matrix"
      android:layout_below="@+id/textView"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true"
      android:layout_alignParentBottom="true"
      android:layout_alignParentRight="true"
      android:layout_alignParentEnd="true" />
      
</RelativeLayout>
Sau đây là nội dung của res / values ​​/ string.xml .
<resources>
   <string name="app_name>My Application</string>
</resources>
Sau đây là nội dung của tệp 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.myapplicationMainActivity"
         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ụ. Đầu ra mẫu phải như thế này
Học lập trình Android
Bây giờ chỉ cần đặt hai ngón tay trên màn hình Android, và tách chúng ra một phần và bạn sẽ thấy rằng hình ảnh Android đang phóng to. Nó được thể hiện trong hình dưới đây
Học lập trình Android
Bây giờ một lần nữa đặt hai ngón tay trên màn hình Android, và cố gắng đóng chúng lại và bạn sẽ thấy rằng hình ảnh Android hiện đang co lại. Nó được thể hiện trong hình dưới đây

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 ...