這是我的片段代碼訪問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)
替換'mainActivity.test();''到((MainActivity)getActivity())測試();' –
不能使用的活動這樣。如果片段包含在主要活動中,則可以從片段中調用getActivity()並獲得該活動的一個實例。否則,無論是將該方法公開還是靜態以訪問該方法(這不是一個好主意,但它起作用),或者在Utils類中提取並在那裏調用它 –