如何从另一个片段的onTouch()中替换片段?

时间:2017-10-05 22:32:07

标签: android android-fragments ontouch

当用户触摸另一个Fragment的{​​{1}}时,我需要显示TextView。这就是我所拥有的:

Fragment

问题是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

任何人都知道如何处理这个问题?

1 个答案:

答案 0 :(得分:0)

您需要从Fragment进行这些Activity次交易。托管Activity的{​​{1}}应该有一个用于处理片段切换的公共函数,以便在点击Fragment的{​​{1}}时,TextView的公共方法将调用1}}来进行Fragment1切换。

所以你可能会考虑像这样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(); } } 中实施onClick侦听器,以便在点击Fragment1时,TextView切换到{{1} }}。

TextView

希望有所帮助。