Android: Butterknife bilan Kotlin

Men Android ilovasi uchun Butterknife bilan Kotlindan foydalanishga harakat qilaman.

Mana mening build.gradle

dependencies {
    ...
    compile 'com.jakewharton:butterknife:8.0.1'
    kapt 'com.jakewharton:butterknife-compiler:8.0.1'
}

kapt {
    generateStubs = true
}

Menda ham EditText bor va o'zgartirilganda ButterKnife-dan foydalanib xabarni ko'rsatishni istayman:

@OnTextChanged(R.id.input)
fun test() {
   toast(1)
}

Biroq, hech narsa sodir bo'lmaydi. Funktsiyaga nuqta qo'ydim - bu hatto bajarilmaydi.

PS: Men kotterknife haqida eshitganman, lekin men misol sof Butterknife bilan.

Men noto'g'ri ish qilyapman?

27
qo'shib qo'ydi muallif pRaNaY, manba
@pRaNaY savolni o'qidingizmi? Mening kodimda aynan shuni qildim
qo'shib qo'ydi muallif Rahul Katrakhtalapali, manba
@JanSlominski, OP faqatgina Kotlin dasturini qayta yozishni istamasa, Java bilan birga ishlash kerak
qo'shib qo'ydi muallif StuStirling, manba
@JanSlominski Bizga nima uchun anko bilan biz ko'proq kalamushka kerak emasligini tushuntira olasizmi?
qo'shib qo'ydi muallif Pablo Cegarra, manba
Men bu to'g'ridan-to'g'ri javob emasligini bilaman, lekin Kotlin, Anko va Kotlin Android kengaytmalari bilan ButterKnife uchun foydalanishni ko'rmayapman.
qo'shib qo'ydi muallif Jan Slominski, manba
ButterKnife.bind (bu) deb ataganmisiz?
qo'shib qo'ydi muallif Maksim Ostrovidov, manba
yaxshiroq Kotlin kengaytmasi plaginidan foydalanishingiz mumkin youtube.com/watch?v=AvMbTY6Vruk
qo'shib qo'ydi muallif Lovekush Vishwakarma, manba

9 javoblar

Kotlinda butterfaxaga ehtiyoj yo'q. Quyidagilarni bevosita ishlatishingiz mumkin:

// app: build.gradle fayli

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.example.nikhiljadhav.myapplication"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:26.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:design:26.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.0'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.0'
}

kapt {
    generateStubs = true
}

// xml layout fayli






// MainActivity.kt fayli

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)

       //use the kotlin property
        tvHello.text="Hi bla bla"
        tvId.text="buubububub"
        //set textcolor  
        tvId.setTextColor(ContextCompat.getColor(this, R.color.colorAccent)) 
        etDemo.hint="nhdodfhfgf"

        tvId.setOnClickListener{ view->
            onClick(view)
        }

        fab.setOnClickListener { view ->
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show()
        }
    }

    fun onClick(view: View) {
        Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show()
    }

    ...
}

OnTextChangeListner uchun:

etText.addTextChangedListener(object : TextWatcher{
        override fun afterTextChanged(p0: Editable?) {
            TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        }

        override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        }

        override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        }

    }) 
52
qo'shib qo'ydi
Ajoyib! Men kotlinni yaxshiroq olishi mumkin deb o'ylamagan edim!
qo'shib qo'ydi muallif just_user, manba
Qanday string, ranglar, registrlarni bog'lash haqida?
qo'shib qo'ydi muallif Michael, manba
Yaxshi misol, rahmat!
qo'shib qo'ydi muallif Dan Loewenherz, manba
Qoyil! Kotlin nafaqat go'zal va oqlangan. Shveytsariyalik haqiqiy pichoq.
qo'shib qo'ydi muallif Rowland Mtetezi, manba
onViewCreated dan qo'ng'iroq qilishingiz kerak bo'lgan parchadan eslatma: antonioleiva.com/kotlin- android-kengaytmalari
qo'shib qo'ydi muallif hmac, manba
Bu juda ajoyib. Siz kabi xml faylini import qilishingiz kerak o'xshaydi: import kotlinx.android.synthetic.main.activity_main. *
qo'shib qo'ydi muallif Ethan_AI, manba
shuning uchun @OnTextChanged-ni Kotlin Extensions bilan qanday foydalanasiz?
qo'shib qo'ydi muallif kike, manba
Men javobni yangiladim, iltimos tekshiring.
qo'shib qo'ydi muallif Nikhil Jadhav, manba
Rahmat rowland-mtetezi.
qo'shib qo'ydi muallif Nikhil Jadhav, manba
Men javobni yangiladim, iltimos tekshiring
qo'shib qo'ydi muallif Nikhil Jadhav, manba
Rahmat, Dan Loewenherz
qo'shib qo'ydi muallif Nikhil Jadhav, manba

In your app level build.gradle

apply plugin: 'kotlin-android'

kapt {
    generateStubs = true
}

dependencies {
    compile 'com.jakewharton:butterknife:8.4.0'
    kapt 'com.jakewharton:butterknife-compiler:8.4.0'
}

Yuqori darajadagi build.gradle ilovasida

buildscript {
    ext.kotlin_version = '1.1.3'
    repositories {
        jcenter()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

Faoliyat

@BindView(R.id.toolbar)  @JvmField var toolbar: Toolbar? = null

yoki

@BindView(R.id.toolbar) lateinit var toolbar: Toolbar

Inside OnCreate

ButterKnife.bind(this)
21
qo'shib qo'ydi

Gradle ichida:

compile 'com.jakewharton:butterknife:8.8.0'
kapt "com.jakewharton:butterknife-compiler:8.8.0"

Faoliyatingizda

@BindView(R.id.toolbar)
lateinit var mToolbar: Toolbar

Of course, remember ButterKnife.bind(this) and apply the plugin on the top of your app.gradle apply plugin: 'kotlin-kapt'

To'liq namunani tekshiring

Full Link: https://github.com/JetBrains/kotlin-examples/tree/master/gradle/android-butterknife

8
qo'shib qo'ydi

Kotlin ijodkorlari o'z saytida shunday deyishadi: Kotlin Android Extensions plaginini (Android Studio'da Kotlin plaginiga avtomatik ravishda ulangan) bir xil muammolarni echishda foydalanadi: r findViewById ni ixcham va soddalashtirilgan kod bilan joylashtirish. Agar siz allaqachon ButterKnife-ni ishlatmaysiz va ko'chirmoqchi bo'lsangiz, uni ishlatib ko'ring. .

va, masalan,

// Using R.layout.activity_main from the main source set
import kotlinx.android.synthetic.main.activity_main.*

class MyActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        textView.setText("Hello, world!")
       //Instead of findViewById(R.id.textView) as TextView
    }
}

textView is an extension property for Activity, and it has the same type as declared in activity_main.xml.

5
qo'shib qo'ydi
albatta. batafsil ma'lumotni bu yerda topishingiz mumkin: kotlinlang.org/docs/tutorials/android-plugin.html
qo'shib qo'ydi muallif sashk0, manba
unga bog'lanish mumkin
qo'shib qo'ydi muallif mzeus.bolt, manba

Siz quyidagi manbadan oddiygina ButterKnife.kt ni qo'shishingiz kerak:
https://github.com/JakeWharton/kotterknife
Men uchun ishladi.

2
qo'shib qo'ydi

Ko'rishlaringizdagi xatti-harakatlaringizni yaxshilash uchun ba'zi kengaytmalarni amalga oshirishingiz mumkin. Muntazam editTextda "onTextChange" uchun bu misolni tekshiring:

fun EditText.onTextChange(callback: (text: CharSequence?, start: Int, before: Int, count: Int) -> Unit) {
    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) {
            callback(s, start, before, count)
        }
    })
}

Foydalanish:

m_editText.onTextChange { text, _, _, _ -> 
   m_textView.text = text
}

Kotlin-android-kengaytmalariga ovoz beraman

1
qo'shib qo'ydi

Buni Project Build.gradle loyihasida qo'shing

buildscript {
ext.kotlin_version = '1.1.2-4'
ext.butterknife_version = '8.6.0'
repositories {
    maven { url 'https://maven.google.com' }
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0-alpha1'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    classpath "com.jakewharton:butterknife-gradle-plugin:$butterknife_version"

   //NOTE: Do not place your application dependencies here; they belong
   //in the individual module build.gradle files
   }
}

Va ilovangiz Build.Gradle ilovasida qo'shing.

    //Butterknife
compile "com.jakewharton:butterknife:$butterknife_version"
kapt "com.jakewharton:butterknife-compiler:$butterknife_version"
0
qo'shib qo'ydi

Kotlinda aslida ButterKnife tushunchalari uchun zarurat yo'q (yoki) kerak emas. chunki faoliyatingizdagi to'g'ridan-to'g'ri tartib-faylning ko'rinishini quyida keltirilgan deb bilib olasiz.

layout.xml

<button
     android:id="@+id/btn_prestage"
     android:layout_width="20dp"
     android:layout_height="20dp"
     android:background="@drawable/prestaging_off"/>

Activity.kt -ga o'ting

 btn_prestage.setBackgroundResource(R.drawable.staging_on)
 btn_prestage.setOnClickListener{ view ->
            Snackbar.make(view, "My Action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show() }

build.gradle(app)

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

android {
   dependencies {... }
}

kapt {
    generateStubs = true
}
0
qo'shib qo'ydi

Say Goodbye to findViewById or any library like Butterknife because,

Kotlin Android kengaytmalari plaginlari siz xml formatidagi ko'rinishga kirishga imkon beruvchi ba'zi qo'shimcha kodlarni ishlab chiqaradi, xuddi siz ular xml tartibi ta'rifida foydalanadigan id nomi bilan xususiyatlardek.

Bundan tashqari, mahalliy ko'rinish keshini hosil qiladi. Shunday qilib, birinchi marta bir xususiyat ishlatiladi, u oddiy findViewById qiladi. Ammo keyingi safar ko'rinish keshdan tiklanadi, shuning uchun komponentlarga kirish tezroq bo'ladi.

Ko'proq tushunish uchun namuna olish uchun docs ga qarang.

0
qo'shib qo'ydi