findViewById
並對他是又愛又恨–
TextView tvTitle = (TextView) getView().findViewById(R.id.tv_title);
TextView tvUserName = (TextView) getView().findViewById(R.id.tv_user_name);
TextView tvUserAge = (TextView) getView().findViewById(R.id.tv_user_age);
Button btnLogout = (TextView) getView().findViewById(R.id.btn_logout);
–
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textColor="@color/black"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
android {
...
buildFeatures {
viewBinding true
}
}
class MainActivity : Activity() {
private lateinit var mBinding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(mBinding.root)
mBinding.tvTitle.text = "Hello ViewBinding"
}
}
ActivityMainBinding
是哪來的?activity_main.xml
那就會產生 ActivityMainBinding
class MainFragment : Fragment() {
private lateinit var mBinding: FragmentMainBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
mBinding = FragmentMainBinding.inflate(layoutInflater, container, false)
return mBinding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
mBinding.tvTitle.text = "Hello ViewBinding"
}
}
//僅寫出產生 view binding 的部分
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
AdapterBinding.inflate(LayoutInflater.from(parent.context), parent, false)
)
}
//...
–
kotlinx.android.synthetic.<layout>.*
–