1. Intent 对象的基本概念
2. Intent 对象的基本使用方法
3. 使用 Intent 在 Activity之间传递数据的方法
1. Intent 对象的基本概念
程序相当于一个个的零件,拼凑起来为一个程序
2. Intent 对象的基本使用方法
3. 使用 Intent 在 Activity之间传递数据的方法
other.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical" > 6 7 <TextView //用来显示第一个Activity传入的数据 8 android:id="@+id/firstTextView" 9 android:layout_width="wrap_content" 10 android:layout_height="wrap_content" 11 /> 12 13 </LinearLayout>
Other.java
1 package first.pack; 2 3 import android.app.Activity; 4 import android.content.Intent; 5 import android.os.Bundle; 6 import android.sax.RootElement; 7 import android.widget.TextView; 8 9 public class Other extends Activity{ 10 11 private TextView textView; 12 13 @Override 14 protected void onCreate(Bundle savedInstanceState) { 15 super.onCreate(savedInstanceState); 16 setContentView(R.layout.other); 17 18 Intent intent = getIntent(); 19 int age = intent.getIntExtra("first.pack.age", 10); //注意有引号, 若键值对名称错误,即传入键值对没有此名称,则默认新建的这个键值对数值为10 20 String name =intent.getStringExtra("first.pack.name");//键值对类型与传入时保持一致 21 22 textView = (TextView)findViewById(R.id.firstTextView); //这里不需加rootView 23 textView.setText(name+ ":" + age+ ""); 24 } 25 }
fragment.xml
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:paddingBottom="@dimen/activity_vertical_margin" 6 android:paddingLeft="@dimen/activity_horizontal_margin" 7 android:paddingRight="@dimen/activity_horizontal_margin" 8 android:paddingTop="@dimen/activity_vertical_margin" 9 tools:context="first.pack.MainActivity$PlaceholderFragment" > 10 11 <Button 12 android:id="@+id/firstButton" 13 android:layout_width="wrap_content" 14 android:layout_height="wrap_content" 15 android:text="OpenDoor" 16 /> 17 18 </RelativeLayout>
MainActivity.java
1 public static class PlaceholderFragment extends Fragment { 2 3 private Button button; 4 5 public PlaceholderFragment() { 6 } 7 8 @Override 9 public View onCreateView(LayoutInflater inflater, ViewGroup container, 10 Bundle savedInstanceState) { 11 View rootView = inflater.inflate(R.layout.fragment_main, container, 12 false); 13 14 button = (Button)rootView.findViewById(R.id.firstButton); 15 ButtonListener buttonListener = new ButtonListener(); 16 button.setOnClickListener(buttonListener); 17 18 return rootView; 19 } 20 21 class ButtonListener implements OnClickListener{ 22 23 @Override 24 public void onClick(View v) { 25 Intent intent = new Intent(); 26 intent.setClass(getActivity(),Other.class); 27 28 intent.putExtra("first.pack.age", 20); //传入键值对 29 intent.putExtra("first.pack.name", "zhangsan"); 30 31 startActivity(intent); 32 } 33 } 34 }
记得在Manifest中注册!!!!!
运行过程
点击后得到