Android App Force立即关闭

时间:2014-05-14 04:02:01

标签: android

我正在尝试构建一个简单的应用来运行Chronometer。一旦我编辑了我的Java代码,当我尝试运行它时,应用程序就会强行关闭。

package com.example.debatetimer;

import android.app.Activity;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;

public class MainActivity extends Activity implements View.OnClickListener {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Button startbutt = (Button) findViewById(R.id.startbutton);
        startbutt.setOnClickListener(this);
        Button stopbutt = (Button) findViewById(R.id.stopbutton);
        stopbutt.setOnClickListener(this);
        Button resetbutt = (Button) findViewById(R.id.resetbutton);
        resetbutt.setOnClickListener(this);
    }
    @Override
    public void onClick(View v)
    {
        switch(v.getId())
        {
        case R.id.startbutton:{
            startChronometer(v);
        }
        case R.id.stopbutton:{
            stopChronometer(v);
        }
        case R.id.resetbutton:{
            resetChronometer(v);
        }
        }
    }

    public void startChronometer(View view)
    {
        ((Chronometer)findViewById(R.id.chronometer1)).start();
    }

    public void stopChronometer(View view)
    {
        ((Chronometer) findViewById(R.id.chronometer1)).stop();
    }

    public void resetChronometer(View view)
    {
        ((Chronometer) findViewById(R.id.chronometer1)).setBase(SystemClock.elapsedRealtime());
    }

    @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;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

我刚刚开始自学Android,这是简单Java的巨大跳跃。谢谢你的帮助!

2 个答案:

答案 0 :(得分:5)

我认为您忘记在Activity中设置布局

setContantView(R.layout.yourlayout);

onCreate(....)方法中以及View引用

之前

答案 1 :(得分:2)

试试这个..

您错过了setContentView(R.layout.layoutname);

在初始化Button之前添加,如下所示

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layoutname);
    Button startbutt = (Button) findViewById(R.id.startbutton);