Skip to content

2. Styling The Views

Muhammet Ali YUCE edited this page Oct 20, 2020 · 1 revision

Style Your View

StyleR let’s you to code many styles for any view. This page will cover how to do it.

Let’s Create That Amazing View

We’ll create basic nested view which has 3 different styles. Here how our view looks like from xml:

500

Here how the packaging looks like:

200

SampleViewkt is our class file and it contains the nested view logics. style.json is contains each of our styles from it. And here one of it:

"SampleView.HugeHeader": [
    {
      "id": "tv_header",
      "style": "AppText.Header",
      "textSize": 60,
      "textColor": "red"
    },
    {
      "id": "tv_description",
      "style": "AppText"
    }
  ]

You must set the "id" parameter of your view from the style. "style" attribute provides to declare view style once and use it wherever needed to be use it. Check styles.json. Here how AppText.Header style looks like:

"AppText": {
  "textColor": "black",
  "fontName": "sf_regular.otf",
  "textSize": 12
},
"AppText.Header": {
  "fontName": "sf_bold.otf",
  "textSize": 18
}

Styles has parent-child relationship. AppText.Header seems like this for the StyleR:

"AppText.Header": {
  "textColor": "black",
  "fontName": "sf_bold.otf",
  "textSize": 18
}

Other attributes declared from StyleR library. If you want to understand how it works & implement your attribute, check the page.

StyleR Your View

We have implemented 3 different styles. And we call it when user clicks the view, here is the code block:

  companion object {
      private const val STYLE_NORMAL = "SampleView"
      private const val STYLE_REVERSE = "SampleView.Reverse"
      private const val STYLE_HUGE = "SampleView.HugeHeader"
  }

  private var styleName = STYLE_NORMAL
      set(value) {
          field = value
          applyStyleDif()
      }

  private fun applyStyleDif() {
      StyleR.applyStyle(binding.root, styleName)
  }

  override fun initView() {
      binding.run {
          root.setOnClickListener {
              styleName = when (styleName) {
                  STYLE_NORMAL -> STYLE_REVERSE
                  STYLE_REVERSE -> STYLE_HUGE
                  else -> STYLE_NORMAL
              }
          }
      }
  }

Here how it looks for each style:

SampleView

200

SampleView.Reverse

200

SampleView.HugeHeader

200

See the sample app to understand more.

200

Clone this wiki locally