TimePicker的startActivityForResult

时间:2018-01-10 14:43:27

标签: android

  

在我的MainActivity中:

public class MainActivity extends AppCompatActivity{
public static final int REQUEST_TIME = 1;

.....

public void chooseTime(){
    ImageButton btn_time = (ImageButton)findViewById(R.id.btn_time);
    btn_time.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent_time = new Intent(MainActivity.this,time_pick.class);
            startActivityForResult(intent_time,REQUEST_TIME);
        }
    });
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode){
        case REQUEST_TIME: {
            if(requestCode == RESULT_OK){
                TextView text_time = (TextView)findViewById(R.id.menu_time);
                text_time.setText(data.getStringExtra("time_detail"));
            }
        }
    }
}
  

在我的TimePicker活动中:

public void onButtonClick(){
    Button btn = (Button)findViewById(R.id.btn_time_confirm);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            TimePicker timePicker = (TimePicker)findViewById(R.id.timePicker) ;
            String time_detail = timePicker.getCurrentHour() + " : " + timePicker.getCurrentMinute();
            Intent data = new Intent();
            data.putExtra("time_detail",time_detail);
            setResult(RESULT_OK,data);
            finish();
        }
    });
}

我尝试从MainActivity启动我的TimePicker活动,并从TimePicker获取时间值并显示在MainActivity中的一个TextView中。

这是代码,我使用了putExtra和getStringExtra,但我没有工作,活动确实从MainActivity更改为TimePicker的活动,从TimePicker的活动更改为MainActivity,当我点击按钮。

0 个答案:

没有答案