ANDROID按下时更改按钮颜色

时间:2020-08-02 11:45:34

标签: android kotlin button layout material-design

我有一个ScrollView,根据我从firebase上的数据库获得的响应数,我添加了buttons

private fun onSurveyLoaded(survey: Survey?) {

        survey?.let {
            survey_question.text = it.title
            val ll = LinearLayout(context)
            ll.orientation = LinearLayout.VERTICAL

            if (it.answer_a.isNotEmpty()){
                createButton(it.answer_a, ll)
            }

            if (it.answer_b.isNotEmpty()) createButton(it.answer_b, ll)

            if (it.answer_c.isNotEmpty()) createButton(it.answer_c, ll)

            if (it.answer_d.isNotEmpty()) createButton(it.answer_d, ll)

            if (it.answer_e.isNotEmpty()) createButton(it.answer_e, ll)

            response_list.addView(ll)
        }
    }

    private fun createButton(text: String, ll: LinearLayout): View {
        val view = (requireContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater)
            .inflate(R.layout.survey_item, ll, false)
        lateinit var letter: String

        when(numberOfAnswer){
            0 -> letter = "A"
            1 -> letter = "B"
            2 -> letter = "C"
            3 -> letter = "D"
            4 -> letter = "E"
        }

        numberOfAnswer++

        val str = SpannableString("$letter.    $text")
        str.setSpan(ForegroundColorSpan(ResourcesCompat.getColor(resources, R.color.colorPrimary, null)), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        str.setSpan(StyleSpan(BOLD), 0,1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

        view.survey_response.text = str

        ll.addView(view)

        return view
    }

按钮的布局是在布局文件survey_item.xml中定义的,在该文件中我使用了“材质按钮”。

按钮可以正确显示,但是问题是我不知道如何更改按钮背景的颜色。我希望按下按钮时其颜色变为绿色,默认情况下为白色。

0 个答案:

没有答案