Android Studio 开发 - 创建一个按钮来启动 activity

Android Studio Development - Creating a button to launch an activity

我是 Android 开发的新手 我需要一个按钮来调用 activity,同时让我的主要 activity 在按下后退按钮时可用。我已经用谷歌搜索了几天,但找不到可行的解决方案。当我在我的设备 (Samsung Galaxy S4) 上调试应用程序时,我收到一条错误消息,指出 "Unfortunately [App Name] has stopped."

这是我的清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.poweredbyite.phoenixcompanion" >

<application
    android:allowBackup="true"
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".Splash"
        android:label="@string/title_activity_splash" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
    </activity>
    <activity
        android:name=".ResistanceCalculator"
        android:label="@string/title_activity_resistance_calculator" >
    </activity>
</application>

还有我的MainActivity.java

 public class MainActivity extends ActionBarActivity {

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

        Button btnResCalc = (Button) findViewById(R.id.buttonResistanceCalculator);

        btnResCalc.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, ResistanceCalculator.class));
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

还有 Activity 我想打电话给:

public class ResistanceCalculator extends Activity {

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

        final Button go = (Button)findViewById(R.id.buttonGo);



        go.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Create references to fields
                final EditText inputMinCount = (EditText) findViewById(R.id.inputMinCount);
                final EditText inputMaxCount = (EditText) findViewById(R.id.inputMaxCount);
                final EditText inputMinOhms = (EditText) findViewById(R.id.inputMinOhms);
                final EditText inputMaxOhms = (EditText) findViewById(R.id.inputMaxOhms);
                final EditText inputResistance = (EditText) findViewById(R.id.inputResistance);

                inputMinCount.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

                    }

                    @Override
                    public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {

                        go.setEnabled(!inputMinCount.getText().toString().trim().isEmpty() &&
                                !inputMaxCount.getText().toString().trim().isEmpty() &&
                                !inputMinOhms.getText().toString().trim().isEmpty() &&
                                !inputMaxOhms.getText().toString().trim().isEmpty() &&
                                !inputResistance.getText().toString().trim().isEmpty());
                    }

                    @Override
                    public void afterTextChanged(Editable editable) {

                    }
                });

                // get values from input
                String sMinCount = inputMinCount.getText().toString();
                String sMaxCount = inputMaxCount.getText().toString();
                String sMinOhms = inputMinOhms.getText().toString();
                String sMaxOhms = inputMaxOhms.getText().toString();
                String sResistance = inputResistance.getText().toString();

                //validate
                String[] values = {sMaxCount, sMinCount, sMaxOhms, sMinOhms, sResistance};
                for (int i = 0; i < values.length - 1; i++) {
                    if (values[i].matches("")) {
                        toast("Values cannot be left empty");
                        return;
                    }
                }

                // Grab values from editText fields
                int min_c = Integer.parseInt(sMinCount);
                int max_c = Integer.parseInt(sMaxCount);
                float min_ohms = Float.parseFloat(sMinOhms);
                float max_ohms = Float.parseFloat(sMaxOhms);
                float med_ohms = (min_ohms + max_ohms) / 2;
                float resistance = Float.parseFloat(sResistance);

                if (isOdd(max_c) || isOdd(min_c)) {
                    toast("Counts must be even numbers");
                    return;
                }

                if (min_c > max_c) {
                    toast("Maximum count must be larger than minimum count");
                    return;
                }

                if (min_ohms > max_ohms) {
                    toast("Maximum resistance must be larger than minimum resistance");
                    return;
                }

                if (resistance > min_ohms && resistance < max_ohms) {
                    toast("Part already in range");
                    return;
                }

                int count = (int) Math.floor(med_ohms / (resistance / min_c));
                //toast(Integer.toString(count));

                for(int i=1; i<11; i++){
                    System.out.println("Count is: " + i);
                }

                if (count < min_c || count > max_c) {
                    toast("Input out of Range: Projected count: " + count);
                    return;
                }

                if (isOdd(count)) {
                    count--;
                }

                /*AlertDialog alertDialog = new AlertDialog.Builder(main.this).create();
                alertDialog.setTitle("Final Count");
                alertDialog.setMessage(Integer.toString(count));
                alertDialog.show();*/
                return;
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.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.

        switch (item.getItemId()) {

        }
        return super.onOptionsItemSelected(item);
    }

    boolean isOdd( int val ) { return (val & 0x01) != 0; }

    void toast(String msg) {
        Context context = getApplicationContext();
        int duration = Toast.LENGTH_SHORT;

        Toast.makeText(context, msg, duration).show();
    }

    void setFields(String part) {
        EditText inputMinCount = (EditText)findViewById(R.id.inputMinCount);
        EditText inputMaxCount = (EditText)findViewById(R.id.inputMaxCount);
        EditText inputMinOhms = (EditText)findViewById(R.id.inputMinOhms);
        EditText inputMaxOhms = (EditText)findViewById(R.id.inputMaxOhms);

        // set values
        inputMinCount.setText(Integer.toString(72));
        inputMaxCount.setText(Integer.toString(78));
        inputMinOhms.setText(Float.toString((float) 0.364));
        inputMaxOhms.setText(Float.toString((float) 0.382));
    }
    }

这是日志错误

01-29 02:21:16.016  30867-30867/com.poweredbyite.phoenixcompanion E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.poweredbyite.phoenixcompanion, PID: 30867
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.poweredbyite.phoenixcompanion/com.poweredbyite.phoenixcompanion.ResistanceCalculator}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
        at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
        at android.app.ActivityThread.access0(ActivityThread.java:161)

at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:157)
        at android.app.ActivityThread.main(ActivityThread.java:5356)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)

at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at com.poweredbyite.phoenixcompanion.ResistanceCalculator.onCreate(ResistanceCalculator.java:28)
        at android.app.Activity.performCreate(Activity.java:5426)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
            at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
            at android.app.ActivityThread.access0(ActivityThread.java:161)
 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5356)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
            at dalvik.system.NativeStart.main(Native Method)
01-29 02:21:48.508  30867-30867/com.poweredbyite.phoenixcompanion I/Process﹕ Sending signal. PID: 30867 SIG: 9

如有任何帮助,我们将不胜感激。

您的两个活动在 setContentView 中具有相同的布局。 (错误原因)

在清单中第二个 activity 的 activity 部分设置属性 android:parentActivityName=".MainActivity"。它将在您的第二个 activity.

按下后退按钮时打开您的主要 activity