【发布时间】:2015-03-28 03:17:20
【问题描述】:
andorid 新手,我坚持尝试在 Fragment 中引用“this”。
使用 Navigation Draw 模板项目,它有一个用于主 Fragment 的静态类。
我正在尝试集成 zxing 条码扫描器,它需要对 Fragment 的引用作为意图,但是在使用 this 时出错,说它无法解析构造函数。
我认为由于类的静态性质,但不知道如何解决它。
我试过this和PlaceholderFragment.this......
public static class PlaceholderFragment extends Fragment implements Button.OnClickListener {
private Button scanBtn;
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
scanBtn = (Button) view.findViewById(R.id.scan_btn);
scanBtn.setOnClickListener(this);
return view;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
@Override
public void onClick(View v) {
// `this` here errors saying it cant find the constructor.
// Im trying to pass a reference to this fragment...
IntentIntegrator integrator = new IntentIntegrator( this );
integrator.initiateScan();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
Toast.makeText(getActivity().getApplicationContext(), "You scanned", Toast.LENGTH_LONG).show();
}
}
}
【问题讨论】:
-
打赌你的 Fragment 支持 Fragment 而 ZXing 使用系统 Fragment,反之亦然。
-
检查您的导入并查找 android.support.v4.app.Fragment
-
你是个天才。永远不会解决这个问题。现在像魅力一样工作,我将主应用程序移动到使用 app.Fragments。谢谢!
-
欢迎来到 Android 框架和愚蠢的碎片化。我将其发布为答案:D
标签: java android android-fragments zxing