zoukankan      html  css  js  c++  java
  • Activity传递参数——传递复杂数据(Bunble包)

    一.新建一个空的工程

    二.在主界面中添加一个按钮

    三.新建一个空的activity,并命名为TheAty

    四.修改MainActivity.java中的onCreate函数

     protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            findViewById(R.id.btnStartAty).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent i = new Intent(MainActivity.this, TheAty.class);
                   // i.putExtra("data", "hello android");
    
                    Bundle b = new Bundle();
                    b.putString("name","jikexueyuan");
                    b.putInt("age",2);
                    i.putExtras(b);
                    startActivity(i);
    
                }
            });

    五.在TheAty的布局文件中给textView加上id号

    <TextView android:text="@string/hello_world" android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tv"/>

    六.修改TheAty的源代码文件中的onCreate函数

    private TextView tv;
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_the_aty);
            Intent i = getIntent();
    
            Bundle data = i.getExtras();
            tv = (TextView)findViewById(R.id.tv);
           // tv.setText(i.getStringExtra("data"));
            tv.setText(String.format("name=%s,age=%d",data.getString("name"),data.getInt("age")));
        }

    七.运行结果

    ps:另一种传递Bundle的方式

     //i.putExtras(b);
    //在MainActivity.java中传递Bunble参数b
    i.pushExtra("data",b);
    //在TheAty.java中获取Bunble参数
    Bunble data = i.getBunbleExtra("name");
  • 相关阅读:
    HTTP——学习笔记(3)
    HTTP——状态码
    HTTP——学习笔记(2)
    HTTP——学习笔记(1)
    Sqlserver 存储过程
    Sqlserver 函数(例子)
    Sqlserver 函数
    sqlserver字段类型
    redis入门笔记(2)
    redis入门笔记(1)
  • 原文地址:https://www.cnblogs.com/happygirl-zjj/p/4705704.html
Copyright © 2011-2022 走看看