0

我知道这是一个长镜头,但我尝试了很多解决方案,但都没有工作。 我试图从一个片段启动一个按钮被点击时的活动。Fragment启动活动抛出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的声明是错误的? 提前感谢任何帮助。

+1

显示您的清单.. – 2015-02-24 12:11:34

回答

2

我不知道为什么其他这样一个上升的ClassNotFoundException

es.uam.eps.dadm.SESSION是您在AndroidManifest.xml活动申报过程中添加动作名称。

从按钮上的活动单击使用操作来准备启动活动的意图。但是从片段尝试使用操作字符串,而不是一个类名包名加载类:

使用类名使用loadClass加载类:

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

谢谢,它的工作smootly! – esseara 2015-02-24 14:41:14

1

这似乎是你没有SESSION.java文件在你es.uam.eps.dadm.SESSION包文件夹或者您在manifest文件错过了它

相关问题