简体   繁体   中英

Android application stops unexpectedly

It does not show any error. Its my first time and i don't know what to do . The emulator keeps on showing the message "application stopped unexpectedly". Please help.

MainActivity.java

package com.l;

import android.os.Bundle; 
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
int counter;

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

    Button add=(Button)findViewById(R.id.badd);
    Button sub=(Button)findViewById(R.id.bsub);
    display=(Button)findViewById(R.id.text);
    add.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            counter++;
            display.setText("Your total is " + counter);
        }
    });

    sub.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
        counter--;  
        display.setText("Your total is " + counter);
        }
    });

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>


<TextView

    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="total"
    android:textSize="45sp" 
    android:id="@+id/text" 
    />

 <Button
    android:layout_width="250dp"
    android:layout_height="wrap_content" 
    android:layout_gravity="center"
    android:text="add"
    android:textSize="20sp" 
    android:id="@+id/badd"
    ></Button>
 <Button
    android:layout_width="250dp"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="sub"
    android:textSize="20sp"
    android:id="@+id/bsub"
     ></Button>

</LinearLayout>

You have declared a textview as a button!

display=(Button)findViewById(R.id.text);

change (Button) to (TextView)!!!

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