2017-10-05 136 views
0

我需要當用戶觸摸的另一個FragmentTextView的以顯示Fragment。下面是我有:如何從另一片段的onTouch()內部替換片段?

public class FindPeopleHelpFragment extends Fragment { 

    public FindPeopleHelpFragment() { 
     // Required empty public constructor 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     View view = inflater.inflate(R.layout.fragment_find_people_help, container, false); 

     ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(R.string.find_people_help); 

     TextView welcome_home = (TextView) view.findViewById(R.id.find_people_help); 
     welcome_home.setOnTouchListener(new View.OnTouchListener() { 
      @Override 
      public boolean onTouch(View view, MotionEvent evt) { 
       if (evt.getAction() == MotionEvent.ACTION_DOWN) { 
        EditProfileFragment editProfileFragment = new EditProfileFragment(); 
        FragmentManager manager = getActivity().getSupportFragmentManager(); 
        manager.beginTransaction().replace(R.id.fragment_container, editProfileFragment, editProfileFragment.getTag()).commit(); 
       } 
       return true; 
      } 
     }); 

     // Inflate the layout for this fragment 
     return view; 
    } 
} 

的問題是,onTouch()返回boolean,但用Fragment的時候,我需要返回一個View。否則,我會得到以下結果。

10-05 15:00:51.057 25152-25152/wegrok.chiaramail.com E/AndroidRuntime: FATAL EXCEPTION: main 
                     Process: wegrok.chiaramail.com, PID: 25152 
                     java.lang.IllegalArgumentException: No view found for id 0x7f0f00b1 (wegrok.chiaramail.com:id/fragment_container) for fragment FindPeopleHelpFragment{c052157 #1 id=0x7f0f00b1} 

任何人都知道如何處理這個?

回答

0

您需要從Activity使這些Fragment交易。承載FragmentActivity應具有用於處理分段切換的公共功能,以便當您單擊Fragment1TextView時,將調用Activity的公共方法來創建Fragment切換。

所以,你可能會考慮接受Activity這樣。

public class YourActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_layout); 

     // The Fragment 1 will be loaded by default 
     switchToFragment1(); 
    } 

    public void switchToFragment1() { 
     getSupportFragmentManager().beginTransaction() 
       .replace(R.id.fragment_container, new Fragment1()).commit(); 
    } 

    public void switchToFragment2() { 
     getSupportFragmentManager().beginTransaction() 
       .replace(R.id.fragment_container, new Fragment2()).commit(); 
    } 
} 

現在從您的Fragment1,你需要到TextView實現一個onClick監聽器,這樣當點擊TextView時,Fragment1切換到Fragment2

textView.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     ((YourActivity) getActivity()).switchToFragment2(); 
    } 
});) 

希望有幫助。

+0

很高興知道這有幫助。 –