简体   繁体   中英

how do i link a button to a second activity after linking the first buttons in my main activity to websites?

How do i make a button open a activity if the rest of my buttons are linked to web pages with a onClickListener?

I go the webpages to open correctly in eclipse by using:

@Override
   public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
      Button b1=(Button)findViewById(R.id.button1);

    public void onClick(View v) {
            // TODO Auto-generated method stub
            sendToCoaches();
        }

    private void sendToCoaches() {
        // TODO Auto-generated method stub
          String url = "http://www.signal5crossfit.com/coaches/";
             Intent i = new Intent(Intent.ACTION_VIEW);
             i.setData(android.net.Uri.parse(url)); 
             startActivity(i);
         }
});

 b7.setOnClickListener(new View.OnClickListener(){
    @Override
    public void onClick(View v){
    sendToContacts();

    }

    public void sendToContacts() {

          Intent intent = new Intent(AppActivity.this, App2Activity.class);
          startActivity(intent); 
          }
 });}}

I changed it to the second example that you up in to include the onClick in my xml file and this is the error i get.

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.Signal5.android/com.Signal5.android.App2Activity}: java.lang.NullPointerException

Does that mean its pointing to nowhere?

I'm guessing you're using android:onClick="onClick" in your xml layout.

Example:

<Button android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button 1"
    android:onClick="onClick" />

<Button android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button 2"
    android:onClick="onClick" />

You can check which view was clicked by getting its id: View.getId() .

public void onClick(View v) {
    switch(v.getId()){
    case R.id.button1:
        sendToCoaches();
        break;

    case R.id.button2:
        doSomethingElse();
        break;
    }
}

Another way of doing this would be to set a View.OnClickListener for each button:

Button b1 = (Button) findViewById(R.id.button1);
Button b2 = (Button) findViewById(R.id.button2);

b1.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
            sendToCoaches();
        }
});

b2.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
            doSomethingElse();
        }
});

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