java.lang.ClassCastException: com.example.harshitbahri.expensebook.MainActivity 无法转换为 com.example.harshitbahri.expensebook.EditorActivity

java.lang.ClassCastException: com.example.harshitbahri.expensebook.MainActivity cannot be cast to com.example.harshitbahri.expensebook.EditorActivity

我想通过单击 Button buttonExpense 来更改编辑器 activity 的 TextView,这也应该打开编辑器 activity 并在中显示结果值 EditText mAmountEditText

我收到 java.lang.ClassCastException,其中清楚地写着 MainActivity 不能转换为 EditorActivity

Calculator.java

package com.example.harshitbahri.expensebook;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Calculator extends android.support.v4.app.Fragment {
Button button0;
Button button1;
Button button2;
Button button3;
Button button4;
Button button5;
Button button6;
Button button7;
Button button8;
Button button9;
Button buttonAdd;
Button buttonSubstract;
Button buttonMul;
Button buttonDiv;
Button buttonClear;
Button buttonEqual;
Button buttonExpense;
String result;
String tmp;
String operator;
TextView resultTextView;
FragmentActivity fa2;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    fa2 = (FragmentActivity) super.getActivity();
    final View RootView= inflater.inflate(R.layout.activity_calculator, container, false);
    button0 = (Button)RootView.findViewById(R.id.button0);
    button1 = (Button)RootView.findViewById(R.id.button1);
    ......
    buttonAdd = (Button)RootView.findViewById(R.id.buttonAdd);
    buttonClear = (Button)RootView.findViewById(R.id.buttonClear);
    buttonSubstract = (Button)RootView.findViewById(R.id.buttonSub);
    buttonMul = (Button)RootView.findViewById(R.id.buttonMul);
    buttonDiv = (Button)RootView.findViewById(R.id.buttonDiv);
    buttonEqual = (Button)RootView.findViewById(R.id.buttonEqual);
    buttonExpense= (Button)RootView.findViewById(R.id.buttonExp);

    resultTextView = (TextView)RootView.findViewById(R.id.text_view_result);


    button0.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onNumberButtonClicked("0");
        }
    });
    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onNumberButtonClicked("1");
        }
    });
    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onNumberButtonClicked("2");
        }
    });
    button3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onNumberButtonClicked("3");
        }
    });
    button4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onNumberButtonClicked("4");
        }
    });
    button5.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onNumberButtonClicked("5");
        }
    });
    button6.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onNumberButtonClicked("6");
        }
    });
    button7.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onNumberButtonClicked("7");
        }
    });
    button8.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onNumberButtonClicked("8");
        }
    });
    button9.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onNumberButtonClicked("9");
        }
    });

    buttonClear.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onClearButtonClicked();
        }
    });
    buttonSubstract.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v){
            onOperatorButtonClicked("-");
        }
    });
    buttonAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onOperatorButtonClicked("+");
        }
    });
    buttonMul.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onOperatorButtonClicked("X");
        }
    });
    buttonDiv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onOperatorButtonClicked("/");
        }
    });
    buttonEqual.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onEqualButtonClicked();

        }
    });
    buttonExpense.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(fa2, EditorActivity.class);
            startActivity(intent);
            ((EditorActivity) getActivity()).updateGoldTextView(result);
            /*Intent intent = new Intent(fa2, EditorActivity.class);
            intent.putExtra(, result);
            final int result2=1;
            startActivityForResult(intent, result2);*/
        }


    });

    return RootView;

}




private void onEqualButtonClicked() {
    int res = 0;
    try {
        int number = Integer.valueOf(tmp);
        int number2 = Integer.valueOf(resultTextView.getText().toString());
        switch (operator) {
            case "+":
                res = number + number2;
                break;
            case "/":
                res = number / number2;
                break;
            case "-":
                res = number - number2;
                break;
            case "X":
                res = number * number2;
                break;
        }
        result = String.valueOf(res);
        resultTextView.setText(result);

    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

public void onOperatorButtonClicked(String operator) {
    ..
}

public void onClearButtonClicked() {
    ...
}

public void onNumberButtonClicked(String pos) {
    ..
}


public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}



}`

EditorActivity.java

package com.example.harshitbahri.expensebook;

import android.app.AlertDialog;
import android.app.LoaderManager;
...
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class EditorActivity extends AppCompatActivity implements
    LoaderManager.LoaderCallbacks<Cursor> {


private static final int EXISTING_EXPENSE_LOADER = 0;


private Uri mCurrentExpenseUri;

private EditText mAmountEditText;

private EditText mDescEditText;

private Spinner mCategorySpinner;



private String mCategory = ExpenseEntry.CATEGORY_GENERAL;


private View.OnTouchListener mTouchListener = new View.OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        mExpenseHasChanged = true;
        return false;
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_editor);
    // Examine the intent that was used to launch this activity,
    // in order to figure out if we're creating a new pet or editing an existing one.
    Intent intent = getIntent();
    mCurrentExpenseUri = intent.getData();

    // If the intent DOES NOT contain a pet content URI, then we know that we are
    // creating a new pet.
    if (mCurrentExpenseUri == null) {
        // This is a new pet, so change the app bar to say "Add a Pet"
        setTitle("Add Expense");

       yet.)
        invalidateOptionsMenu();
    } else {
        // Otherwise this is an existing pet, so change app bar to say "Edit Pet"
        setTitle("Edit Expense");


        getLoaderManager().initLoader(EXISTING_EXPENSE_LOADER, null, this);
    }
    mAmountEditText = (EditText) findViewById(R.id.exp_amount);
    mDescEditText = (EditText) findViewById(R.id.description);
    mCategorySpinner = (Spinner) findViewById(R.id.spinner_category);
.....

}
   ......

finish();

 }

public void updateGoldTextView(String goldAmount) {
    mAmountEditText.setText(goldAmount);
}


}

MainActivity.java

package com.example.harshitbahri.expensebook;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements  
Calculator.OnFragmentInteractionListener , 
Entries.OnFragmentInteractionListener,Info.OnFragmentInteractionListener{

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

    TabLayout tabLayout = (TabLayout)findViewById(R.id.tablayout);
    tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
    tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
    tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    final ViewPager viewPager = (ViewPager)findViewById(R.id.pager);
    final Pageradapter adapter = new Pageradapter(getSupportFragmentManager(),tabLayout.getTabCount());
    viewPager.setAdapter(adapter);
    viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    viewPager.setCurrentItem(1, false);

    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

}

@Override
public void onFragmentInteraction(Uri uri) {

}

}

您的片段是从 MainActivity 而不是 EditorActivity 加载的,因此 class 转换异常。如果你想在编辑器 activity 中预填充一些数据,你可以在意图中传递它(你在 onclick 侦听器上评论的代码)并在 EditorActivity 中检索并设置你的 UI 元素。 已编辑

buttonExpense.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(fa2, EditorActivity.class);
        intent.putExtra("result", result);
        startActivity(intent);
    }});

在您的 EditorActivity class 中,在创建时

String result=getIntent().getStringExtra("result")
updateGoldTextView(result)