android 的button响应及(Intent,Bundle)传递参数

注:1.button.setonClickListener()的实现方法单独封装成一个函数,返回值 View.onClickListener , 直接写成 onClickListener.

       2. 再次练习用Bundle设置和读取数据。通过Intent传递,Bundle作为Intent传递数据的载体。

----------------------------------------------------------------------------------------------------------

效果截图:

android 的button响应及(Intent,Bundle)传递参数_第1张图片


android 的button响应及(Intent,Bundle)传递参数_第2张图片


--------------------------------------------------------------------------------------------------------------------

关键代码一:点击主页面按钮的响应

package com.android.myapp;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

	private Button button;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button)findViewById(R.id.button);
        button.setOnClickListener(listener);
    }

    private OnClickListener listener = new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			Intent intent = new Intent(MainActivity.this, OtherActivity.class);
			Bundle bundle = new Bundle();
			bundle.putString("name", "Nicole");
			bundle.putInt("age", 25);
			intent.putExtras(bundle);
			startActivity(intent);
			
			
		}
	};

    
}


关键代码二:接收端OtherActivity.java 用Bundle读取数据

package com.android.myapp;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class OtherActivity extends Activity {
	
	private TextView textView;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_other);
		textView = (TextView)findViewById(R.id.msg);
		
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		String nameString = bundle.getString("name");
		int age = bundle.getInt("age");
		
		String str = "Name-->>"+nameString+"\n"+"Age-->>"+age+"\n";
		textView.setText(str);
		
	}

}



你可能感兴趣的:(Android开发,onClickListener,Bundle)