activity

一、顶部菜单

    //创建一个菜单
    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.main,menu)
        return true
    }
    //触发事件
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item.itemId){
            R.id.add_item -> Toast.makeText(this,"add",Toast.LENGTH_SHORT).show()
            R.id.del_item -> Toast.makeText(this,"del",Toast.LENGTH_SHORT).show()
        }
        return true
    }

 

二、intent

intent可以和activity、服务、广播交互。本节只讲 activity交互

1.使用显式intent

        button.setOnClickListener {
            val intent = Intent(this, Main2Activity::class.java)
            startActivity(intent)
        }

2.使用隐式intent

AndroidManifest.xml

        <activity android:name=".Main2Activity">
            <intent-filter>
                <action android:name="com.rockcheck.konlittest.ACTION_START" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

跳转到Main2Activity

        button.setOnClickListener {
            val intent=Intent("com.rockcheck.konlittest.ACTION_START")
            startActivity(intent)
        }

 使用intent调用浏览器

        button.setOnClickListener {
            val intent=Intent(Intent.ACTION_VIEW)
            intent.data= Uri.parse("https://www.baidu.com")
            startActivity(intent)
        }

 

 

 3.传参给下一个activity

main1

        button.setOnClickListener {
            val intent=Intent(this,Main2Activity::class.java)
            intent.putExtra("key","data")
            startActivity(intent)
        }

main2

        var str=intent.getStringExtra("key")
        Toast.makeText(this,str,Toast.LENGTH_SHORT).show()

 

4.传回给上个界面

main1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        button.setOnClickListener {
            val intent=Intent(this,Main2Activity::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 res=data?.getStringExtra("key")
                Toast.makeText(this,res,Toast.LENGTH_SHORT).show()
            }
        }
    }

main2

    //按返回键
    override fun onBackPressed() {
        intent.putExtra("key","abc")
        setResult(RESULT_OK,intent)
        finish()
    }

 

posted @ 2020-04-15 13:16  富坚老贼  阅读(473)  评论(0编辑  收藏  举报