1. Binding Approach instead of R. approach
for using view-binding approach instad of R.layout, R.id. approach
Step 1:
inside the build.gradle (Module:app) file
inside the android block
android{
....
....
buildFeatures{
viewBinding true
}
}
add buildFeature and set viewBinding to true
Step 2:
inside the MainActivity( or some intent of view in which we want to use binding )
create a variable
var binding_name : ActivityMainBinding? = null
Note:
* ActivityMainBinding now refers to activity_main.xml file
* so set name according to the activity file
Step 3:
now set up the binding by layoutInflater
binding = ActivityMainBinding.inflate(layoutInflater)
now the R.layout is reffered to root of layout
now the R.id is reffered to the root->id_of_the_element
syntax wise work as
1.
setContentView(binding_name?.root) // instead of setContentView(R.layout.activity_main)
2.
binding_name?.id_of_the_element?.setOnClickListner{..} //
instead of
var object_name = findViewByID(R.id.id_of_the_element)
object_name.setOnClickListner{ .... }
Step 4:
add a onDestroy function and use it to prevent memory leakages
override fun onDestroy(){
super.onDestroy()
binding_name = null
}
Benefits / or why should we use binding approach insted of R. approach
1. The approach will make code shorter and concise
2. Faster and more effiecient during compile time
3. we can now have same id to different file's elements and still can use them
4. google recommends this approach
2.Moving between activities by intent creation
inside some function by which we have to change the activity
add the code below
1.Creating intent
val intent = Intent(this, Another_Activity_name::class.java)
2. passing data by intent
intent.putExtra(Constants.Name_Of_Variable_Who_Will_Recieve, variable_having_data_to_be_passed.text.toString()) // for passing data of this intent to another
// Constants is a constant class file havin g the variable Name_Of_Variable_Who_Will_Recieve ( in this case it will be in string form )
on reciving side
mYour_Name = intent.getStringExtra(Constants.Name_of_Variable_Who_Will_recieve)
3. Starting the new activity by intent
startActivity(intent) // for starting the new activity
4. Closing the current activity
finish() // for closing the current activity
Comments
Post a Comment