onActivityResult seems to be not working

2019-03-03 10:14发布

问题:

MainActivity.java - Main class

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView ClockButton;

    private LinearLayout linearLayout;
    private TextView[] textViews;
    private int hours;
    private int minutes;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        textViews=new TextView[20];

        linearLayout=(LinearLayout)findViewById(R.id.LinearLayout1);

        ClockButton=(ImageView)findViewById(R.id.ClockIconButton);
        ClockButton.setOnClickListener(this);

    }

    public void onChangeContentView()
    {
        Intent intent = new Intent(this, MainActivity2.class);
        this.startActivityForResult(intent,1);
    }

    @Override
    public void onClick(View v) {
        onChangeContentView();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Toast.makeText(getApplicationContext(),"test",Toast.LENGTH_SHORT).show();//test
        hours=Integer.parseInt(data.getStringExtra("H"));
        minutes=Integer.parseInt(data.getStringExtra("M"));

        for(int i=0;i<textViews.length;i++)
        {
            if(textViews[i]==null)
            {
                textViews[i].setText(hours+" : "+minutes);
                linearLayout.addView(textViews[i]);

                break;
            }
        }
    }


}

MainActivity2.java - Sub class

 public class MainActivity2 extends AppCompatActivity implements View.OnClickListener {

    private ImageView OkButton;
    private TimePicker timePicker;
    private int hours;
    private int minutes;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        OkButton = (ImageView) findViewById(R.id.OkIcon);
        OkButton.setOnClickListener(this);
        timePicker = (TimePicker) findViewById(R.id.TimePicker1);
    }


    @Override
    public void onClick(View v) {

        hours = timePicker.getCurrentHour();
        minutes = timePicker.getCurrentMinute();
        Intent intent = new Intent();
        intent.putExtra("H", hours);
        intent.putExtra("M", minutes);
        setResult(1, intent);

        finish();
    }


}

I've tried to fix it. It's no problem, but I can't see the the Toast which is called in onActivityResult() in my Main class. (Toast.makeText(getApplicationContext(),"test",Toast.LENGTH_SHORT).show();)

What am I missing out on?

回答1:

int RESULT_OK Standard activity result: operation succeeded.

Constant Value: -1 (0xffffffff)

android developer site

Do like this:

setResult(RESULT_OK);