简体   繁体   中英

Using SWITCH to call different intents depending on what button was pressed

I cant seem to find any info on this anywhere.

Is it possible first?

Classic page with 5 buttons each open new page.

I guess the question is how do i create a listener for an unknown button?

Thanks

Not sure what you mean by an "unknown" button, but yes, this is possible. Have your class implement onClickListener, and then in the onClick method, switch on v.getId():

public class IntentClass extends Activity implements OnClickListener {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button button1 = (Button)findViewById(R.id.button1);
        button1.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button1:
            Intent i = new Intent(this, OtherClass.class);
            startActivity(i);
            break;
        //other cases here
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM