如何为每个imageView制作片段

时间:2016-07-10 23:18:26

标签: android android-fragments

我有这个

enter image description here

widnowManger这个没有布局的4图像中 我只是想知道当我点击它时如何为每个imageView添加片段 并且它将在service而不是活动我是初学者所以任何人都可以告诉我在点击某些图片时添加片段的方式并在点击时传递图片keyid在它上片段,当点击另一个imageView我不想破坏最后一个片段,在最后我不想为每个图像视图制作4个片段,因为我不知道我有多少imageView

1 个答案:

答案 0 :(得分:1)

试试这个!使用隐藏() show()

imageview.setOnClickListener(this);
//……

@Override
public void onClick(View v) {

    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.add(fragment1,"f1");
    transaction.add(fragment2,"f2");
    transaction.add(fragment3,"f3");
    transaction.add(fragment4,"f4");

    switch (v.getId()){
             case R.id.imageView1:
                 transaction.show(fragment1);
                 if(lastFragment!=null)
                     transaction.hide(lastFragment);
                 lastFragment=fragment1;
                 break;
             case R.id.imageView2:
                 transaction.show(fragment2);
                 if(lastFragment!=null)
                     transaction.hide(lastFragment);
                 lastFragment=fragment2;

                 break;
             case R.id.imageView3:
                 transaction.show(fragment3);
                 if(lastFragment!=null)
                     transaction.hide(lastFragment);
                 lastFragment=fragment3;
                 break;
             case R.id.imageView4:
                 transaction.show(fragment4);
                 if(lastFragment!=null)
                     transaction.hide(lastFragment);
                 lastFragment=fragment4;
                 break;
         }
    transaction.commit();

}