Giải đáp Các Vấn đề Thường gặp trong Lập trình Android

Lắng nghe sự kiện thay đổi nội dung EditText

editText.addTextChangedListener(new TextWatcher() {
    @Override
    public void afterTextChanged(Editable editable) {}
    
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
    
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        boolean hasContent = !s.toString().trim().isEmpty();
        btnConfirm.setEnabled(hasContent);
        btnConfirm.setClickable(hasContent);
    }
});

Thiết lập màu sắc TextView trong mã nguồn

statusTextView.setTextColor(
    getContext().getResources().getColor(R.color.status_color)
);

Truy vấn dữ liệu theo khoảng thời gian

SELECT * FROM orders 
WHERE order_date BETWEEN '2023-01-01' AND '2023-12-31';

Lưu ý: BETWEEN bao gồm cả ngày bắt đầu/kết thúc

Ngăn ProgressDialog đóng khi chạm bên ngoài

ProgressDialog progress = new ProgressDialog(this);
progress.setMessage("Đang xử lý...");
progress.setCanceledOnTouchOutside(false);
progress.show();

So sánh mkdir() và mkdirs()

File newDir = new File("/sdcard/Documents/Reports");
// Tạo tất cả thư mục cha nếu cần
newDir.mkdirs(); 

Thiết lập kích thước chữ cho TextView

Cách 1: Trong XML

<TextView
    android:textSize="18sp"
    android:textColor="#FF5722"/>

Cách 2: Trong Java/Kotlin

textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);

Xử lý ngắt dòng trong TextView

String content = dataModel.getContent().replace("\\n", "\n");
textDisplay.setText(content);

Điều khiển bàn phím ảo

InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(inputField.getWindowToken(), 0);

Đường dẫn lưu file trong Android

// Lưu trên bộ nhớ ngoài
File externalFile = new File(Environment.getExternalStorageDirectory(), "image.jpg");

// Lưu trong thư mục ứng dụng
File internalFile = new File(getFilesDir(), "config.json");

Lấy kích thước màn hình

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int screenWidth = metrics.widthPixels;
int screenHeight = metrics.heightPixels;

Lấy kích thước View

ViewTreeObserver observer = view.getViewTreeObserver();
observer.addOnGlobalLayoutListener(() -> {
    int viewWidth = view.getWidth();
    int viewHeight = view.getHeight();
});

Lấy khung hình đầu tiên từ video

MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(videoPath);
Bitmap firstFrame = retriever.getFrameAtTime();
imagePreview.setImageBitmap(firstFrame);

Thiết lập khoảng cách giữa các mục ListView

<ListView
    android:divider="@color/divider_gray"
    android:dividerHeight="1dp"/>

Thẻ: EditText TextView SQLite ProgressDialog filesystem

Đăng vào ngày 21 tháng 6 lúc 23:37