Intend之属性extra
我们这次想要实现的功能是从A活动跳到B活动时,A活动中有一个输入框和一个按钮,当点击按钮是时会跳到B活动,然后把A活动中的输入框的内容传到B活动中,且在B活动中的TextView中显示
A活动中先添加一个输入框和一个按钮
代码如下
1 <EditText 2 android:id="@+id/new_et" 3 android:layout_marginTop="20dp" 4 android:layout_width="match_parent" 5 android:layout_height="wrap_content" /> 6 7 <Button 8 android:layout_marginTop="20dp" 9 android:layout_width="match_parent" 10 android:layout_height="wrap_content" 11 android:text="跳转" 12 android:id="@+id/btn1"/>
然后在A活动中初始化这两个控件
如
1 private Button btn1; 2 private EditText new_dt; 3 btn1=(Button)findViewById(R.id.btn1); 4 new_dt=(EditText)findViewById(R.id.new_et);
因为我们需要的功能是点击按钮跳转到B活动,所以需要在A活动中设置按钮监听器,并且在监听器中添加跳转所需要的代码
1 Intent i=new Intent(NewActivity.this,ThirdActivity.class);//初始化Intent 2 i.putExtra("info",new_dt.getText().toString());//把输入框中的内容,传到info 3 startActivity(i);//启动活动
接下来我们接着完成B活动,在B活动中我们使用TextView来显示
我们把xml文件中我们添加TextView控件
1 <TextView 2 android:id="@+id/third_tv" 3 android:layout_width="wrap_content" 4 android:layout_height="wrap_content" 5 android:text="显示内容" 6 android:textSize="20sp" 7 android:layout_gravity="center_horizontal" 8 android:layout_marginTop="200dp" 9 />
在B活动的Java中我们先初始化控件,然后接受A活动传回来的数据,并在TextView中显示
初始化控件
1 private TextView tv; 2 tv=(TextView)findViewById(R.id.third_tv);
接下来使用getIntent来获取A活动传过来的Intend对象,代码如下
1 if (getIntent()!=null){//判断是否由上个界面跳转过来 2 Intent intent=getIntent(); 3 String info=intent.getStringExtra("info");//获取info中的信息并且转化为String类型的 4 tv.setText(info);//如果不为空,则在TextView中显示info中的数据 5 }
如果需要大数据来进行传输的话,可以使用Bundle,并且适应extras,来进行添加和接受,可以把在A活动中按钮监听器中的代码换为如下代码
1 Intent i=new Intent(NewActivity.this,ThirdActivity.class);//初始化Intent 2 Bundle bundle=new Bundle();//初始化Bundle集合 3 bundle.putString("info",new_dt.getText().toString());//把输入框中的字符串传给info 4 i.putExtras(bundle);//在intent对象中添加bundle 5 startActivity(i);//启动活动
在B活动中的fi代码可以换位如下代码:
1 if (getIntent()!=null){//判断是否由上个界面跳转过来 2 Intent intent=getIntent(); 3 Bundle bundle=intent.getExtras(); 4 String info=bundle.getString("info"); 5 tv.setText(info);//如果不为空,则在TextView中显示info中的数据 6 }
以上就是extra的知识

浙公网安备 33010602011771号