Android Fragment , view is not removed

2019-01-15 08:12发布

I have developed an app, in that I have a fragment transaction,

MainActivity contains Fragment View.

MainActivity have three Button on top of the screen, that remain same when we go this Activity to another Fragment, only MainActivity Fragment part change when we click out of three.

But, my problem is that when I move from the this MainActivity to Fragment when click on First-Button that is OK, but when I click on Second-Button, result is overwrite the screen with first Fragment to another Fragment.

it is in same Activity so , I can not remove Fragment through remove(fr).commit();

Because if I do that then it become non-clickable may be fragment remove so not response on click of next button.

overall result, It display both FirstFragment and NewFragment Screen , when i move to NewFragment how i remove the FirstFragment screen ?

In MainActivity three button have following code to change fragment :

Main Activity :

 public class MasterActivity extends Activity {                
   ImageView imgOne, imgTwo, imgThree;
   Fragment fr;                                              

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

    setContentView(R.layout.activity_master);             

    imgOne = (ImageView) findViewById(R.id.imgOne);       
    imgTwo = (ImageView) findViewById(R.id.imgTwo);       
    imgThree = (ImageView) findViewById(R.id.imgThree);


 imgOne.setOnClickListener(new View.OnClickListener() {                                                

       @Override                                                                                         
      public void onClick(View v) {                                                                     
     // TODO Auto-generated method stub                                                            
     fr = new FirstFragment();                                                                          

     FragmentManager fm = getFragmentManager();                                                    
     FragmentTransaction fragmentTransaction = fm.beginTransaction();                              
     fragmentTransaction.replace(R.id.fragment_place, fr);                                         
     fragmentTransaction.addToBackStack(null);                                                     
     //fragmentTransaction.remove(fr).commit();                                                    
     //getFragmentManager().beginTransaction().remove(fr).commit();                                  
     fragmentTransaction.commit();                                                                 
     }                                                                                                 
  });                                                                                                   

  imgTwo.setOnClickListener(new View.OnClickListener() {                                                

    @Override                                                                                         
    public void onClick(View v) {                                                                     
      // TODO Auto-generated method stub                                                            


     fr = new SecondFragment();                                                                           

     FragmentManager fm = getFragmentManager();                                                    
     FragmentTransaction fragmentTransaction = fm.beginTransaction();                              
     fragmentTransaction.replace(R.id.fragment_place, fr);                                         
     fragmentTransaction.addToBackStack(null);                                                     
     //fragmentTransaction.remove(fr).commit();                                                    
     // getFragmentManager().beginTransaction().remove(fr).commit();                                  
     fragmentTransaction.commit();                                                                 
    }                                                                                                 
 });    

its xml file like following :

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical" >

   <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="#000000"
    android:gravity="bottom"
    android:weightSum="3" >

    <ImageView
        android:id="@+id/imgOne"
        android:layout_width="0dp"
        android:layout_height="27dp"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:src="@drawable/img1" />

    <ImageView
        android:id="@+id/imgTwo"
        android:layout_width="0dp"
        android:layout_gravity="center"
        android:layout_height="27dp"
        android:layout_weight="1"
        android:src="@drawable/img2"/>
    <ImageView
        android:id="@+id/imgThree"
        android:layout_width="0dp"
        android:layout_gravity="center"
        android:layout_height="27dp"
        android:layout_weight="1"
        android:src="@drawable/img3" />
</LinearLayout>

 <fragment
     android:id="@+id/fragment_place"
    android:name="packagename.FirstFragment"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_weight="0.87"/>       
   <LinearLayout/>
 <LinearLayout/>

First Fragment :

public class FirstFragment extends Fragment {

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

        return r;
    }
}    

Second Fragment :

public class SecondFragment extends Fragment {

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

        return r;
    }
}    

But when click on one button Fragment button to another it display both first and second Fragment screens.

So how to resolve it and how to remove first view when second click?

I used this

fragmentTransaction.remove(fr).commit();

and this

getFragmentManager().beginTransaction().remove(fr).commit();

but it's not working.

7条回答
我命由我不由天
2楼-- · 2019-01-15 08:16

Fragment declared in the layout are treated differently by Android. Replace

 <fragment
     android:id="@+id/fragment_place"
     android:name="packagename.FirstFragment"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_weight="0.87"/> 

with a FrameLayout, or a subclass of ViewGroup of your choice, and handle all the transactions programmatically. The rest looks good to me

查看更多
Rolldiameter
3楼-- · 2019-01-15 08:20

when i move to NewFragment how i remove the first frament screen ?

well you can do that by hiding the old(first) Fragment source

getSupportFragmentManager().beginTransaction().hide(getSupportFragmentManager()
                      .findFragmentById(R.id.the_id_of_my_first_fragment));

you can also get him(the first fragment) back by the same approach source

getSupportFragmentManager().beginTransaction().show(getSupportFragmentManager()
                      .findFragmentById(R.id.the_id_of_my_first_fragment));

This approach buys flexibility and not re-changing your app's architecture, and logic, and also one line of work

im always late to a party (:

查看更多
SAY GOODBYE
4楼-- · 2019-01-15 08:25

Its better to use a viewGroup or a layout/FrameLayout instead of fragments (fragment navigations on button clicks in an Activity). Because fragments have their own lifecycle and fragment hold thier views or are not killed when you do fragment transition within an activity.

Although if you still want to go with fragment, first load a fragment of first button click and handle the click events of other two buttons by removing the fragment previously attached (Fragment attached to first button click).

This can be done by:

getSupportFragmentManager().beginTransaction().remove(YOUR_FIRST_FRAGMENT).commit();

and after this you can write a code to add fragment in this place, getFragmentManager().beginTransaction().replace(YOUR_FIRST_FRAGMENT, new YourSecondButtonFragment()).commit(); and hence this can be done for your third button click too, just need to change the fragment attached to second button.

I hope this will help you.

查看更多
虎瘦雄心在
5楼-- · 2019-01-15 08:28

Fragments that are hard coded in XML, cannot be replaced. Use the FramLayout as a fragment container instead.

in your XML replace

<fragment
     android:id="@+id/fragment_place"
     android:name="packagename.FirstFragment"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_weight="0.87"/>       
   <LinearLayout/>

with

<FrameLayout
     android:id="@+id/contentFragment"
     android:layout_width="match_parent"
     android:layout_height="0px"
     android:layout_weight="2" />

Now, Do follow the following code style to achieve your goal:

First set the onClickListeners to all the imageviews: like: imgOne.setOnClickListener(this);

            @Override
            public void onClick(View v) {
                Fragment fragment = null;
                switch (v.getId()) {
                    case R.id.imgOne:
                        fragment = new Fragment1();
                        break;
                    case R.id.imgTwo:
                        fragment = new Fragment2();
                        break;
                }
                if (fragment != null) {
                    FragmentManager fm = getSupportFragmentManager();
                    fm.beginTransaction().replace(R.id.contentFragment, fragment).commit();                        
                } else {
                    Log.e(LOG_TAG, "Error in fragment transaction.");
                }
            }

Hope this helps.

查看更多
孤傲高冷的网名
6楼-- · 2019-01-15 08:28

Make necessary changes. Replace your activity and xml with this. It should run solid if you do.

public class MasterActivity extends Activity {                
ImageView imgOne, imgTwo, imgThree;
Fragment fr;                                              

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

setContentView(R.layout.activity_master);             

imgOne = (ImageView) findViewById(R.id.imgOne);       
imgTwo = (ImageView) findViewById(R.id.imgTwo);       
imgThree = (ImageView) findViewById(R.id.imgThree);

getFragmentManager().beginTransaction().add(R.id.fragment_place, new FirstFragment()).commit();


imgOne.setOnClickListener(new View.OnClickListener() {                                                
    @Override                                                                                         
    public void onClick(View v) {    
        getFragmentManager().beginTransaction().replace(R.id.fragment_place, new FirstFragment()).commit();
    }                                                                                                 
});                                                                                                   

imgTwo.setOnClickListener(new View.OnClickListener() {
    @Override                                                                                         
    public void onClick(View v) {                                                                     
        getFragmentManager().beginTransaction().replace(R.id.fragment_place, new SecondFragment()).commit();                                                               
    }
});  

xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#000000"
android:gravity="bottom"
android:weightSum="3" >

<ImageView
    android:id="@+id/imgOne"
    android:layout_width="0dp"
    android:layout_height="27dp"
    android:layout_gravity="center"
    android:layout_weight="1"
    android:src="@drawable/img1" />

<ImageView
    android:id="@+id/imgTwo"
    android:layout_width="0dp"
    android:layout_gravity="center"
    android:layout_height="27dp"
    android:layout_weight="1"
    android:src="@drawable/img2"/>
<ImageView
    android:id="@+id/imgThree"
    android:layout_width="0dp"
    android:layout_gravity="center"
    android:layout_height="27dp"
    android:layout_weight="1"
    android:src="@drawable/img3" />
</LinearLayout>

 <FrameLayout
 android:id="@+id/fragment_place"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_weight="0.87"/>       
 <LinearLayout/>
 <LinearLayout/>
查看更多
爷、活的狠高调
7楼-- · 2019-01-15 08:35

copy and pest code in your button click event.

fr = new FirstFragment();  
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);                                         
fragmentTransaction.commit();

this is completed work.

查看更多
登录 后发表回答