Spinner、startActivityForResult、setResult的使用

效果图


Spinner、startActivityForResult、setResult的使用_第1张图片

Spinner、startActivityForResult、setResult的使用_第2张图片


功能


实现带选择所在城市的用户注册、主要为了测试带有返回值的页面

Java源码


public class UserRegisterActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_register);

        Button choosebtn = (Button) findViewById(R.id.choosebtn);
        choosebtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(UserRegisterActivity.this, ChooseCityActivity.class);
                // 有返回值的跳转 ,, 其中  0x11 为请求码
                startActivityForResult(intent, 0x11);
            }
        });
    }
    /**
     * 功能: 处理返回的数据
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        {
            if (requestCode == 0x11 && resultCode == 0x11)
            {
                Bundle bundle = data.getExtras();
                String city = bundle.getString("city");
                EditText editText = (EditText)findViewById(R.id.city);
                editText.setText(city);
            }
        }
    }
}

public class ChooseCityActivity extends Activity {
    Spinner spinner;
    Button button;
    String city = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_city);

        spinner = (Spinner)findViewById(R.id.citySpinner);
        button = (Button)findViewById(R.id.returnBtn);
        /**
         * Spinner 的使用;
         */
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                city = parent.getItemAtPosition(position).toString();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        /**
         * 功能: 处理返回的数据
         */
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = getIntent();
                Bundle bundle = new Bundle();
                bundle.putString("city", city);
                intent.putExtras(bundle);
                // 返回页面  其中 0x11为返回码
                setResult(0x11, intent);
                finish();
            }
        });
    }
}







你可能感兴趣的:(Spinner、startActivityForResult、setResult的使用)