如何setOnlick Listener to fragment in fragment

时间:2015-07-28 09:00:09

标签: android android-fragments

我在fragment1中有按钮。我想点击这个按钮并用fragment2替换fragment1,但是当我尝试运行它时我的应用仍然关闭

这是我在fragment1中的代码

   @Override
   public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

      View rootView = inflater.inflate(R.layout.layout_menu, container, false);

     // gallery = (Gallery) rootView.findViewById(android.R.id.list);
      //gallery.setAdapter(new ItemAdapter(generateData(), getActivity()));
      Button button = (Button) rootView.findViewById(R.id.imageButtonAll);
      button.setOnClickListener(new View.OnClickListener() {
          @Override
        public void onClick(View v) {
              HomeFragment homeFragment = new HomeFragment();
              FragmentTransaction transaction = getFragmentManager().beginTransaction();
              transaction.replace(R.id.frame_container, homeFragment);
              transaction.commit();

        }       

        });     

      return rootView;       

        }  

  } 

2 个答案:

答案 0 :(得分:2)

你无法从另一个片段中打开一个片段。 因此,您必须将代码从onClick移动到您的活动并在那里运行。

在您的活动中(假设其主要活动):

public void openMyFragment(){
    HomeFragment homeFragment = new HomeFragment();
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.replace(R.id.frame_container, homeFragment);
    transaction.commit();
}

然后,在你的片段中添加这个onClick:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        ((MainActivity) getActivity()).openMyFragement();
    }

});

答案 1 :(得分:1)

问题是您正在尝试替换您正在膨胀的视图中不存在的视图。您必须从FragmentActivity切换这些片段,FragmentActivity的contentview包含您要替换的布局。

<强> MainActivity:

class MainActivity extends FragmentActivity {
    public Fragment frag1;
    public Fragment frag2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...

        frag1 = new Frag1();
        frag2 = new Frag2();
        //assumption to switch to frag 1 immediately
        switchToFragment(R.id.frame_container, homeFragment);

        ...
    }

    /** Switch UI to the given fragment (example) */
    void switchToFragment(Fragment newFrag) {
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, newFrag)
            .commitAllowingStateLoss();
        currentFragment = newFrag;
    }
}

<强>片段:

....

final Activity activity = getActivity();
button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            about.setTextColor(Color.WHITE);

            if(activity instanceof MainActivity) {
                ((MainActivity) activity).switchToFragment(((MainActivity) activity).frag1));
            }
        }
    });

...