2017-03-04 55 views
2

我想在单击FloatingActionButton时调用片段方法。
我正在使用Butterknife。在活动中调用片段方法会导致空指针异常

错误:

PID: 9956 java.lang.NullPointerException: Attempt to invoke virtual method 'void com.fischerdaniel.testapp.FirstFragment.setTvText()' on a null object reference

的MainActicity的一部分:

@OnClick({R.id.fab_one, R.id.fab_two, R.id.fab_three}) public void test(View view) { 
     switch (view.getId()) { 
      case R.id.fab_three: 
       FirstFragment firstFragment = (FirstFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_first); 
       firstFragment.setTvText(); 
       break; 
      default: 
       break; 
     } 
    } 

片段的一部分:

@BindView(R.id.et_one) EditText etOne; 
    @BindView(R.id.et_two) EditText etTwo; 
    @BindView(R.id.tv_one) TextView tvOne; 
    @BindView(R.id.tv_two) TextView tvTwo; 

    private Unbinder unbinder; 

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View view = inflater.inflate(R.layout.fragment_first, container, false); 
     unbinder = ButterKnife.bind(this, view); 

     return view; 
    } 

    protected void setTvText() { 
     tvOne.setText(etOne.getText()); 
     tvTwo.setText(etTwo.getText()); 
    } 
+0

你调用它通过refrence –

回答

0
public void onMenuItemClick(View clickedView, int position) { 
    switch (position){ 
     case 1: 
      fragmentChanger("Notifications",new notifyFragment()); 
      break; 
     case 2: 
      fragmentChanger("QR Code",new qrFragment()); 
      break; 
     case 3: 
      fragmentChanger("User ID",new MainFragment()); 
      break; 
     case 4: 
      fragmentChanger("Settings",new settingsFragment()); 
      break; 
     default: 
      Toast.makeText(this, "Clicked on position: " + position, Toast.LENGTH_SHORT).show(); 
      break; 
    } 
} 

//function that does the trasaction when a fragment object is passed 
//R.id.container is my default frame 
public void fragmentChanger(String title, Object expectedFragment){ 
    // mToolBarTextView.setText(title); 
    transaction = fragmentManager.beginTransaction(); 
    transaction.replace(R.id.container, (Fragment) expectedFragment); 
    transaction.addToBackStack(null); 
    transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); 
    transaction.commit(); 
} 
+1

看起来详细,但可以使用一些说明文字。请参阅[我如何写出一个好的答案?](http://stackoverflow.com/help/how-to-answer)。 – Cheticamp

+0

该片段位于viewpager中 –

0

请参阅此链接:findFragmentById always returns null

当您创建片段,使用方法:

add(int id, Fragment fragment, String tag) 

,然后让你的片段,使用:

findFragmentByTag(String tag) 
+0

该片段位于viewpager中 –

相关问题