不幸的是,该应用程序已停止工作-android



点击按钮时会发生这种情况

我的活动。XML文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
<EditText android:id="@+id/enter_number"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:hint="@string/enter_number"
    android:layout_weight="1"
    />
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_calculate" 
    android:onClick="calculate"
    />
</LinearLayout>

.java文件

    package com.example.helloworld;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.widget.TextView;
public class Tables extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the message from the intent
        int number=0;
        int i=1;
        int next=0;
        Intent intent = getIntent();
        String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
        number=Integer.parseInt(message);
        TextView textView = new TextView(this);
        String[] myString = new String[10]; //create array
        for (i = 1; i <= myString.length; i++) { 
             next= number + next;
             myString[i] =  String.valueOf(number)+'x'+String.valueOf(i)+'='+String.valueOf(next)+'n';
            // textView.setText(myString[i]);  
            // setContentView(textView);
        }
        StringBuilder builder = new StringBuilder();
        for (String s : myString){
          builder.append(s+" ");
        textView.setText(builder.toString());
        }
        setContentView(textView);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_tables, menu);
        return true;
    }
}

我认为错误是在显示过程中。但找不到解决方案。

谢谢,

您必须在活动中定义一个calculate方法。由于您已经在布局文件中设置了onClick属性,当您单击该按钮时,Android Framework将尝试调用Tables活动的以下方法:

  public void calculate(View v){
      //put you code here this will be execute when the button is clicked
  }

布局文件似乎是用于主活动的,而不是用于Tables活动的。确保您的MainActivity类有一个签名为public void calculate(View view)的方法,以便活动可以响应按钮单击。这可能是问题所在,而不是显示Tables活动的问题。

最新更新