有什么方法可以通过编程使用kotlin更改片段中的文本颜色吗?

时间:2019-12-14 13:00:41

标签: android xml android-studio android-fragments kotlin

这是示例代码,对于某些情况,我需要在文本视图中更改文本颜色。像,不同月份的文字颜色应该不同。 谢谢。

FragmentOne.kt

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup



class FragmentOne : Fragment() {



    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_one, container, false)

    }

}

fragment_one.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".FragmentOne">


    <TextView
        android:id="@+id/textview"
        android:textAlignment="center"
        android:layout_gravity="center"
        android:background="#7654ad"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="me !" />

</FrameLayout>

1 个答案:

答案 0 :(得分:0)

您可以在onCreateView方法中尝试吗

var view = inflater.inflate(R.layout.fragment1, container, false);
var textView : TextView = view?.findViewById(R.id.textview) as TextView
//your condition,then set the color. Use if or when
textView.setTextColor(Color.RED)
相关问题