如何从Java片段类调用kotlin片段

时间:2019-10-23 19:01:50

标签: android kotlin

这是ActivityUtil代码

        public class ActivityUtil {

        public static void addFragmentToActivity(@NonNull FragmentManager fragmentManager,
                                                 @NonNull Fragment fragment, int frameId, String fragmentTag) {

            //Fragment fragment1=fragmentManager.findFragmentByTag(fragmentTag);
            Preconditions.checkNotNull(fragmentManager);
            Preconditions.checkNotNull(fragment);
            FragmentTransaction transaction = fragmentManager.beginTransaction();

                transaction.replace(frameId, fragment, fragmentTag);
                transaction.addToBackStack(fragmentTag);
                transaction.commit();


        }
        }

这是主要的片段类,在这里我想使用kotlin片段(例如,CameraFragment类)添加/替换片段事务

我已经使用了Photofragment类,现在我想更改kotlin片段,如何实现这种情况?

    public class ExpLotBcodeFragment extends Fragment{
     public ExpLotBcodeFragment() {      
        }  
          @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            this.setRetainInstance(true);
              }
        @SuppressLint("ClickableViewAccessibility")
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {

            View root = inflater.inflate(R.layout.fragment_exp_lot_bcode, container, false);


            }


        @OnClick({R.id.scan})
        public void onClick(View view) {
                switch (view.getId()) {
                case R.id.scan:
                     //here i want to add kotlin call CameraFragment   class

                 //This is old call 
                ActivityUtil.addFragmentToActivity(getFragmentManager(), 
                photoFragment, R.id.frame_content, "photoFragment"); 

                      break;
    }

这是科特琳课

class CameraFragment : Fragment() {   

  companion object {

    fun newInstance(): CameraFragment {
      return CameraFragment ()
    }
  }


  override fun onCreateView(inflater: LayoutInflater, 
                            container: ViewGroup?, 
                            savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_exp_lot_bcode, container, false)
  }

}

我要从CameraFragment类添加/替换为ExpLotBcodeFragment类吗?

1 个答案:

答案 0 :(得分:0)

您必须致电CameraFragment.Companion.newInstance()或直接致电new CameraFragment()才能获得instance中的CameraFragment。 检查以下内容:

@OnClick({R.id.scan})
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.scan:
            CameraFragment cameraFragment = CameraFragment.Companion.newInstance();
            ActivityUtil.addFragmentToActivity(getFragmentManager(),
                    cameraFragment, R.id.frame_content, "cameraFragment");
            break;
    }
}