2016-10-20 3 views
8

カスタムビューを作成したいところは、Androidビューのラッパーだけです。子ビューのレイアウトを管理するカスタムViewGroupを作成しましたが、そのような複雑さは必要ありません。私は基本的にやりたいことのようなものです:理由Anko DSLでカスタムView/ViewGroupクラスを作成

class MainActivity 
verticalLayout { 
    textView { 
    text = "Something that comes above the swipe" 
    } 
    swipeLayout { 
    } 
} 

class SwipeLayout 
linearLayout { 
    textView { 
    text = "Some text" 
    } 
    textView { 
    text = "Another text" 
    } 
} 

私は別のファイルにSwipeLayoutコードを移動したいのですが、どの複雑なレイアウトのものを自分で行うにはしたくないということです。これはAnkoを使って可能ですか?

編集:推奨されているように、Is it possible to reuse a layout in Kotlin Ankoは、ビューがルートレイアウトの場合にこの問題を解決します。しかし、例に示されているように、私はこれを別のレイアウトに含めたいと思います。それは可能ですか?

+3

[それはKotlinアンコでレイアウトを再利用することが可能である]の可能な重複(http://stackoverflow.com/questions/40076956/is-it-possible-to-reuse- a-layout-in-kotlin-anko) – miensol

+1

私は@miensolに同意します。この回答を参照してください:http://stackoverflow.com/a/40078650/4568679 – Slav

+1

すみません。これは大丈夫だったはずです。しかし、カスタムビューをルートレイアウトにしたくない場合はどうすればよいですか?私が示した例のように、それは別のレイアウトに含まれています。私がしようとすると、java.lang.IllegalStateExceptionが発生します。ビューはすでに設定されています:org.jetbrains.anko._LinearLayout {8bdb786 V.E ...... ......。 0,0-0,0} ' –

答えて

1

私もこのような何かを探していたが、私はカスタムビューが見つかり最適なソリューションは、このようなものです:

public inline fun ViewManager.customLayout(theme: Int = 0) = customLayout(theme) {} 
public inline fun ViewManager.customLayout(theme: Int = 0, init: CustomLayout.() -> Unit) = ankoView({ CustomLayout(it) }, theme, init) 

class CustomLayout(c: Context) : LinearLayout(c) { 
    init { 
     addView(textView("Some text")) 
     addView(textView("Other text")) 
    } 
} 
2

あなたがViewManagerを使用することができます。

fun ViewManager.swipeLayout() = linearLayout { 
    textView { 
    text = "Some text" 
    } 
    textView { 
    text = "Another text" 
    } 
} 

class MainActivity 
    verticalLayout { 
    textView { 
     text = "Something that comes above the swipe" 
    } 
    swipeLayout {} 
} 
関連する問題