Uri and uri kotlin

Android KTX

Kotlin упростил написание кода по сравнению с Java, но нет предела совершенству. Благодаря гибкости Kotlin можно создавать расширения к существующим классам и сделать код ещё проще. Чтобы не изобретать велосипед каждый раз, наиболее удачные примеры решили выделить в отдельную группу, которая получила название Android KTX.

Подключаем библиотеку (один из вариантов).

 // добавьте в секцию android kotlinOptions < jvmTarget = JavaVersion.VERSION_1_8.toString() >// для секции dependencies implementation 'androidx.core:core-ktx:1.2.0' //fragment implementation 'androidx.fragment:fragment-ktx:' // pallete implementation 'androidx.pallete:palette-ktx:' //SQLite implementation 'androidx.sqlite:sqlite-ktx:' // collections implementation 'androidx.collection:collection-ktx:' 

Примеры

Несколько примеров для знакомства.

Uri

Если у вас есть строка, которую нужно перевести в Uri, то писали следующую конструкцию.

 val uriString = "http://developer.alexanderklimov.ru/android" val uriOld = Uri.parse(uriString) Log.d("KTX", uri.host) 

Теперь можно писать проще. Код стал читаемым.

 val uriString = "http://developer.alexanderklimov.ru/android" val uri = uriString.toUri() Log.d("KTX", uri.host) 

SharedPreferences

При работе с файлами настройки приходится писать однотипный код.

 sharedPreferences.edit() .putBoolean(key, value) .apply() 

Сокращаем код. Разница не слишком большая, но выглядит опрятнее.

Bitmap/Drawable

 // get a drawable from resources va myDrawable = ContextCompat.getDrawable(context, R.drawable.cat) // convert the drawable to a bitmap val bitmap = myDrawable.toBitmap() 

Масштабируем Bitmap с помощью scale()

Удобная функция scale() поможет изменить размеры картинки.

 // get bitmap from drawable resource val bitmap = BitmapFactory.decodeResource(resources,R.drawable.table_cat) // scale bitmap using android ktx val scaledBitmap = bitmap.scale( 300, // width 300, // height false // filter ) button.setOnClickListener

View.drawToBitmap

Конвертирует компонент в изображение. Создадим карточку CardView и созданное изображение карточки поместим в ImageView.

 package ru.alexanderklimov.ktx import android.graphics.Bitmap import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.core.view.drawToBitmap import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() < override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) button.setOnClickListener < // draw a bitmap from cardView val bitmap: Bitmap = cardView.drawToBitmap(Bitmap.Config.ARGB_8888) // show to generated bitmap to imageView imageView.setImageBitmap(bitmap) >> > 

Span

 val string = buildSpannedString < append("no styling text") bold < append("bold") italic < append("bold and italic) >> inSpans(RelativeSizeSpan(2f), QuoteSpan()) < append("double sized quote text") >> 

Bundle

 val bundle = bundleOf( "KEY_INT" to 1, "KEY_LONG" to 2L, "KEY_BOOLEAN" to true, "KEY_NULL" to null, "KEY_ARRAY" to arrayOf(1, 2, 3) ) 

Обратите внимание, что в примерах используется пакет androidx, это позволит не путать их с стандартными пакетами android.

Другие примеры из разных источников.

 //default usage supportFragmentManager .beginTransaction() .replace( R.id.my_fragment_container, myFragment, FRAGMENT_TAG ) .commitAllowingStateLoss() // using androidx.fragment:fragment-ktx supportFragmentManager.transaction( allowStateLosss = true ) < replace( R.id.my_fragment_container, myFragment, FRAGMENT_TAG) >// using androidx.core:core-ktx val s = "Hello, Spans!".toSpannable() val bold = StyleSpan(BOLD) s += bolds[7..12] = ForegroundColorSpan(Color.RED) // using androidx.core:core-ktx menu.forEach < // do action >// check if an itme is in the menu and remove it if(menuItem in menu) menu -= menuItem // default usage db.beginTransaction() try < // insert data db.setTransactionSuccessful() >finally < db.endTransaction() >// using androidx.sqlite:sqlite-ktx db.transaction < // insert data >

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A Kotlin Multiplatform Utility Library for Uniform Resource Identifiers (URIs)

License

chRyNaN/uri

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

A Kotlin Multi-platform Utility Library for Uniform Resource Identifiers (URIs).

Uri.fromString("https://john.doe@www.example.com:123/forum/questions/?tag=networking&order=newest#top")
Uri.fromParts( scheme = "https", fragment = "top", path = "/forum/questions/", query = "tag=networking&order=newest", userInfo = "john.doe", host = "www.example.com", port = 123 )

If an error is encountered with the Uri.fromParts function, then an exception is thrown. Instead of throwing an exception, null can be returned, using the Uri.fromPartsOrNull function.

Uri.fromPartsOrNull( scheme = "https", fragment = "top", path = "/forum/questions/", query = "tag=networking&order=newest", userInfo = "john.doe", host = "www.example.com", port = 123 )

Creating a Uri from a String:

This library has a typealias, UriString , which is just a String . A UriString can be parsed and turned into a Uri .

Uri.fromString(uriString = "https://john.doe@www.example.com:123/forum/questions/?tag=networking&order=newest#top")

Creating an optional Uri from a String:

If an error is encountered with the Uri.fromString function, then an exception is thrown. Instead of throwing an exception, null can be returned, using the Uri.fromStringOrNull function.

Uri.fromStringOrNull(uriString = "https://john.doe@www.example.com:123/forum/questions/?tag=networking&order=newest#top")

The library is provided through Repsy.io. Refer to the releases page for the latest version.

repositories < maven < url = "https://repo.repsy.io/mvn/chrynan/public" > >
implementation("com.chrynan.uri:uri-core:$VERSION")
implementation("com.chrynan.uri:uri-ktor-client:$VERSION")

More detailed documentation is available in the docs folder. The entry point to the documentation can be found here.

Copyright 2021 chRyNaN Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License 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. 

About

A Kotlin Multiplatform Utility Library for Uniform Resource Identifiers (URIs)

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Kotlin URI/URL and Path parsing library

License

oxgl/urilib

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Path and URI (URL) parsing library for Kotlin by Oxyggen.

The path parsing part is (probably) finished. To create a Path object call the Path.parse method:

val p = Path.parse("/first/second/third/../fourth/") 

You can set an optional parameter pathSeparator . The default value is «/» (Linux, URL, etc. ). Set value «\\» if you want to parse Windows style paths:

val w = Path.parse("C:\\temp\\abc.txt", pathSeparator = "\\") 

Because it is designed to parse URL paths few simple few simple rules were introduced:

  1. directory is the substring before last separator and file is the substring after last separator
  2. path «» is the same as «/»
  3. file name and extension separator is «.»

I had to introduce rules 1) and 3) because these are not real or local paths, so it’s not possible to check whether given path points to a file or a directory. Always add a separator at the end, if the path points to directory! So /dev/etc/ is directory but /dev/etc is file.

val p = Path.parse("/first/second/third/../fourth/myfile.html") 
property value
p.complete «/first/second/third/../fourth/myfile.html»
p.file «myfile.html»
p.fileName «myfile»
p.fileExtension «html»
p.directory «/first/second/third/../fourth/»

Let’s normalize this path and check the values:

property value
n.complete «/first/second/fourth/myfile.html»
n.file «myfile.html»
n.fileName «myfile»
n.fileExtension «html»
n.directory «/first/second/fourth/»

Normalized path is a subclass of Path , so it’s easy to check whether path object is normalized:

This does not mean that Path object can’t contain normalized path, but you can be sure that NormalizedPath object must contain normalized path.

You can also resolve relative paths. Let’s create relative r path and resolve it to absolute a using the original path p . Check also the normalized values from a ( a.normalized ):

val r = Path.parse("../anotherfile.html") val a = p.resolve(r) 
property a.(property) a.normalized.(property)
complete «/first/second/third/../fourth/../anotherfile.php» «/first/second/anotherfile.php»
file «anotherfile.php» «anotherfile.php»
fileName «anotherfile» «anotherfile»
fileExtension «php» «php»
directory «/first/second/third/../fourth/../» «/first/second/»

Library was primarily created for c4k web crawling framework, but it’s a standalone library. To parse URI and create URI object call method:

 val u = URI.parse("http://test.com") 

This is the type hierarchy:

 URI ├── UnresolvedURI (partial URI -> no scheme specified) └── ResolvedURI (complete URI -> scheme & scheme specific part specified) ├── MailtoURI (implemented, but not complete) └── ContextURI └── URL └── CommonURL ├── HttpURL └── FtpURL (not yet implemented) 

As you can see the URI has 2 subclasses: UnresolvedURI and ResolvedURI. The UnresolvedURI is a relative URI, which is not complete. It can be resolved in a context, so each subclass of the class ContextURI implements a method parse. Using this method you can convert an UnresolvedURI to ResolvedURI (the runtime class will be for example HttpURL).

After parsing you can test the uri type:

 val u = URI.parse("http://test.com") if (u is HttpURL)

There are few methods to convert URI to string (depends on class hierarchy):

toString() -> returns object info: Object@xxx (Uri) toUriString() -> returns the original URI (in case of relative URI: ./index.html) toResolvedUriString() -> returns resolved URI (./index.html in context test.com is test.com/index.html) toNormalizedUriString() -> returns normalized, resolved URI string 

Источник

Читайте также:  Java копирование массива строк
Оцените статью