简体   繁体   中英

Unfortunately, my Android app has stopped

I am very new to Android development, so I was puzzled, when all I made a, very simple app, and got a very non-descriptive error: "Unfortunately, MyApp has stopped". No syntax error. Just this somewhat unhelpfull message. Here is what I did.

  1. Made a new app project (Android 4.1)
  2. Made a button - button1
  3. Made a java method - DoStuff() - in the activity class (see below)
  4. Added call to DoStuff to the button the activity dialog xml (see below)
  5. Run project as Android Application
  6. Press Button
  7. The error appears

The Method:

public void DoStuff(){
    TextView tv = (TextView)this.findViewById(R.id.textView1);
    tv.setText("Hello dude");
}

The button xml:

 <Button
        android:id="@+id/button1"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/textView1"
        android:layout_marginTop="82dp"
        android:text="Button"
        android:onClick="DoStuff" />

I hope you can help me.

I found the solution elsewhere. It appears that the DoStuff needs to have View as argument, thus looking like this:

public void DoStuff(View v){
    TextView tv = (TextView)this.findViewById(R.id.textView1);
    tv.setText("Hello dude");
}

Why, I don't know, but it works :-)

In Android, for different types of events and actions, the respective listeners have their specified functions signatures. for example, for an action listener of a button, the function must have following signature:

public void functionName(View view);

in your layout file, for onClick property of Button you'll be required to provide function name only..

where View argument tells the view object that has fired that action (eg, the button in your case)

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