转到片段

时间:2016-06-01 07:12:37

标签: java android xml android-fragments

我真的很抱歉这个愚蠢的问题,但我一直在读各种各样的东西,但似乎无法通过我厚厚的头骨。我真的很绝望,所以请耐心等待。

所以我得到了一个充满文字的片段,比如fragment_chapter_1.xml。其中一个文本需要进一步解释,所以我想在单击文本(Copyright Act (Amendment) 1997)时(在xml布局中没有设置可点击),它会转到fragment_explain_law.xml

fragment_explain_law.xml有一个TextView explainLaw,它将获得setText(在ExplainLawFragment.java中)自己对fragment_chapter_1.xml中点击的文字的解释。我使用这种方式是因为如果点击其他文本,它将重复使用相同的fragment_explain_law.xml,但explainLaw将设置为不同的解释。

这是代码。

  1. Chapter1Fragment.java中,它会查看fragment_chapter_one.xmllaw1Copyright Act (Amendment) 1997的ID。

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.fragment_chapter_1, container, false);
    
    law1 = (TextView) rootView.findViewById(R.id.law1);
    law1.setOnClickListener(this);
    
    // Inflate the layout for this fragment
    return rootView;
    }
    
  2. 点击law1后,系统会显示fragment_explain_law.xml。为此,我转到ExplainLawFragment.java(我做得对吗?)。

    @Override
    public void onClick(View v) {
    // when law1 till law11 clicked, go to ExplainLawFragment.java to view fragment_explain_law.xml
    Fragment fragment = null;
    String title = null;
    
    switch (v.getId()) {
        case R.id.law1:
            // view explainLaw
            fragment = new ExplainLawFragment();
            title = "Copyright Act (Amendment) 1997";
            break;
    }
    

    }

  3. ExplainLawFragment.java

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_explain_law, container, false);
    explainLaw = (TextView) rootView.findViewById(R.id.explainLaw);
    explainLaw.setText("blahblahblah");
    // Inflate the layout for this fragment
    return rootView;
    }
    
  4. 结果:什么都没发生。

    点击law1V/SettingsInterface: from settings cache , name = sound_effects_enabled , value = 1

    时的Logcat

    我哪里出错了?请帮忙。

1 个答案:

答案 0 :(得分:2)

您可以像这样调用第二个片段....

@Override
public void onClick(View v) {
// when law1 till law11 clicked, go to ExplainLawFragment.java to view fragment_explain_law.xml
Fragment fragment = null;
String title = null;

switch (v.getId()) {
case R.id.law1:
    // view explainLaw
    fragment = new ExplainLawFragment();
    title = "Copyright Act (Amendment) 1997";
 FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
    break;

}

希望这会对你有帮助..