从Fragment启动Activity会抛出ClassNotFoundException

时间:2015-02-24 12:10:37

标签: java android android-fragments classloader 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的声明是错的? 在此先感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

  

我不知道为什么另一种方式会引发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>"));

答案 1 :(得分:1)

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

相关问题