山岸  英樹

山岸 英樹

1656759900

Android開発者向けの5つの便利なKotlin拡張機能

Kotlin拡張機能とは何ですか?

Kotlinは、クラスから継承したり、などのデザインパターンを使用したりすることなく、クラスまたはインターフェイスを新しい機能で拡張する機能を提供しますDecorator。これは、拡張機能と呼ばれる特別な宣言を介して行われます。

たとえば、String主にコードでクラスを使用しました。一部のプロパティをに含めたい場合がありますが、含まれString classません。この場合、KotlinExtensionメソッドを使用すると可能になります。

String文字列内のすべての文字をアルファベット順に並べ替える1つのプロパティが必要だとします。Extensionそのための関数を作ってみましょう。

fun String.sortAlphabetically() = toCharArray().apply { sort() }

拡張機能の機能とは何か、そしてそれらがどのように見えるかを理解していただければ幸いです。

1. EditText onChanged Text

テキストの編集の変更は、モバイルアプリケーションで実行する重要なタスクです。どのテキストが変更されたかを確認します。テキストの使用例の1つはEditText.onChange、3〜4文字の文字が検索を開始したときにボタンを押さずに、検索バーで何かを検索することです。テキストに変更がある場合、関数は文字列で変更されたテキストを返します。

fun EditText.onChange(textChanged: ((String) -> Unit)) {
    this.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {

        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            textChanged.invoke(s.toString())
        }
    })
}

2.トーストを表示

この拡張機能を使用すると、ActivitiesまたはFragmentのどこでも、またはを渡すことができる場所ならどこでもtoastを呼び出すことができますContext。電話をかけるだけshowToast(MESSAGE_YOU_WANT_TO_SHOW)で、デフォルトではトーストの持続時間はになりますToast.LENGTH_SHORT

fun Context.showToast(message: String?, length: Int = Toast.LENGTH_SHORT) {
    message?.let {
        Toast.makeText(this, it, length).show()
    }
}


//Usage
showToast("Hello World👋")

3.スナックバーを表示する

Snackbarモバイルアプリの画面下部に簡単なメッセージを表示するために使用されます。トーストの一種です。でSnackBar、要件がある場合はアクションボタンがある場合があります。

fun View.showSnackMessage(
    message: String?,
    anchorView: View? = null,
    backgroundColor: Int,
    textColor: Int,
    length: Int = Snackbar.LENGTH_SHORT
) {
    message?.let {
        try {
            val snack = Snackbar.make(this, it, length)
            snack.setBackgroundTint(ContextCompat.getColor(context, backgroundColor))
            snack.setTextColor(ContextCompat.getColor(context, textColor))
            snack.anchorView = anchorView
            snack.show()
        } catch (ex: Exception) {
            ex.showLog()
        }
    }
}

4.インターネットが利用可能かどうかを確認します

ファイルのアップロードやアプリでインターネットからのあらゆる種類のデータの取得などのAPIリクエストを行う際には、インターネットが利用可能である必要があります。インターネットが利用できない場合、アプリはクラッシュします。

1つのシナリオで、Androidプロジェクトに複数のアクティビティとフラグメントがあり、インターネットが多くのポイントで利用可能であることを確認する必要がある場合、接続マネージャーを数回呼び出す必要があります。これは、プロジェクトで使用する拡張機能が1つあるためです。 。

それもあなたを助けます。

fun Context.isNetworkAvailable(): Boolean {
    val manager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        val capabilities = manager.getNetworkCapabilities(manager.activeNetwork)
        if (capabilities != null) {
            if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                return true
            } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                return true
            } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
                return true
            }
        }
    } else {
        try {
            val activeNetworkInfo = manager.activeNetworkInfo
            if (activeNetworkInfo != null && activeNetworkInfo.isConnected) {
                return true
            }
        } catch (e: Exception) {
            e.showLog()
        }
    }
    return false
}


//Usage
//For example, In the MainActivity, how to call this?
if(isNetworkAvailable()){
  //Perform your task
}else{
   showToast("Internet is not available, Try Later")
}   
  

インターネット接続チェック拡張機能

5.ビューの可視性を制御する

Androidで、取得したデータに応じてビューを表示または非表示にする場合。特定のビューの表示を非表示にしたい場合があります。たとえば、を使用ProgressBarすると、一部のデータがバックエンドまたはローカルソースから取得しているときにのみプログレスバーを表示したいとします。データがフェッチされたら、プログレスバーを非表示にします。

Androidでこのアクションを実行する一般的な方法はbinding.loadingProgressBar = View.GONE、毎回実行する必要があります。Viewこれで、クラスを使用して1つの拡張関数を作成するだけで、ニーズを満たすことができます。

fun View.show() {
    visibility = View.VISIBLE
}

fun View.hide() {
    visibility = View.GONE
}

fun View.invisible() {
    visibility = View.INVISIBLE
}

//Removing visibility of ProgressBar
//Using Extension
binding.loadingPb.hide()
//Without Extension
binding.loadingPb.visibility = View.GONE

結論

それで全部です!あなたが何かを学んだことを願っています。疑問がある場合は、コメントしてください。私はあなたの問題を喜んで解決します。

ありがとう、そして乾杯!

ソース:https ://betterprogramming.pub/5-useful-kotlin-extensions-for-android-developers-485f7c9ad7e8

#kotlin #android #web-development 

Android開発者向けの5つの便利なKotlin拡張機能
Mike  Kozey

Mike Kozey

1656758400

Edge_detection: Flutter Plugin to Detect Edges Of Objects, Scan Paper

edge_detection

A flutter plugin to detect edges of objects, scan paper, detect corners, detect rectangles. It allows cropping of the detected object image and returns the path of the cropped image.

Usage:

iOS

iOS 10.0 or higher is needed to use the plugin. If compiling for any version lower than 10.0 make sure to check the iOS version before using the plugin. Change the minimum platform version to 10 (or higher) in your ios/Podfile file.

Add below permission to the ios/Runner/Info.plist:

  • one with the key Privacy - Camera Usage Description and a usage description.

Or in text format add the key:

<key>NSCameraUsageDescription</key>
<string>Can I use the camera please?</string>

Android

The plugin code is written in kotlin 1.5.31 so the same has to be set to the android project of yours for compilation. Change the kotlin_version to 1.5.31 in your android/build.gradle file.

ext.kotlin_version = '1.5.31'

Change the minimum Android SDK version to 21 (or higher) in your android/app/build.gradle file.

minSdkVersion 21

Add dependency:

Please check the latest version before installation.

dependencies:
  flutter:
    sdk: flutter
  edge_detection: ^1.0.9

Add the following imports to your Dart code:

import 'package:edge_detection/edge_detection.dart';

//Make sure to await the call to detectEdge.
String imagePath = await EdgeDetection.detectEdge;

Installing

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add edge_detection

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  edge_detection: ^1.0.9

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:edge_detection/edge_detection.dart';

example/lib/main.dart

import 'dart:async';
import 'dart:io';

import 'package:edge_detection/edge_detection.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String? _imagePath;

  @override
  void initState() {
    super.initState();
  }

  Future<void> getImage() async {
    String? imagePath;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      imagePath = (await EdgeDetection.detectEdge);
      print("$imagePath");
    } on PlatformException catch (e) {
      imagePath = e.toString();
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _imagePath = imagePath;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Center(
                child: ElevatedButton(
                  onPressed: getImage,
                  child: Text('Scan'),
                ),
              ),
              SizedBox(height: 20),
              Text('Cropped image path:'),
              Padding(
                padding: const EdgeInsets.only(top: 0, left: 0, right: 0),
                child: Text(
                  _imagePath.toString(),
                  textAlign: TextAlign.center,
                  style: TextStyle(fontSize: 14),
                ),
              ),
              Visibility(
                visible: _imagePath != null,
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Image.file(
                    File(_imagePath ?? ''),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Demo

Demo

Screenshots

Android

iOS

Using these native implementation
https://github.com/WeTransfer/WeScan

https://github.com/KePeng1019/SmartPaperScan

Author: Sawankumarbundelkhandi
Source Code: https://github.com/sawankumarbundelkhandi/edge_detection 
License: Apache-2.0 license

#flutter #dart #edge #ios #android 

Edge_detection: Flutter Plugin to Detect Edges Of Objects, Scan Paper

Builder Implementations Wrapping Dart VM Compilers

Vm compilers for users of package:build.

Installation

This package is intended to be used as a development dependency for users of package:build who want to run code in the Dart vm with precompiled kernel files. This allows you to share compilation of dependencies between multiple entrypoints, instead of doing a monolithic compile of each entrypoint like the Dart VM would normally do on each run.

Note: If you want to use this package for running tests with dart run build_runner test you will also need a build_test dev dependency.

Usage

This package creates a .vm.app.dill file corresponding to each .dart file that contains a main function.

These files can be passed directly to the vm, instead of the dart script, and the vm will skip its initial parse and compile step.

You can find the output either by using the -o <dir> option for build_runner, or by finding it in the generated cache directory, which is located at .dart_tool/build/generated/<your-package>.

Configuration

There are no configuration options available at this time.

Custom Build Script Integration

If you are using a custom build script, you will need to add the following builder applications to what you already have, sometime after the build_modules builder applications:

    apply('build_vm_compilers|entrypoint',
        [vmKernelEntrypointBuilder], toRoot(),
        hideOutput: true,
        // These globs should match your entrypoints only.
        defaultGenerateFor: const InputSet(
            include: const ['bin/**', 'tool/**', 'test/**.vm_test.dart'])),
]

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add build_vm_compilers

With Flutter:

 $ flutter pub add build_vm_compilers

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  build_vm_compilers: ^1.0.11

Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:build_vm_compilers/build_vm_compilers.dart'; 

Download Details:

Author: build

Source Code: https://github.com/dart-lang/build/tree/master/build_vm_compilers

#dart #android #ios 

Builder Implementations Wrapping Dart VM Compilers

Local Storage inspector for Flutter

Plugin providing shared preferences inspector capabilities for local storage inspector.

See https://pub.dev/packages/storage_inspector

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add preferences_local_storage_inspector

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  preferences_local_storage_inspector: ^0.2.3

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:preferences_local_storage_inspector/preferences_local_storage_inspector.dart'; 

example/example.dart

import 'package:flutter/material.dart';
import 'package:preferences_local_storage_inspector/preferences_local_storage_inspector.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:storage_inspector/storage_inspector.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // ignore: avoid_print
  storageInspectorLogger = (e) => print(e);

  final preferences = await SharedPreferences.getInstance();

  final driver = StorageServerDriver(
    bundleId: 'com.example.test',
    icon: '<some icon>',
  );
  final keyValueServer =
      PreferencesKeyValueServer(preferences, 'Preferences', keySuggestions: {
    const ValueWithType(StorageType.string, 'testBool'),
    const ValueWithType(StorageType.string, 'testInt'),
    const ValueWithType(StorageType.string, 'testFloat'),
  });
  driver.addKeyValueServer(keyValueServer);

  // Don't wait for a connection from the instrumentation driver
  await driver.start(paused: false);

  // run app
  await Future<void>.delayed(const Duration(minutes: 15));

  await driver.stop(); //Optional when main ends
} 

Download Details:

Author: NicolaVerbeeck

Source Code: https://github.com/NicolaVerbeeck/flutter_local_storage_inspector

#flutter #android #ios 

Local Storage inspector for Flutter

Flutter Plugin for KARTE Notification, Provides A Simple API

KARTE Notification for Flutter

A Flutter plugin to use the KARTE Notification API, for both Android & iOS. KARTE Notification package provides a simple API for push notification.

Documentation

The developer guide is located at

License

Flutter KARTE Notification package is published under the Apache 2.0 License.

Your use of KARTE is governed by the KARTE Terms of Use.

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add karte_notification

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  karte_notification: ^1.1.0

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:karte_notification/karte_notification.dart'; 

example/lib/main.dart

import 'dart:async';

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:karte_core/karte_core.dart';
import 'package:karte_notification/karte_notification.dart' as krt;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

Future<dynamic> myBackgroundMessageHandler(RemoteMessage message) async {
  // Called when received notification on background only Android
  print('myBackgroundMessageHandler $message');
  var karteNotification = await krt.Notification.create(message);
  print("karte notification: $karteNotification");
  if (karteNotification != null) {
    karteNotification.handleForAndroid();
  }
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _homeScreenText = "Waiting for token...";
  String _logText = "";
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;

  void updateState({String? log, String? token}) {
    if (!mounted) return;
    setState(() {
      if (log != null) _logText += log;
      if (token != null) _homeScreenText = "Push Messaging token: $token";
    });
  }

  void checkInitialMessage() async {
    RemoteMessage? message =
        await FirebaseMessaging.instance.getInitialMessage();
    // Called when app launch by tap notification on iOS
    print("checkInitialMessage: $message");
    updateState(log: "\nonLaunch");
    if (message == null) return;
    var karteNotification = await krt.Notification.create(message);
    print("karte notification: $karteNotification");
    if (karteNotification != null) {
      karteNotification.handleForIOS();
    }
  }

  @override
  void initState() {
    super.initState();

    checkInitialMessage();
    FirebaseMessaging.onBackgroundMessage(myBackgroundMessageHandler);
    FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
      // Called when received notification on foreground
      print("onMessage: $message");
      updateState(log: "\nonMessage");
      var karteNotification = await krt.Notification.create(message);
      print("karte notification: $karteNotification");
      if (karteNotification != null) {
        karteNotification.handleForAndroid();
      }
    });
    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) async {
      // Called when app resume by tap notification on iOS
      print("onMessageOpenedApp: $message");
      updateState(log: "\nonMessageOpenedApp");
      var karteNotification = await krt.Notification.create(message);
      print("karte notification: $karteNotification");
      if (karteNotification != null) {
        karteNotification.handleForIOS();
      }
    });
    _firebaseMessaging
        .requestPermission(
            alert: true, badge: true, provisional: true, sound: true)
        .then((NotificationSettings value) {
      print("Settings registered: $value");
    });
    _firebaseMessaging.onTokenRefresh.listen((String token) {
      print("onTokenRefreshed: $token");
      krt.Notification.registerFCMToken(token);
      updateState(token: token);
    });
    _firebaseMessaging.getToken().then((String? token) {
      if (token == null) return;
      krt.Notification.registerFCMToken(token);
      updateState(token: token);
      print(_homeScreenText);
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('KARTE Notification example app'),
        ),
        body: Center(
          child: Column(
              // mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(_homeScreenText),
                ElevatedButton(
                  onPressed: () {
                    Tracker.view("push_text");
                  },
                  child: Text("View"),
                ),
                Text(_logText),
              ]),
        ),
      ),
    );
  }
} 

Download Details:

Author: plaidev

Source Code: https://github.com/plaidev/karte-flutter

#flutter #android #ios 

Flutter Plugin for KARTE Notification, Provides A Simple API

5 Useful Kotlin Extensions for Android Developers

What is a Kotlin Extension?

Kotlin provides the ability to extend a class or an interface with new functionality without having to inherit from the class or use design patterns such as Decorator. This is done via special declarations called extensions.

For example, you have used the String class mostly in your code. It may happen that you want some properties to be included in the String class , but they won’t. In this case, it is possible when using the Kotlin Extension method.

Suppose you want a String having one property to sort all the characters in the string alphabetically. Let’s make an Extension function for that.

fun String.sortAlphabetically() = toCharArray().apply { sort() }

I hope you get the idea of what exactly extensions' functions are and what they look like.

See more at: https://betterprogramming.pub/5-useful-kotlin-extensions-for-android-developers-485f7c9ad7e8

#kotlin #android #web-development 

5 Useful Kotlin Extensions for Android Developers
Hong  Nhung

Hong Nhung

1656684965

5 Tiện ích Mở Rộng Kotlin Hữu ích Cho Nhà Phát Triển Android

Phần mở rộng Kotlin là gì?

Kotlin cung cấp khả năng mở rộng một lớp hoặc một giao diện với chức năng mới mà không cần phải kế thừa từ lớp hoặc sử dụng các mẫu thiết kế như Decorator. Điều này được thực hiện thông qua các khai báo đặc biệt được gọi là phần mở rộng.

Ví dụ, bạn đã sử dụng Stringlớp chủ yếu trong mã của mình. Có thể xảy ra trường hợp bạn muốn một số thuộc tính được đưa vào String class, nhưng chúng sẽ không. Trong trường hợp này, có thể thực hiện được khi sử dụng phương pháp Mở rộng Kotlin.

Giả sử bạn muốn Stringcó một thuộc tính để sắp xếp tất cả các ký tự trong chuỗi theo thứ tự bảng chữ cái. Hãy tạo một Extensionhàm cho điều đó.

fun String.sortAlphabetically() = toCharArray().apply { sort() }

Tôi hy vọng bạn hiểu được các chức năng chính xác của tiện ích mở rộng là gì và chúng trông như thế nào.

1. EditText onChanged Text

Thay đổi văn bản chỉnh sửa là nhiệm vụ chính cần thực hiện trong ứng dụng di động. Kiểm tra xem văn bản nào đã được thay đổi. Một trường hợp sử dụng của EditText.onChangevăn bản là tìm kiếm thứ gì đó trong thanh tìm kiếm mà không cần nhấn nút chỉ khi có 3–4 ký tự ở đó bắt đầu tìm kiếm. Khi có thay đổi trong văn bản, hàm sẽ trả về văn bản đã thay đổi trong chuỗi.

fun EditText.onChange(textChanged: ((String) -> Unit)) {
    this.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {

        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            textChanged.invoke(s.toString())
        }
    })
}

2. Hiển thị bánh mì nướng

Với chức năng mở rộng này, bạn có thể gọi bánh mì nướng ở bất kỳ đâu trong Hoạt động hoặc Phân đoạn hoặc bất kỳ nơi nào bạn có thể vượt qua Context. Bạn chỉ cần gọi showToast(MESSAGE_YOU_WANT_TO_SHOW)và theo mặc định, thời lượng bánh mì nướng sẽ là Toast.LENGTH_SHORT.

fun Context.showToast(message: String?, length: Int = Toast.LENGTH_SHORT) {
    message?.let {
        Toast.makeText(this, it, length).show()
    }
}


//Usage
showToast("Hello World👋")

3. Hiển thị SnackBar

Snackbarđược sử dụng để hiển thị thông báo ngắn gọn ở cuối màn hình trên ứng dụng dành cho thiết bị di động của bạn. Đó là một loại thay thế cho bánh mì nướng. Trong SnackBar, bạn có thể có một nút hành động nếu có yêu cầu.

fun View.showSnackMessage(
    message: String?,
    anchorView: View? = null,
    backgroundColor: Int,
    textColor: Int,
    length: Int = Snackbar.LENGTH_SHORT
) {
    message?.let {
        try {
            val snack = Snackbar.make(this, it, length)
            snack.setBackgroundTint(ContextCompat.getColor(context, backgroundColor))
            snack.setTextColor(ContextCompat.getColor(context, textColor))
            snack.anchorView = anchorView
            snack.show()
        } catch (ex: Exception) {
            ex.showLog()
        }
    }
}

4. Kiểm tra xem Internet có khả dụng không

Trong khi thực hiện bất kỳ yêu cầu API nào như tải lên tệp hoặc nhận bất kỳ loại dữ liệu nào từ internet trong ứng dụng của chúng tôi, chúng tôi cần đảm bảo rằng Internet phải khả dụng. Nếu Internet không khả dụng, thì ứng dụng sẽ bị treo.

Giả sử trong một tình huống có nhiều hoạt động và phân đoạn trong dự án Android của bạn và bạn cần kiểm tra Internet có khả dụng ở nhiều thời điểm hay không, sau đó bạn cần gọi trình quản lý kết nối nhiều lần, vì có một chức năng mở rộng mà tôi sử dụng trong dự án của mình. .

Nó cũng sẽ giúp bạn.

fun Context.isNetworkAvailable(): Boolean {
    val manager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        val capabilities = manager.getNetworkCapabilities(manager.activeNetwork)
        if (capabilities != null) {
            if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                return true
            } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                return true
            } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
                return true
            }
        }
    } else {
        try {
            val activeNetworkInfo = manager.activeNetworkInfo
            if (activeNetworkInfo != null && activeNetworkInfo.isConnected) {
                return true
            }
        } catch (e: Exception) {
            e.showLog()
        }
    }
    return false
}


//Usage
//For example, In the MainActivity, how to call this?
if(isNetworkAvailable()){
  //Perform your task
}else{
   showToast("Internet is not available, Try Later")
}   
  

Phần mở rộng kiểm tra kết nối Internet

5. Kiểm soát khả năng hiển thị của VIEWS

Trong Android, khi chúng ta muốn hiển thị hoặc ẩn chế độ xem tùy theo dữ liệu mà chúng ta nhận được. Có một số trường hợp khi chúng tôi muốn ẩn khả năng hiển thị của bất kỳ chế độ xem cụ thể nào. Ví dụ: bằng cách sử dụng, ProgressBarchúng tôi muốn hiển thị thanh tiến trình chỉ khi một số dữ liệu đang trong quá trình lấy từ phần phụ trợ hoặc nguồn cục bộ. Khi dữ liệu được tìm nạp, chúng tôi chỉ muốn ẩn thanh tiến trình.

Thông lệ chung để thực hiện hành động này trong Android là binding.loadingProgressBar = View.GONEnó cần phải thực hiện mọi lúc. Bây giờ, chúng ta có thể chỉ cần tạo một hàm mở rộng với Viewlớp và nó sẽ đáp ứng nhu cầu của chúng ta.

fun View.show() {
    visibility = View.VISIBLE
}

fun View.hide() {
    visibility = View.GONE
}

fun View.invisible() {
    visibility = View.INVISIBLE
}

//Removing visibility of ProgressBar
//Using Extension
binding.loadingPb.hide()
//Without Extension
binding.loadingPb.visibility = View.GONE

Sự kết luận

Đó là tất cả! Tôi hy vọng bạn đã học được một cái gì đó. Trong trường hợp có bất kỳ nghi ngờ, chỉ cần bình luận! Tôi rất vui khi giải quyết các vấn đề của bạn.

Cảm ơn và chúc mừng!

Nguồn: https://betterprogramming.pub/5-useful-kotlin-extensions-for-android-developers-485f7c9ad7e8

#kotlin #android #web-development 

5 Tiện ích Mở Rộng Kotlin Hữu ích Cho Nhà Phát Triển Android
郝 玉华

郝 玉华

1656681242

5 个对 Android 开发者有用的 Kotlin 扩展

什么是 Kotlin 扩展?

Kotlin 提供了使用新功能扩展类或接口的能力,而无需从类继承或使用Decorator. 这是通过称为扩展的特殊声明完成的。

例如,您String主要在代码中使用了该类。您可能希望某些属性包含在 中String class,但它们不会。在这种情况下,可以使用 Kotlin 扩展方法。

假设您想要String一个属性来按字母顺序对字符串中的所有字符进行排序。让我们Extension为此创建一个函数。

fun String.sortAlphabetically() = toCharArray().apply { sort() }

我希望您了解扩展的功能到底是什么以及它们的外观。

1.EditText onChanged 文本

编辑文本更改是在移动应用程序中执行的一项关键任务。检查是否更改了哪些文本。文本的一个用例EditText.onChange是在搜索栏中搜索某些内容,而无需在 3-4 个字符开始搜索时按下按钮。当文本发生更改时,该函数将返回字符串中更改的文本。

fun EditText.onChange(textChanged: ((String) -> Unit)) {
    this.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {

        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            textChanged.invoke(s.toString())
        }
    })
}

2. 展示吐司

使用此扩展功能,您可以在活动或片段中的任何位置或您可以传递Context. 您只需拨打电话showToast(MESSAGE_YOU_WANT_TO_SHOW),默认情况下,吐司持续时间为Toast.LENGTH_SHORT.

fun Context.showToast(message: String?, length: Int = Toast.LENGTH_SHORT) {
    message?.let {
        Toast.makeText(this, it, length).show()
    }
}


//Usage
showToast("Hello World👋")

3. 显示 SnackBar

Snackbar用于在您的移动应用程序屏幕底部显示简短消息。它是吐司的一种替代品。在SnackBar中,如果有需要,您可能会有一个操作按钮。

fun View.showSnackMessage(
    message: String?,
    anchorView: View? = null,
    backgroundColor: Int,
    textColor: Int,
    length: Int = Snackbar.LENGTH_SHORT
) {
    message?.let {
        try {
            val snack = Snackbar.make(this, it, length)
            snack.setBackgroundTint(ContextCompat.getColor(context, backgroundColor))
            snack.setTextColor(ContextCompat.getColor(context, textColor))
            snack.anchorView = anchorView
            snack.show()
        } catch (ex: Exception) {
            ex.showLog()
        }
    }
}

4. 检查互联网是否可用

在我们的应用程序中发出任何 API 请求(例如上传文件或从 Internet 获取任何类型的数据)时,我们需要确保 Internet 必须可用。如果互联网不可用,则应用程序将崩溃。

假设在一种情况下,您的 Android 项目中有多个活动和片段,并且您需要检查互联网在很多时候是否可用,然后您需要多次调用连接管理器,因为我在项目中使用了一个扩展功能.

它也会帮助你。

fun Context.isNetworkAvailable(): Boolean {
    val manager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        val capabilities = manager.getNetworkCapabilities(manager.activeNetwork)
        if (capabilities != null) {
            if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                return true
            } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                return true
            } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
                return true
            }
        }
    } else {
        try {
            val activeNetworkInfo = manager.activeNetworkInfo
            if (activeNetworkInfo != null && activeNetworkInfo.isConnected) {
                return true
            }
        } catch (e: Exception) {
            e.showLog()
        }
    }
    return false
}


//Usage
//For example, In the MainActivity, how to call this?
if(isNetworkAvailable()){
  //Perform your task
}else{
   showToast("Internet is not available, Try Later")
}   
  

互联网连接检查扩展

5. 控制 VIEWS 的可见性

在Android中,当我们想根据我们得到的数据显示或隐藏视图时。在某些情况下,我们想要隐藏任何特定视图的可见性。例如,使用ProgressBar我们希望仅在某些数据正在从后端或本地源获取的过程中显示进度条。获取数据后,我们只想让进度条不可见。

在 Android 中执行此操作的一般做法是binding.loadingProgressBar = View.GONE,每次都需要执行。现在,我们可以简单地使用该类创建一个扩展函数View,它将满足我们的需求。

fun View.show() {
    visibility = View.VISIBLE
}

fun View.hide() {
    visibility = View.GONE
}

fun View.invisible() {
    visibility = View.INVISIBLE
}

//Removing visibility of ProgressBar
//Using Extension
binding.loadingPb.hide()
//Without Extension
binding.loadingPb.visibility = View.GONE

结论

就这样!我希望你学到了一些东西。如有任何疑问,请发表评论!我很乐意解决您的问题。

谢谢,欢呼!

来源:https ://betterprogramming.pub/5-useful-kotlin-extensions-for-android-developers-485f7c9ad7e8

#kotlin #android #web-development 

5 个对 Android 开发者有用的 Kotlin 扩展

5 Extensões Kotlin úteis Para Desenvolvedores android

O que é uma extensão Kotlin?

Kotlin fornece a capacidade de estender uma classe ou uma interface com novas funcionalidades sem ter que herdar da classe ou usar padrões de design como Decorator. Isso é feito por meio de declarações especiais chamadas extensões.

Por exemplo, você usou a Stringclasse principalmente em seu código. Pode acontecer que você queira que algumas propriedades sejam incluídas no String class, mas elas não serão. Nesse caso, é possível ao usar o método Kotlin Extension.

Suponha que você queira Stringter uma propriedade para classificar todos os caracteres na string em ordem alfabética. Vamos fazer uma Extensionfunção para isso.

fun String.sortAlphabetically() = toCharArray().apply { sort() }

Espero que você tenha uma ideia de quais são exatamente as funções das extensões e como elas se parecem.

1. Editar texto em texto alterado

Uma alteração de texto de edição é uma tarefa importante a ser executada no aplicativo móvel. Verificando se o texto foi alterado. Um caso de uso de EditText.onChangetexto é pesquisar algo na barra de pesquisa, sem pressionar um botão apenas quando 3 a 4 caracteres estiverem lá, comece a pesquisar. Quando houver uma alteração no texto, a função retornará o texto alterado na string.

fun EditText.onChange(textChanged: ((String) -> Unit)) {
    this.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {

        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            textChanged.invoke(s.toString())
        }
    })
}

2. Mostrar brinde

Com esta função de extensão, você pode chamar o toast em qualquer lugar em Atividades ou Fragmento ou em qualquer lugar em que possa passar o arquivo Context. Você só precisa chamar showToast(MESSAGE_YOU_WANT_TO_SHOW)e, por padrão, a duração do brinde será Toast.LENGTH_SHORT.

fun Context.showToast(message: String?, length: Int = Toast.LENGTH_SHORT) {
    message?.let {
        Toast.makeText(this, it, length).show()
    }
}


//Usage
showToast("Hello World👋")

3. Mostrar SnackBar

Snackbaré usado para mostrar a breve mensagem na parte inferior da tela em seu aplicativo móvel. É uma espécie de substituto para torradas. Em SnackBar, você pode ter um botão de ação se houver um requisito.

fun View.showSnackMessage(
    message: String?,
    anchorView: View? = null,
    backgroundColor: Int,
    textColor: Int,
    length: Int = Snackbar.LENGTH_SHORT
) {
    message?.let {
        try {
            val snack = Snackbar.make(this, it, length)
            snack.setBackgroundTint(ContextCompat.getColor(context, backgroundColor))
            snack.setTextColor(ContextCompat.getColor(context, textColor))
            snack.anchorView = anchorView
            snack.show()
        } catch (ex: Exception) {
            ex.showLog()
        }
    }
}

4. Verifique se a Internet está disponível

Ao fazer qualquer solicitação de API, como fazer upload de um arquivo ou obter qualquer tipo de dados da Internet em nosso aplicativo, precisamos garantir que a Internet esteja disponível. Se a internet não estiver disponível, o aplicativo travará.

Suponha que em um cenário existem várias atividades e fragmentos em seu projeto Android e você precisa verificar se a internet está disponível em muitos pontos, então você precisa chamar o gerenciador de conectividade várias vezes, para isso existe uma função de extensão que eu uso no meu projeto .

Vai te ajudar também.

fun Context.isNetworkAvailable(): Boolean {
    val manager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        val capabilities = manager.getNetworkCapabilities(manager.activeNetwork)
        if (capabilities != null) {
            if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                return true
            } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                return true
            } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
                return true
            }
        }
    } else {
        try {
            val activeNetworkInfo = manager.activeNetworkInfo
            if (activeNetworkInfo != null && activeNetworkInfo.isConnected) {
                return true
            }
        } catch (e: Exception) {
            e.showLog()
        }
    }
    return false
}


//Usage
//For example, In the MainActivity, how to call this?
if(isNetworkAvailable()){
  //Perform your task
}else{
   showToast("Internet is not available, Try Later")
}   
  

Extensão de verificação de conectividade com a Internet

5. Controlar a visibilidade das VISUALIZAÇÕES

No Android, quando queremos mostrar ou ocultar a visualização de acordo com os dados que obtemos. Existem algumas circunstâncias em que queremos ocultar a visibilidade de qualquer visualização específica. Por exemplo, usando ProgressBarqueremos mostrar a barra de progresso apenas quando alguns dados estão em processo de obtenção do back-end ou fonte local. Uma vez que os dados são buscados, queremos apenas tornar a barra de progresso invisível.

A prática geral para executar essa ação no Android é binding.loadingProgressBar = View.GONE, ela precisa ser executada sempre. Agora, podemos simplesmente criar uma função de extensão com a Viewclasse e ela atenderá às nossas necessidades.

fun View.show() {
    visibility = View.VISIBLE
}

fun View.hide() {
    visibility = View.GONE
}

fun View.invisible() {
    visibility = View.INVISIBLE
}

//Removing visibility of ProgressBar
//Using Extension
binding.loadingPb.hide()
//Without Extension
binding.loadingPb.visibility = View.GONE

Conclusão

Isso é tudo! Espero que você tenha aprendido alguma coisa. Qualquer dúvida é só comentar! Ficarei feliz em resolver seus problemas.

Obrigado, e aplausos!

Fonte: https://betterprogramming.pub/5-useful-kotlin-extensions-for-android-developers-485f7c9ad7e8

#kotlin #android #web-development 

5 Extensões Kotlin úteis Para Desenvolvedores android

5 Extensiones útiles De Kotlin Para Desarrolladores De Android

¿Qué es una extensión de Kotlin?

Kotlin brinda la capacidad de extender una clase o una interfaz con nueva funcionalidad sin tener que heredar de la clase o usar patrones de diseño como Decorator. Esto se hace a través de declaraciones especiales llamadas extensiones.

Por ejemplo, ha usado la Stringclase principalmente en su código. Puede suceder que desee que se incluyan algunas propiedades en el String class, pero no lo harán. En este caso, es posible al usar el método Kotlin Extension.

Suponga que desea Stringtener una propiedad para ordenar alfabéticamente todos los caracteres de la cadena. Hagamos una Extensionfunción para eso.

fun String.sortAlphabetically() = toCharArray().apply { sort() }

Espero que tengas una idea de cuáles son exactamente las funciones de las extensiones y cómo se ven.

1. EditText onChangeText

Un cambio de texto de edición es una tarea clave para realizar en la aplicación móvil. Comprobando si se ha cambiado qué texto. Un caso de uso de EditText.onChangetexto es buscar algo en la barra de búsqueda, sin presionar un botón, justo cuando hay 3 o 4 caracteres que comienzan a buscar. Cuando haya un cambio en el texto, la función devolverá el texto modificado en la cadena.

fun EditText.onChange(textChanged: ((String) -> Unit)) {    this.addTextChangedListener(object : TextWatcher {        override fun afterTextChanged(s: Editable?) {        }        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {            textChanged.invoke(s.toString())        }    })}

2. Mostrar tostadas

Con esta función de extensión, puede llamar al brindis en cualquier lugar, ya sea en Actividades o Fragmento, o en cualquier lugar donde pueda pasar el archivo Context. Solo necesita llamar showToast(MESSAGE_YOU_WANT_TO_SHOW)y, de forma predeterminada, la duración del brindis será Toast.LENGTH_SHORT.

fun Context.showToast(message: String?, length: Int = Toast.LENGTH_SHORT) {    message?.let {        Toast.makeText(this, it, length).show()    }}//UsageshowToast("Hello World👋")

3. Mostrar SnackBar

Snackbarse utiliza para mostrar el breve mensaje en la parte inferior de la pantalla de su aplicación móvil. Es una especie de sustituto de las tostadas. En SnackBar, puede tener un botón de acción si hay un requisito.

fun View.showSnackMessage(    message: String?,    anchorView: View? = null,    backgroundColor: Int,    textColor: Int,    length: Int = Snackbar.LENGTH_SHORT) {    message?.let {        try {            val snack = Snackbar.make(this, it, length)            snack.setBackgroundTint(ContextCompat.getColor(context, backgroundColor))            snack.setTextColor(ContextCompat.getColor(context, textColor))            snack.anchorView = anchorView            snack.show()        } catch (ex: Exception) {            ex.showLog()        }    }}

4. Compruebe si Internet está disponible

Al realizar cualquier solicitud de API, como cargar un archivo u obtener cualquier tipo de datos de Internet en nuestra aplicación, debemos asegurarnos de que Internet debe estar disponible. Si Internet no está disponible, la aplicación se bloqueará.

Supongamos que en un escenario hay múltiples actividades y fragmentos en su proyecto de Android y necesita verificar que Internet esté disponible en muchos puntos, luego debe llamar al administrador de conectividad varias veces, para eso hay una función de extensión que uso en mi proyecto .

También te ayudará.

fun Context.isNetworkAvailable(): Boolean {    val manager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {        val capabilities = manager.getNetworkCapabilities(manager.activeNetwork)        if (capabilities != null) {            if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {                return true            } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {                return true            } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {                return true            }        }    } else {        try {            val activeNetworkInfo = manager.activeNetworkInfo            if (activeNetworkInfo != null && activeNetworkInfo.isConnected) {                return true            }        } catch (e: Exception) {            e.showLog()        }    }    return false}//Usage//For example, In the MainActivity, how to call this?if(isNetworkAvailable()){  //Perform your task}else{   showToast("Internet is not available, Try Later")}     

Extensión de verificación de conectividad a Internet

5. Controlar la visibilidad de las VISTAS

En Android, cuando queremos mostrar u ocultar la vista según los datos que obtengamos. Hay algunas circunstancias en las que queremos ocultar la visibilidad de una vista específica. Por ejemplo, ProgressBarqueremos mostrar la barra de progreso solo cuando algunos datos están en proceso de obtenerse del backend o fuente local. Una vez que se obtienen los datos, solo queremos que la barra de progreso sea invisible.

La práctica general para realizar esta acción en Android es binding.loadingProgressBar = View.GONEque debe realizarse cada vez. Ahora, simplemente podemos crear una función de extensión con la Viewclase y satisfará nuestras necesidades.

fun View.show() {    visibility = View.VISIBLE}fun View.hide() {    visibility = View.GONE}fun View.invisible() {    visibility = View.INVISIBLE}//Removing visibility of ProgressBar//Using Extensionbinding.loadingPb.hide()//Without Extensionbinding.loadingPb.visibility = View.GONE

Conclusión

¡Eso es todo! Espero que hayas aprendido algo. Ante cualquier duda, ¡comenta! Estaré feliz de resolver sus problemas.

¡Gracias y ánimo!

Fuente: https://betterprogramming.pub/5-useful-kotlin-extensions-for-android-developers-485f7c9ad7e8

#kotlin #android #web-development 

5 Extensiones útiles De Kotlin Para Desarrolladores De Android
Thierry  Perret

Thierry Perret

1656677289

5 Extensions Kotlin Utiles Pour Les Développeurs Android

Qu'est-ce qu'une extension Kotlin ?

Kotlin offre la possibilité d'étendre une classe ou une interface avec de nouvelles fonctionnalités sans avoir à hériter de la classe ou à utiliser des modèles de conception tels que Decorator. Cela se fait via des déclarations spéciales appelées extensions.

Par exemple, vous avez utilisé la Stringclasse principalement dans votre code. Il peut arriver que vous vouliez que certaines propriétés soient incluses dans le String class, mais elles ne le seront pas. Dans ce cas, c'est possible en utilisant la méthode d'extension Kotlin.

Supposons que vous souhaitiez Stringavoir une propriété pour trier tous les caractères de la chaîne par ordre alphabétique. Créons une Extensionfonction pour cela.

fun String.sortAlphabetically() = toCharArray().apply { sort() }

J'espère que vous avez une idée de ce que sont exactement les fonctions des extensions et à quoi elles ressemblent.

1. EditText onChanged Text

Un changement de texte d'édition est une tâche clé à effectuer dans l'application mobile. Vérifier si quel texte a été modifié. Un cas d'utilisation du EditText.onChangetexte consiste à rechercher quelque chose dans la barre de recherche, sans appuyer sur un bouton juste au moment où 3 à 4 caractères sont là pour commencer la recherche. Lorsqu'il y aura un changement dans le texte, la fonction renverra le texte modifié dans la chaîne.

fun EditText.onChange(textChanged: ((String) -> Unit)) {
    this.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {

        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            textChanged.invoke(s.toString())
        }
    })
}

2. Afficher le toast

Avec cette fonction d'extension, vous pouvez appeler toast n'importe où dans Activités ou Fragment ou n'importe où vous pouvez passer le Context. Il vous suffit d'appeler showToast(MESSAGE_YOU_WANT_TO_SHOW)et par défaut, la durée du toast sera de Toast.LENGTH_SHORT.

fun Context.showToast(message: String?, length: Int = Toast.LENGTH_SHORT) {
    message?.let {
        Toast.makeText(this, it, length).show()
    }
}


//Usage
showToast("Hello World👋")

3. Afficher SnackBar

Snackbarest utilisé pour afficher le bref message en bas de l'écran de votre application mobile. C'est une sorte de substitut aux toasts. Dans SnackBar, vous pouvez avoir un bouton d'action s'il y a une exigence.

fun View.showSnackMessage(
    message: String?,
    anchorView: View? = null,
    backgroundColor: Int,
    textColor: Int,
    length: Int = Snackbar.LENGTH_SHORT
) {
    message?.let {
        try {
            val snack = Snackbar.make(this, it, length)
            snack.setBackgroundTint(ContextCompat.getColor(context, backgroundColor))
            snack.setTextColor(ContextCompat.getColor(context, textColor))
            snack.anchorView = anchorView
            snack.show()
        } catch (ex: Exception) {
            ex.showLog()
        }
    }
}

4. Vérifiez si Internet est disponible

Lors de toute demande d'API, comme le téléchargement d'un fichier ou l'obtention de tout type de données d'Internet dans notre application, nous devons nous assurer qu'Internet doit être disponible. Si Internet n'est pas disponible, l'application plantera.

Supposons que dans un scénario, il y ait plusieurs activités et fragments dans votre projet Android et que vous deviez vérifier qu'Internet est disponible à de nombreux points, puis vous devez appeler le gestionnaire de connectivité plusieurs fois, pour cela il y a une fonction d'extension que j'utilise dans mon projet .

Cela vous aidera aussi.

fun Context.isNetworkAvailable(): Boolean {
    val manager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        val capabilities = manager.getNetworkCapabilities(manager.activeNetwork)
        if (capabilities != null) {
            if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                return true
            } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                return true
            } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
                return true
            }
        }
    } else {
        try {
            val activeNetworkInfo = manager.activeNetworkInfo
            if (activeNetworkInfo != null && activeNetworkInfo.isConnected) {
                return true
            }
        } catch (e: Exception) {
            e.showLog()
        }
    }
    return false
}


//Usage
//For example, In the MainActivity, how to call this?
if(isNetworkAvailable()){
  //Perform your task
}else{
   showToast("Internet is not available, Try Later")
}   
  

Extension de vérification de la connectivité Internet

5. Contrôler la visibilité des VUES

Dans Android, lorsque nous voulons afficher ou masquer la vue en fonction des données que nous obtenons. Dans certaines circonstances, nous souhaitons masquer la visibilité d'une vue spécifique. Par exemple, en utilisant, ProgressBarnous souhaitons afficher la barre de progression uniquement lorsque certaines données sont en cours d'obtention depuis le backend ou la source locale. Une fois les données récupérées, nous voulons simplement rendre la barre de progression invisible.

La pratique générale pour effectuer cette action dans Android est binding.loadingProgressBar = View.GONEqu'elle doit être exécutée à chaque fois. Maintenant, nous pouvons simplement créer une fonction d'extension avec la Viewclasse, et elle répondra à nos besoins.

fun View.show() {
    visibility = View.VISIBLE
}

fun View.hide() {
    visibility = View.GONE
}

fun View.invisible() {
    visibility = View.INVISIBLE
}

//Removing visibility of ProgressBar
//Using Extension
binding.loadingPb.hide()
//Without Extension
binding.loadingPb.visibility = View.GONE

Conclusion

C'est tout! J'espère que vous avez appris quelque chose. En cas de doute, il suffit de commenter ! Je serai heureux de résoudre vos problèmes.

Merci et bravo !

Source : https://betterprogramming.pub/5-useful-kotlin-extensions-for-android-developers-485f7c9ad7e8

#kotlin #android #web-development 

5 Extensions Kotlin Utiles Pour Les Développeurs Android

A Flutter Package for Getting Better Feedback

feedback_sentry

Getting Started

Follow the setup instructions of sentry_flutter.

Then, you will need to add feedback_sentry to your pubspec.yaml. The latest version is .

dependencies:
  feedback_sentry: x.y.z # use the latest version found on pub.dev

Then, run flutter pub get in your terminal.

Use it

Just wrap your app in a BetterFeedback widget. To show the feedback view just call BetterFeedback.of(context).show(...);. The callback gets called when the user submits his feedback.

import 'package:feedback/feedback.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(
    BetterFeedback(
      child: const MyApp(),
    ),
  );
}

Provide a way to show the feedback panel by calling

import 'package:feedback_sentry/feedback_sentry.dart';

BetterFeedback.of(context).showAndUploadToSentry(
    name: 'Foo Bar', // optional
    email: 'foo_bar@example.com', // optional
);

Provide a way to hide the feedback panel by calling BetterFeedback.of(context).hide();

📣 Author

Issues, questions and contributing

You can raise issues here. If you've got a question do not hesitate to ask it here. Contributions are also welcome. You can do a pull request on GitHub here. Please take a look at up for grabs issues first.

Sponsoring

I'm working on my packages on my free-time, but I don't have as much time as I would. If this package or any other package I created is helping you, please consider to sponsor me. By doing so, I will prioritize your issues or your pull-requests before the others.

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add feedback_sentry

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  feedback_sentry: ^2.3.0

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:feedback_sentry/feedback_sentry.dart'; 

Download Details:

Author: ueman

Source Code: https://github.com/ueman/feedback

#flutter #android #ios 

A Flutter Package for Getting Better Feedback
Hunter  Krajcik

Hunter Krajcik

1656601280

Contentsquare: Contentsquare Flutter Plugin

A plugin to use Contensquare in Flutter apps.

This plugin supports Android and iOS.

Features

Use this plugin in your Flutter app to:

  • Manage opt-in and opt-out of analytic.
  • Track screenviews and transactions.

Installing

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add contentsquare

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  contentsquare: ^0.5.1

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:contentsquare/contentsquare.dart';

example/README.md

Contentsquare Flutter plugin Examples

2 examples are available to showcase the usage and features of the Contentsquare flutter plugin:

  • simple_app: a simple app example with buttons for each API feature
  • flutter_gallery: a more complex app example (extract from flutter/gallery) to showcase example of the zoning features on a large code base application

Getting started

This plugin relies on the Contentsquare native SDKs to log events. It exposes a unified surface, but you can consult each SDK documentation for more in-depth information :

iOS

To ensure the best experience, you should target 10+ iOS version. In Podfile add this line at the top of the file:

platform :ios, '10.0'

Android

The plugin works out of the box.

Usage

To learn how to use this plugin, see the documentation

Original article source at: https://pub.dev/packages/contentsquare 

#flutter #dart #ios #android 

Contentsquare: Contentsquare Flutter Plugin

A Simple Variable Accessor with Flutter

Accessor

A simple variable accessor.

Documentation #

Defining variable is like

    Accessor<int>().data = 5;

Also you can access the variable with same method

    Accessor<int>().data;

If you want to define same type more then once you must use "key" parameter

    Accessor<int>(key: "number").data = 3;

You can listen variable

    Accessor<int>().listen((data) => print(data.toString()));

Note: Listen function triggered when value is changed or removed.

This project is a starting point for a Dart package, a library module containing code that can be shared easily across multiple Flutter or Dart projects.

For help getting started with Flutter, view our online documentation, which offers tutorials, samples, guidance on mobile development, and a full API reference.

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add accessor

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  accessor: ^1.0.2

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:accessor/accessor.dart'; 

Download Details:

Author: onurmio

Source Code: https://github.com/onurmio/Accessor

#flutter #android 

A Simple Variable Accessor with Flutter

A Declarative Library with an Easy-to-use interface for Build Flutter

amplify_auth_cognito_ios

The method channel implementation for amplify_auth_cognito on iOS

Usage

This package is an endorsed plugin of amplify_auth_cognito and will be included as a transitive dependency. It does not need to be imported manually

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add amplify_auth_cognito_ios

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  amplify_auth_cognito_ios: ^0.6.0

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more. 

example/lib/main.dart

/*
 * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  http://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: const Center(
          child: Text(
              'This application serves as a test bed for the iOS implementation of the amplify_auth_cognito method channel. Please see the example app in the main amplify_api repository for a functional example app.'),
        ),
      ),
    );
  }
} 

Download Details:

Author: aws-amplify

Source Code: https://github.com/aws-amplify/amplify-flutter

#flutter #android #ios 

A Declarative Library with an Easy-to-use interface for Build Flutter