2017-08-29 69 views
-4

這是我的片段代碼訪問MainActivity.class拋出一個錯誤

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    final MainActivity mainActivity = new MainActivity(); 
    // Inflate the layout for this fragment 
    View view = inflater.inflate(R.layout.encrypt_fragment, container, false); 

    btn_selectin = (Button)view.findViewById(R.id.btn_import); 
    btn_encrypt = (Button)view.findViewById(R.id.btn_encrypt); 

    btn_selectin.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      mainActivity.test(); 
     } 
    }); 

    btn_encrypt.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      mainActivity.test1(); 
     } 
    }); 

    return view; 
} 

我想訪問MainActivity.class方法

public void test(){ 
     textview = 1; 
     showFileChooser(); 
} 

    private void showFileChooser() { 
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
    intent.setType("*/*"); 
    intent.addCategory(Intent.CATEGORY_OPENABLE); 

    try { 
     startActivityForResult(
       Intent.createChooser(intent, "Select a File to Process"), FILE_SELECT_CODE); 
    } catch (android.content.ActivityNotFoundException ex) { 
     // Potentially direct the user to the Market with a Dialog 
     Toast.makeText(this, "Please install a File Manager.", Toast.LENGTH_SHORT).show(); 
    } 
} 

這段代碼實例文件瀏覽器

FATAL EXCEPTION:main 進程:com.plane.fusionencryp,PID:7551 java.la ng.RuntimeException:無法啓動活動ComponentInfo {com.plane.fusionencryp/com.plane.fusionencryp.MainActivity}:android.view.InflateException:二進制XML文件行#109:二進制XML文件行#109:錯誤的文件擴展類片段 android.app.ActivityThread.-wrap11(Unknown Source:0)在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) at android .app.ActivityThread $ H.handleMessage(ActivityThread.java:1593) at android.os.Handler.dispatchMessage(Handler.java:105) at android.os.Looper.loop(Looper.java:164) at android .app.ActivityThread.main(ActivityThread.java:6541) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote $ MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:767)

+0

替換'mainActivity.test();''到((MainActivity)getActivity())測試();' –

+0

不能使用的活動這樣。如果片段包含在主要活動中,則可以從片段中調用getActivity()並獲得該活動的一個實例。否則,無論是將該方法公開還是靜態以訪問該方法(這不是一個好主意,但它起作用),或者在Utils類中提取並在那裏調用它 –

回答

1

你在做什麼是創造的MainActivity Class 這是越來越活動實例的錯誤的方式一個新的實例。

這是你的問題。

final MainActivity mainActivity = new MainActivity();mainActivity.test();

但是你想要的是持有該片段在MainActivity的實例。所以在片段中,你可以這樣做。

((MainActivity)getActivity()).test(); 
0

您可以通過強制轉換獲得父級活動。

((MainAcitivty)getActivity).test() 

記住:MainActivity應該是你的片段父活動