传递ArrayList<String>
传递ArrayList<String>类型数据的方法
1)在创建的项目工程里面创建一个用来发送数据的SendActivity类,具体代码如下:
package zjh.android.lx;
import java.util.ArrayList;
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button;
public class SendActivity extends Activity { private Button send = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.activity_main); this.send = (Button)super.findViewById(R.id.send); this.send.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ArrayList<String> info = new ArrayList<String>(); info.add("张三"); info.add("zhangsan"); info.add("22"); Intent intent = new Intent(SendActivity.this,ReceiveActivity.class); //传递List<String>类型的数据 intent.putStringArrayListExtra("infolist", info); startActivity(intent); } }); }
}
|
2)创建一个用来接收SendActivity类发送过来数据的ReceiveActivity,其代码如下所示:
package zjh.android.lx;
import java.util.ArrayList;
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.widget.TextView;
public class ReceiveActivity extends Activity { private TextView show; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.receive); this.show = (TextView)super.findViewById(R.id.show); //取得Intent对象 Intent intent = super.getIntent(); ArrayList<String> infolist = new ArrayList<String>(); //接收发送过来的数据 infolist = intent.getStringArrayListExtra("infolist"); String name = infolist.get(0); String password = infolist.get(1); String age = infolist.get(2); this.show.setText("name="+name+"\n"+"password="+password+"\n"+"age="+age); } }
|
3)在AndroidMainfest.xml文件中添加相应的activity
<activity android:name="zjha.android.lx.ReceiveActivity"/> |
此时,Intent传递ArrayList<String>类型数据的方法就实现了,当然也可以把ArrayList<String>中的String换成其它简单数据类型。