我有两个单选按钮,如果选择了一个,我想更改Textview的值。我收到一个错误。单击单选按钮之一时,该应用程序停止工作。它在日志中给出此错误。

 logged error
>    /com.example.myapp.mttally E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.myapp.mttally, PID: 15125
    java.lang.IllegalStateException: Could not execute method of the activity
            at android.view.View$1.onClick(View.java:4025)
            at android.view.View.performClick(View.java:4785)
            at android.widget.CompoundButton.performClick(CompoundButton.java:120)
            at android.view.View$PerformClick.run(View.java:19884)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5343)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
     Caused by: java.lang.reflect.InvocationTargetException
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at android.view.View$1.onClick(View.java:4020)
            at android.view.View.performClick(View.java:4785)
            at android.widget.CompoundButton.performClick(CompoundButton.java:120)
            at android.view.View$PerformClick.run(View.java:19884)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5343)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at

    `com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
         Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference


..`




我在主文件上的Java代码是这个

package com.example.myapp.mttally;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
RadioButton lend;
RadioButton borrow;
TextView toFrom;

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


    TextView toFrom = (TextView) findViewById(R.id.toFrom);

    RadioButton lend = (RadioButton) findViewById(R.id.lend);
    RadioButton borrow = (RadioButton) findViewById(R.id.borrow);


}

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


public void onRadioButtonClicked(View view) {
    // Is the button now checked?

    Boolean checked = ((RadioButton) view).isChecked();

    // Check which radio button was clicked
    switch (view.getId()) {
        case R.id.lend:
            if (checked)
                toFrom.setText("   To");
                break;
        case R.id.borrow:
            if (checked)
                toFrom.setText("   From");
            break;
    }
}
}


这是我的xml文件

<RelativeLayout 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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
 tools:context=".MainActivity">

<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"

    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_marginTop="8dp"
    android:id="@+id/linearLayout">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:clickable="false"
        >

        <RadioGroup
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/radio_button1"
                android:id="@+id/lend"
                android:textSize="16dp"
                android:onClick="onRadioButtonClicked"
                />

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/radio_button2"
                android:id="@+id/borrow"
                android:textSize="16dp"
                android:onClick="onRadioButtonClicked"
                />
        </RadioGroup>
    </LinearLayout>


</LinearLayout>

<TextView
    android:layout_width="140dp"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:id="@+id/toFrom"
    android:layout_below="@+id/linearLayout"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="78dp" />

</RelativeLayout>

最佳答案

每次您编写诸如TextView toFromRadioButton lend或更通常的<type of variable> <variable name>之类的内容时,都在声明一个新变量。您可以在两个地方声明名为twoFromlendborrow的变量:一次在MainActivity类中,一次在onCreate方法中。因此,您的代码有两个不同的变量,都称为toFrom,两个变量是lend,两个变量是borrow

考虑lend变量。 lend变量的每个副本都有其自己的“作用域”,或它所在的代码区域。由于您在类本身中声明了第一个lend变量(不在任何方法中),因此其作用域是该类。您可以(通常)在类中任何地方的代码中使用它。

但是,第二个lend变量是导致此问题的原因。您已经在lend方法中声明了第二个onCreate变量。第二个lend是获取TextView对象的对象,然后onCreate方法完成执行后就不存在了。

因此,要解决此问题,您的onCreate应如下所示:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    toFrom = (TextView) findViewById(R.id.toFrom);
    lend = (RadioButton) findViewById(R.id.lend);
    borrow = (RadioButton) findViewById(R.id.borrow);
}


这样,当您获得对TextView的引用时,会将其保存在调用onRadioButtonClicked时仍将存在的变量中,而不是将其保存在几乎立即不复存在的第二个同名变量中。

07-24 16:03