Thứ Hai, 13 tháng 8, 2018

Android - Thành phần tùy chỉnh

Thực hiện các thành phần riêng trong các thành phần dựng sẵn có sẵn với mở rộng lớp con với lớp được định nghĩa riêng

Học lập trình Android cung cấp một danh sách lớn của các widget được xây dựng trước như Button, TextView, EditText, ListView, CheckBox, RadioButton, Bộ sưu tập, Spinner, AutoCompleteTextView vv mà bạn có thể sử dụng trực tiếp trong phát triển ứng dụng Android của bạn, nhưng có thể có một tình huống khi bạn đang không hài lòng với chức năng hiện có của bất kỳ tiện ích con nào có sẵn. 

Android cung cấp cho bạn phương tiện tạo các thành phần tùy chỉnh của riêng bạn mà bạn có thể tùy chỉnh cho phù hợp với nhu cầu của mình.

Nếu bạn chỉ cần điều chỉnh nhỏ cho tiện ích hoặc bố cục hiện tại, bạn có thể chỉ cần phân lớp tiện ích con hoặc bố cục và ghi đè các phương pháp của nó, điều này sẽ giúp bạn kiểm soát chính xác giao diện và chức năng của phần tử màn hình.

Hướng dẫn này giải thích cho bạn cách tạo Chế độ xem tùy chỉnh và sử dụng chúng trong ứng dụng của bạn bằng các bước đơn giản và dễ dàng.

ảnh minh họa

VÍ DỤ VỀ CÁC THÀNH PHẦN TÙY CHỈNH TRONG PHÂN CẤP CHẾ ĐỘ XEM TÙY CHỈNH

Tạo một thành phần tùy chỉnh đơn giản
Bậc thangSự miêu tả
1Bạn sẽ sử dụng Android studio IDE để tạo một ứng dụng Android và đặt tên ứng dụng đó là myapplication dưới một góicom.example.tutorialspoint7.myapplication như được giải thích trong chương Hello World Example .
2Tạo một tệp XML res / values ​​/ attrs.xml để định nghĩa các thuộc tính mới cùng với kiểu dữ liệu của chúng.
3Tạo tệp src / mainactivity.java và thêm mã để xác định thành phần tùy chỉnh của bạn
4Sửa đổi tệp res / layout / activity_main.xml và thêm mã để tạo ra thể hiện khung nhìn Color compound cùng với một vài thuộc tính mặc định và các thuộc tính mới.
5Chạy ứng dụng để khởi chạy trình giả lập Android và xác minh kết quả của các thay đổi được thực hiện trong ứng dụng.
Tạo tệp thuộc tính sau được gọi là attrs.xml trong thư mục res / values ​​của bạn.
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <declare-styleable name="TimeView">
      <declare-styleable name="TimeView">
         <attr name="title" format="string" />
         <attr name="setColor" format="boolean"/>
      </declare-styleable>
   </declare-styleable>
</resources>
Thay đổi tệp bố cục được sử dụng bởi hoạt động thành các hoạt động sau.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   xmlns:custom="http://schemas.android.com/apk/res-auto"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity" >

   <com.example.tutorialspoint7.myapplication.TimeView
      android:id="@+id/timeView"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:textColor="#fff"
      android:textSize="40sp"
      custom:title="my time view"
      custom:setColor="true" />

   <TextView
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:id="@+id/simple"
      android:layout_below="@id/timeView"
      android:layout_marginTop="10dp" />
</RelativeLayout>
Tạo tệp java sau đây gọi là timeview cho chế độ xem phức hợp của bạn.
package com.example.tutorialspoint7.myapplication;
/**
 * Created by TutorialsPoint7 on 9/14/2016.
 */
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.content.Context;
import android.content.res.TypedArray;

import android.graphics.Color;
import android.util.AttributeSet;
import android.widget.TextView;

public class TimeView extends TextView {
   private String titleText;
   private boolean color;

   public TimeView(Context context) {
      super(context);
      setTimeView();
   }

   public TimeView(Context context, AttributeSet attrs) {
      super(context, attrs);
      // retrieved values correspond to the positions of the attributes
         TypedArray typedArray = context.obtainStyledAttributes(attrs, 
            R.styleable.TimeView);
      int count = typedArray.getIndexCount();
      try{
         
         for (int i = 0; i < count; ++i) {
            
            int attr = typedArray.getIndex(i);
            // the attr corresponds to the title attribute
            if(attr == R.styleable.TimeView_title) {
               
               // set the text from the layout
               titleText = typedArray.getString(attr);
               setTimeView();
            } else if(attr == R.styleable.TimeView_setColor) {
               // set the color of the attr "setColor"
               color = typedArray.getBoolean(attr, false);
               decorateText();
            }
         }
      }
        
      // the recycle() will be executed obligatorily
      finally {
         // for reuse
         typedArray.recycle();
      }
   }

   public TimeView(Context context, AttributeSet attrs, int defStyle) {
      super(context, attrs, defStyle);
      setTimeView();
   }

   private void setTimeView() {
      // has the format hour.minuits am/pm
      SimpleDateFormat dateFormat = new SimpleDateFormat("hh.mm aa");
      String time = dateFormat.format(Calendar.getInstance().getTime());
      
      if(this.titleText != null )
      setText(this.titleText+" "+time);
      else
         setText(time);
   }

   private void decorateText() {
      // when we set setColor attribute to true in the XML layout
      if(this.color == true){
         // set the characteristics and the color of the shadow
         setShadowLayer(4, 2, 2, Color.rgb(250, 00, 250));
         setBackgroundColor(Color.CYAN);
      } else {
         setBackgroundColor(Color.RED);
      }
   }
}
Thay đổi tệp java hoạt động chính của bạn thành mã sau và chạy ứng dụng của bạn.
package com.example.tutorialspoint7.myapplication;

import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;

public class MainActivity extends Activity {

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

      TextView simpleText = (TextView) findViewById(R.id.simple);
      simpleText.setText("That is a simple TextView");
   }
}
Ứng dụng đang chạy sẽ trông giống như ảnh chụp màn hình sau đây.

ảnh minh họa

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