onActivityResult似乎无法正常工作

时间:2017-03-26 13:46:10

标签: java android android-intent

MainActivity.java - 主类

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 - 子类

 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();
    }


}

我试图解决它。这没问题,但我看不到我的Main类Toast中调用的onActivityResult()。 (Toast.makeText(getApplicationContext(),"test",Toast.LENGTH_SHORT).show();

我错过了什么?

1 个答案:

答案 0 :(得分:0)

int RESULT_OK 标准活动结果:操作成功。

常数值:-1(0xffffffff)

android developer site

这样做:

setResult(RESULT_OK);