从Fragment启动Activity引发ClassNotFoundException



我知道这是一个很长的机会,但我尝试了很多解决方案,但都没有成功。当点击按钮时,我正试图从片段中启动一个活动。

Fragment.java

public class Lev1 extends Fragment implements OnClickListener {
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View v = inflater.inflate(R.layout.lev1, null);     
        Button button1= (Button) v.findViewById(R.id.level1);
        button1.setOnClickListener(this);           
        return v;
    }
    @Override
    public void onClick(View v) {
        try {
            Intent intent = new Intent(getActivity(), getActivity().getClassLoader().loadClass("es.uam.eps.dadm.SESSION"));
            startActivity(intent);
        }
        catch(ClassNotFoundException e) {
            //to handle carefully
            Toast.makeText(context, "Class not found",
                     Toast.LENGTH_SHORT).show();
        }
    } 

Fragment.xml

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout        
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button
        android:id="@+id/level1"            
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_margin="8dp"
        android:background="@drawable/fr1"
         />        
</LinearLayout>

我想这不是一个包的问题,因为如果我使用一个活动而不是一个片段,那么以下操作会很好:

Button button1= (Button)findViewById(R.id.level1);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
        startActivity(new Intent("es.uam.eps.dadm.SESSION"));
}

所以我不知道为什么当我尝试加载SESSION类时,另一种方式会引发ClassNotFoundException。也许intent的声明是错误的?提前感谢您的帮助。

我不知道为什么另一种方式会产生ClassNotFoundException

es.uam.eps.dadm.SESSION是您在AndroidManifest.xml中的活动声明期间添加的操作名称。

在按钮上的"活动"中,单击使用操作为启动"活动"准备Intent。但来自Fragment尝试使用操作字符串而不是包名为的类名加载类

使用类名使用loadClass:加载类

Intent intent = new Intent(getActivity(), getActivity().getClassLoader().
                                      loadClass("es.uam.eps.dadm.<Class_Name>"));

您的es.uam.eps.dadm.SESSION包文件夹中似乎没有SESSION.java文件,或者您在清单文件中错过了它

最新更新