Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Anko DSL inside a Fragment?

The Github wiki page show this example to be used in Activity instance:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    verticalLayout {
        padding = dip(30)
        editText {
            hint = "Name"
            textSize = 24f
        }
        editText {
            hint = "Password"
            textSize = 24f
        }
        button("Login") {
            textSize = 26f
        }
    }
}

How to do the same inside a Fragment?

I tried to put that verticalLayout block in onCreateView but the method cannot be resolved. I have added anko-support-v4 dependency, but still no luck.

like image 878
akhy Avatar asked Nov 16 '15 07:11

akhy


3 Answers

With Anko 0.8 you can also use an AnkoComponent, if you want to hold your UI in a separate class so you can reuse it elsewhere.

class FragmentUi<T>: AnkoComponent<T> {
    override fun createView(ui: AnkoContext<T>) = with(ui) {
        verticalLayout {
            // ...
        }
    }
}

You can call it in your fragment onCreateView() by

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle?): View
        = FragmentUi<Fragment>().createView(AnkoContext.create(ctx, this))
like image 75
RussHWolf Avatar answered Oct 19 '22 05:10

RussHWolf


After digging up anko-support-v4 source code plus some trial and errors, I have found a workaround although I'm not sure if it's the right/recommended way. It seems a little undocumented.

A sample from my Fragment code:

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {

    return UI {
        verticalLayout {
            linearLayout {
                avatar = imageView().lparams(width = dip(48), height = dip (48))
                name = textView().lparams(width = 0, weight = 1f)
            }

            linearLayout {
                // ...
            }
        }
    }.toView()
} 

I'm returning layout DSL wrapped in UI { ... }.toView() in Fragment.onCreateView(...)

like image 37
akhy Avatar answered Oct 19 '22 04:10

akhy


As of anko 0.8.1 the correct code would be:

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return UI {
        verticalLayout {
            linearLayout {
                // ...
            }
            linearLayout {
                // ...
            }
        }
    }.view
} 
like image 7
Eefret Avatar answered Oct 19 '22 03:10

Eefret