当前位置:网站首页>Learning Android II from scratch - activity
Learning Android II from scratch - activity
2022-04-23 04:47:00 【Scattered moon】
Catalog
Basic knowledge
-
Any... In the project Activity All should be rewrite onCreate() Method , And now our FirstActivity This method has been overridden in , This is a Android Studio It's automatic
-
Android The design of program stresses the separation of logic and view , It's better for each one Activity Can correspond to a layout . Layout is used to display the content of the interface .
-
Check Generate Layout File Indicates that it will automatically be FirstActivity Create a corresponding Layout file , Check Launcher Activity Indicates that the FirstActivity Set as... Of the current project Lord Activity
-
Destroy one activity,finish() Method
-
startActivity() Method , Used to start Activity
-
Android Medium Activity It can be layered . Every time we start one new Activity, Will cover the original Activity above , And then click Back The key will destroy the top Activity, Below One Activity It will reappear .
-
activity Four kinds of state : function 、 Pause 、 stop it 、 The destruction
button
activity in :
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button1: Button = findViewById<Button>(R.id.button1)
button1.setOnClickListener {
Toast.makeText(this, "You clicked Button 1", Toast.LENGTH_SHORT).show()
}
}
- Toast yes Android A very good reminder provided by the system
Toast.makeText(this, "You clicked Button 1", Toast.LENGTH_SHORT).show()
The first parameter is Context, That is to say Toast Required context , because Activity Is itself a Context object , therefore It's coming in directly here this that will do . The second parameter is Toast Displayed text content . The third parameter is Toast When displayed Long , There are two built-in constants to choose from :Toast.LENGTH_SHORT and Toast.LENGTH_LONG. - **setOnClickListener()** Method register a listener for the button , When you click the button, the onClick() Method .
button.setOnClickListener {}
menu
- res New under the directory menu Catalog
- rewrite onCreateOptionsMenu() Method
- rewrite onOptionsItemSelected() Method
Intent( Jump 、 To transfer data )
- Show intent
Intent Overload with multiple constructors , One of them is Intent(Context packageContext, Class<? > cls). This constructor takes two arguments : The first parameter Context Ask for a startup Activity Up and down writing ; The second parameter Class Used to specify the target you want to start Activity, With this constructor, you can build Intent Of “ Intention ”.
val intent = Intent(this, SecondActivity::class.java)
startActivity(intent)
- Implicit Intent
button1.setOnClickListener {
val intent = Intent("com.example.activitytest.ACTION_START")
intent.addCategory("com.example.activitytest.MY_CATEGORY")
startActivity(intent)
}
<activity android:name=".SecondActivity" >
<intent-filter>
<action android:name="com.example.activitytest.ACTION_START" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="com.example.activitytest.MY_CATEGORY"/>
</intent-filter>
</activity>
- Show a web page
button1.setOnClickListener {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse("https://www.baidu.com")
startActivity(intent)
}
- Call dialing
button1.setOnClickListener {
val intent = Intent(Intent.ACTION_DIAL)
intent.data = Uri.parse("tel:10086")
startActivity(intent)
}
- Next Activity To transfer data
button1.setOnClickListener {
val data = "Hello SecondActivity"
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("extra_data", data)
startActivity(intent)
}
val extraData = intent.getStringExtra("extra_data")
Log.d("SecondActivity", "extra data is $extraData")
- Returns data to the previous Activity,startActivityForResult(intent, 1) Method
button1.setOnClickListener {
val intent = Intent(this, SecondActivity::class.java)
startActivityForResult(intent, 1)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
1 -> if (resultCode == RESULT_OK) {
val returnedData = data?.getStringExtra("data_return")
Log.d("FirstActivity", "returned data is $returnedData")
} }
}
button2.setOnClickListener {
val intent = Intent()
intent.putExtra("data_return", "Hello FirstActivity")
setResult(RESULT_OK, intent)
finish()
}
override fun onBackPressed() {
val intent = Intent()
intent.putExtra("data_return", "Hello FirstActivity")
setResult(RESULT_OK, intent)
finish()
}
activity The survival period of 7 Callback methods
- onCreate(). It will be Activity Called the first time it is created . In this method Activity Of Initialization operation , Such as loading layout 、 Binding events, etc .
- onStart(). This method is Activity Call when it changes from invisible to visible .
- onResume(). This method is Activity Called when you are ready to interact with the user . At this time Activity One Locate at the top of the return stack , And in operation .
- onPause(). This method is used when the system is ready to Start or restore another Activity Called when . We usually Will consume some... In this method CPU Resources released , And save some key data , But the execution speed of this method must be fast , Otherwise, it will affect the new stack top Activity Use .
- onStop(). This method is Activity Called when it is completely invisible . It and onPause() The main area of the method Don't lie in , If you start new Activity It's a dialog like Activity, that onPause() The method will be implemented That's ok , and onStop() Method does not execute .
- onDestroy(). This method is Activity By Call before destruction , after Activity The state of will change to destroyed state .
- onRestart(). This method is Activity The call is made from the stop state to the running state , That is to say Activity Has been rebooted .
3 Species survival time
- Complete life span .Activity stay onCreate() Methods and onDestroy() Method What you're going through is complete survival . In general , One Activity Will be in onCreate() Method to complete various initialization operations , And in the onDestroy() Method to release memory .
- Visible lifetime .Activity stay onStart() Methods and onStop() Method What you're going through is visible survival . Within the visible lifetime ,Activity Always visible to users , Even though it may not be possible to interact with users . I Through these two methods, we can reasonably manage the resources visible to users . For example onStart() Method to load resources , And in the onStop() Method to release resources , So as to ensure that it is in a stopped state Activity It won't take up too much memory .
- Front desk lifetime .Activity stay onResume() Methods and onPause() Method What we're going through is the life span of the front desk . Within the life of the front desk ,Activity Always running , At this time Activity It can interact with users , What we usually see and contact most is in this state Activity.
Activity Best practices
- Know which one you are now Activity, There is no need to let BaseActivity stay AndroidManifest.xml Register in , So choose to create a normal Kotlin Class 了 . And then let BaseActivity Inherited from AppCompatActivity, And rewrite onCreate() Method . Give Way BaseActivity Become ActivityTest All... In the project Activity Parent class of , because BaseActivity It's inherited from AppCompatActivity Of , So all in the project Activity The existing functionality of is not affected , They still inherit Activity All properties in .
open class BaseActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d("BaseActivity", javaClass.simpleName)
} }
- sign out activity,controller class
- To transfer data
companion object {
fun actionStart(context: Context, data1: String, data2: String) {
val intent = Intent(context, SecondActivity::class.java)
intent.putExtra("param1", data1)
intent.putExtra("param2", data2)
context.startActivity(intent)
} }
Activity2.actionStart(this, "data1", "data2")
版权声明
本文为[Scattered moon]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220555418254.html
边栏推荐
- leetcode003--判断一个整数是否为回文数
- 使用model.load_state_dict()时,出现AttributeError: ‘str‘ object has no attribute ‘copy‘
- [timing] empirical evaluation of general convolution and cyclic networks for sequence modeling based on TCN
- IEEE Transactions on industrial information (TII)
- Better way to read configuration files than properties
- Unity rawimage background seamlessly connected mobile
- QML进阶(五)-通过粒子模拟系统实现各种炫酷的特效
- Innovative practice of short video content understanding and generation technology in meituan
- Leetcode005 -- delete duplicate elements in the array in place
- Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.1.15.
猜你喜欢
拼了!两所A级大学,六所B级大学,纷纷撤销软件工程硕士点!
Innovation training (V) configuration information
Windows remote connection to redis
Luogu p1858 [multi person knapsack] (knapsack seeking the top k optimal solution)
Repair of self calibration SPC failure of Tektronix oscilloscope dpo3054
Perfect test of coil in wireless charging system with LCR meter
Simply drag objects to the item bar
Practice and exploration of knowledge map visualization technology in meituan
Spark optimization
520. Detect capital letters
随机推荐
JS détermine si la chaîne de nombres contient des caractères
Eight misunderstandings that should be avoided in data visualization
View analysis of scenic spots in ArcGIS
Simply drag objects to the item bar
Innovation training (XII) reptile
List&lt; Map&gt; Replication: light copy and deep copy
[paper reading] [3D object detection] voxel transformer for 3D object detection
Migrate from MySQL database to AWS dynamodb
Use model load_ state_ Attributeerror appears when dict(): 'STR' object has no attribute 'copy‘
Unity RawImage背景无缝连接移动
Programmers complain: I really can't live with a salary of 12000. Netizen: how can I say 3000
Unity3D 实用技巧 - 理论知识库(一)
Supplement 14: cmake practice project notes (to be continued 4 / 22)
Luogu p1858 [multi person knapsack] (knapsack seeking the top k optimal solution)
敏捷实践 | 提高小组可预测性的敏捷指标
leetcode008--实现strStr()函数
List remove an element
Customize the navigation bar at the top of wechat applet (adaptive wechat capsule button, flex layout)
Leetcode003 -- judge whether an integer is a palindrome number
C language: spoof games