左邊和右邊分別是兩個(gè)不同的Fragment,左邊的Fragment中右一個(gè)Button組件,目標(biāo)是想要獲取這個(gè)組件的id,以便進(jìn)行將右邊的Fragment更改成另一個(gè)Fragmeent的操作。
left_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Button"
/>
</LinearLayout>
LeftFragment.kt
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
class LeftFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.left_fragment, container, false)
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
tools:context=".MainActivity"
android:orientation="horizontal">
<fragment
android:id="@+id/leftFragment"
android:name="com.example.fragmenttest.LeftFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
/>
<fragment
android:id="@+id/rightLayput"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
/>
</LinearLayout>
可以看到,通過(guò)findViewById的方式來(lái)獲取肯定是失敗的
以前以通過(guò)kotlin-android-extensions這個(gè)插件,可以直接使用布局中的控件id來(lái)操作view控件, 不用再findViewById。但是很可惜,在as升級(jí)到4.0之后便被拋棄了。
現(xiàn)在通過(guò)MainBingding也可以實(shí)現(xiàn),首先在app下的build.gradle文件下面添加如下代碼:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-581628.html
android{
...
buildFeatures{
viewBinding true
}
}
將上述代碼報(bào)錯(cuò)修改成如下圖所示的代碼即可:
獲取到后成功修改:
ps:
綁定的書(shū)寫(xiě):
例如news_content_frag.xml需要綁定,那么寫(xiě)法如下:文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-581628.html
val binding = NewsContentFragBinding.inflate(layoutInflater)
到了這里,關(guān)于Kotlin獲取Fragment中的組件的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!