当前位置: 代码迷 >> 综合 >> kotlin如何找控件id
  详细解决方案

kotlin如何找控件id

热度:10   发布时间:2024-02-02 14:35:24.0

Activity

module:app -> build.gradle 添加以下代码

apply plugin: 'kotlin-android-extensions'

我们不需要使用findViewById来获取控件,只需要使用控件的id就可以操作控件的相关方法。当然大家也发现了import,没错,这也是必须的,AndroidStudio会自动为你添加。如果你不嫌麻烦,手动写也是没毛病的。

import格式是这样的:kotlinx.android.synthetic.main.布局名称.*。需要注意的是include进来的布局,也是需要通过import导入相应布局,这样才能正常使用。

建议布局文件中id的命名规则和java类中的命名规则保持一致,都使用驼峰命名。

?//直接引用即可
helloTv.text = "Hello Kotlin!"?

Fragment

class CardViewFragment : Fragment() {private val TAG = "CardViewFragment"@VisibleForTesting lateinit var cardView: CardView// SeekBar that changes the cornerRadius attribute for the cardView widget.@VisibleForTesting lateinit var radiusSeekBar: SeekBar// SeekBar that changes the Elevation attribute for the cardView widget.@VisibleForTesting lateinit var elevationSeekBar: SeekBaroverride fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {return inflater.inflate(R.layout.fragment_card_view, container, false)}override fun onViewCreated(view: View, savedInstanceState: Bundle?) {super.onViewCreated(view, savedInstanceState)cardView = view.findViewById(R.id.cardview)radiusSeekBar = view.findViewById(R.id.cardview_radius_seekbar)elevationSeekBar = view.findViewById(R.id.cardview_elevation_seekbar)}}