1

私の変数を定義する時に、私がnullで初期化するときに初期値を与えることを頼むので、私はアンドロイドでkotlin言語を使って問題を解決し始めました。値とのOnCreate関数内の変数をバインドするには、そのkotlinを使ってアンドロイドでウィジェットを初期化する方法

がここに私のコードです

kotlin.KotlinNullPointerExceptionを与える

class AddsFragment : Fragment() { 

    var Add: Button = null!! 

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { 
     val Rootview = inflater!!.inflate(R.layout.clubsfragment, null, false) 
     Add = Rootview.findViewById(R.id.add) as Button 
     return Rootview 
    } 
} 

答えて

13

!!オペレータは、受信者がnullで、それがKotlinNullPointerExceptionであるかどうかをチェックします。したがって、null!!は常に例外をスローします。

あなたは次の方法で望むものを達成することができます:

  1. Button?にプロパティの種類を設定します。この場合、ボタンのメソッドにアクセスするときは、?または!!のいずれかを使用する必要があります。

    var add: Button? = null 
    // Initialize it somewhere. 
    
    add?.setText("Text") // Calls setText if Add != null 
    add!!.setText("Text") // Throws an exception if Add == null 
    
  2. ボタンlateinitプロパティを確認します。

    lateinit var add: Button 
    
  3. は、ボタンnotNullデリゲートプロパティを確認します。最後の2つの場合

    var add: Button by Delegates.notNull() 
    

ボタンがnullある場合は、チェックすることはできません。あなたがnullの変数との比較を必要とする場合は、最初のアプローチを使用してください。


私はこの答えの詳細については説明しません。最初にはKotlin Android Extensionsを使用しています。これは、ビューの合成プロパティを生成するコンパイラプラグインで、findViewById()を呼び出す必要はなく、生成されたプロパティを使用してビューにアクセスできます。

2番目の方法はfindViewById()を呼び出す独自の代理人を作成することです。

val add: Button by bindView(R.id.add) 

あなたはKotterKnifeプロジェクトで、このようなデリゲートの例を見つけることができます:それは次のようになります。

+0

で各メソッドのプロ/短所をチェックアウトすることができます? – sasuke

+0

答えにさらに情報を追加しました。 – Michael

3

あなたはヘルパーbind関数を記述するためにKotlinを使用することができます。

fun <T : View> Activity.bind(@IdRes res : Int) : Lazy<T> { 
    @Suppress("UNCHECKED_CAST")  
    return lazy { findViewById(res) as T } 
} 

その後、あなたは、単に(Javaでfinalに等しい)valを使用して、一度あなたの変数を定義することができます。

class MyActivity : AppCompatActivity() { 
    private val button: Button by bind(R.id.button) 
} 

または

class MyActivity : AppCompatActivity() { 
    private val button by bind<Button>(R.id.button) 
} 
1

ビューを初期化できます以下の方法のいずれかの使用によってkotlinで:

1 NULL可能に

private var textView: TextView? = null 
… 
textView = findViewById(R.id.text_view) as TextView 

2 lateinit

private lateinit var textView: TextView 
… 
textView = findViewById(R.id.text_view) as TextView 

3 Delegates.notNull()

をvarsの
private var textView: TextView by Delegates.notNull() 
… 
textView = findViewById(R.id.text_view) as TextView 

4.レイジープロパティ

private val textView: TextView by lazy { findViewById(R.id.text_view) as TextView } 

5. Butterknife

@BindView(R2.id.text_view) 
internal lateinit var textView: TextView 

6. Kotterknife

private val textView: TextView by bindView(R.id.text_view) 

7. Kotlin Androidの拡張

コードサンプルがありません。正しいインポートが追加され、以下のような合成生成プロパティが使用されます。

binding = FragmentLayoutBinding.inflate(inflater, container, false) 
... 
binding.textView.text = "Hello" 

を結合

import kotlinx.android.synthetic.main.<layout>.* 

8. Androidのデータあなたは、どのように私は私の変数を初期化することができますPros/cons of Android view access strategies

関連する問題