2016-04-26 22 views
0

Ich bin Neuling für Android-Entwicklung. Ich habe 3 Fragmente in tabview. BlankFragment, Map Fragment und RageComicListFragment. In der RageComicListFragment möchte ich das Fragment in RageComicDetailsFragment ändern, wenn der Benutzer auf eines der Elemente in der Liste klickt. Aber jetzt, wenn der Benutzer auf RageComicListFragment klickt und ein Bild erstellt, wird RageComicDetailsFragment auf dem Bildschirm angezeigt, aber das alte Fragment ist immer noch sichtbar. Ich suchte im Internet und fand einen Grund, der dieses Problem verursachen könnte. Ich denke, ich muss Fragmente dynamisch zur tabview hinzufügen. Aber ich kann in meiner Haupttätigkeit keinen richtigen Weg finden, dies zu tun. Mein Code ist so.Ersetzen von Fragment mit einem neuen Fragment in TabLayout

//MainActivity.java. 
public class MainActivity extends AppCompatActivity implements MapFragment.OnMarkerClicked, RageComicListFragment.OnRageComicSelected { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 

    // Get the ViewPager and set it's PagerAdapter so that it can display items 
    ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager); 
    PagerAdapter pagerAdapter 
      = new PagerAdapter(getSupportFragmentManager(), MainActivity.this); 
    viewPager.setAdapter(pagerAdapter); 

    // Give the TabLayout the ViewPager 
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout); 
    tabLayout.setupWithViewPager(viewPager); 

    // Iterate over all tabs and set the custom view 
    for (int i = 0; i < tabLayout.getTabCount(); i++) { 
     TabLayout.Tab tab = tabLayout.getTabAt(i); 
     tab.setCustomView(pagerAdapter.getTabView(i)); 
    } 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_main, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    int id = item.getItemId(); 

    if (id == R.id.action_settings) { 
     return true; 
    } 

    return super.onOptionsItemSelected(item); 
} 

class PagerAdapter extends FragmentPagerAdapter { 

    String tabTitles[] = new String[]{"Tab One", "Tab Two", "Tab Three",}; 
    Context context; 

    public PagerAdapter(FragmentManager fm, Context context) { 
     super(fm); 
     this.context = context; 
    } 

    @Override 
    public int getCount() { 
     return tabTitles.length; 
    } 

    @Override 
    public Fragment getItem(int position) { 

     switch (position) { 
      case 0: 
       return new BlankFragment(); 
      case 1: 
       return new MapFragment(); 
      case 2: 
       return new RageComicListFragment(); 
     } 

     return null; 
    } 

    @Override 
    public CharSequence getPageTitle(int position) { 
     // Generate title based on item position 
     return tabTitles[position]; 
    } 

    public View getTabView(int position) { 
     View tab = LayoutInflater.from(MainActivity.this).inflate(R.layout.custom_tab, null); 
     TextView tv = (TextView) tab.findViewById(R.id.custom_text); 
     tv.setText(tabTitles[position]); 
     return tab; 
    } 

} 

@Override 
public void OnMarkerClicked(int resId) { 
    Toast.makeText(this, "Hey, you selected " + resId + "!", Toast.LENGTH_SHORT).show(); 
    final BlankFragment2 detailsFragment 
      = BlankFragment2.newInstance(resId); 
    getSupportFragmentManager() 
      .beginTransaction() 
      .replace(R.id.main_layout, detailsFragment, "rageComicDetails") 
      .addToBackStack(null) 
      .commit(); 
} 

@Override 
public void onRageComicSelected(int imageResId, String name, String description, String url) { 
    final DetailsFragment detailsFragment = DetailsFragment.newInstance(imageResId, name, description, url); 
    RelativeLayout contentView = (RelativeLayout) this.findViewById(R.id.main_layout); 

    getSupportFragmentManager() 
      .beginTransaction() 
      .replace(contentView.getId(), detailsFragment, "rageComicDetails") 
      .addToBackStack(null) 
      .commit(); 

} 
} 

//RageComicListFragment.java 


public class RageComicListFragment extends Fragment { 

private int[] mImageResIds; 
private String[] mNames; 
private String[] mDescriptions; 
private String[] mUrls; 
private OnRageComicSelected mListener; 

public static RageComicListFragment newInstance() { 
    return new RageComicListFragment(); 
} 

public RageComicListFragment() { 
    // Required empty public constructor 
} 

@Override 
public void onAttach(Context context) { 
    if (context instanceof OnRageComicSelected) { 
     mListener = (OnRageComicSelected) context; 
    } else { 
     throw new ClassCastException(context.toString() + " must implement OnRageComicSelected."); 
    } 
    super.onAttach(context); 

    // Get rage face names and descriptions. 
    final Resources resources = context.getResources(); 
    mNames = resources.getStringArray(R.array.names); 
    mDescriptions = resources.getStringArray(R.array.descriptions); 
    mUrls = resources.getStringArray(R.array.urls); 

    // Get rage face images. 
    final TypedArray typedArray = resources.obtainTypedArray(R.array.images); 
    final int imageCount = mNames.length; 
    mImageResIds = new int[imageCount]; 
    for (int i = 0; i < imageCount; i++) { 
     mImageResIds[i] = typedArray.getResourceId(i, 0); 
    } 
    typedArray.recycle(); 
} 

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

    final Activity activity = getActivity(); 
    final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view); 
    recyclerView.setLayoutManager(new GridLayoutManager(activity, 2)); 
    recyclerView.setAdapter(new RageComicAdapter(activity)); 
    return view; 
} 

class RageComicAdapter extends RecyclerView.Adapter<ViewHolder> { 

    private LayoutInflater mLayoutInflater; 

    public RageComicAdapter(Context context) { 
     mLayoutInflater = LayoutInflater.from(context); 
    } 

    @Override 
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { 
     return new ViewHolder(mLayoutInflater 
       .inflate(R.layout.recycler_item_rage_comic, viewGroup, false)); 
    } 

    @Override 
    public void onBindViewHolder(ViewHolder viewHolder, final int position) { 
     final int imageResId = mImageResIds[position]; 
     final String name = mNames[position]; 
     final String description = mDescriptions[position]; 
     final String url = mUrls[position]; 
     viewHolder.setData(imageResId, name); 

     viewHolder.itemView.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       mListener.onRageComicSelected(imageResId, name, description, url); 
      } 
     }); 
    } 

    @Override 
    public int getItemCount() { 
     return mNames.length; 
    } 
} 

class ViewHolder extends RecyclerView.ViewHolder { 

    // Views 
    private ImageView mImageView; 
    private TextView mNameTextView; 

    private ViewHolder(View itemView) { 
     super(itemView); 

     // Get references to image and name. 
     mImageView = (ImageView) itemView.findViewById(R.id.comic_image); 
     mNameTextView = (TextView) itemView.findViewById(R.id.name); 
    } 

    private void setData(int imageResId, String name) { 
     mImageView.setImageResource(imageResId); 
     mNameTextView.setText(name); 
    } 
} 

public interface OnRageComicSelected { 

    void onRageComicSelected(int imageResId, String name, 
      String description, String url); 
} 
} 

//RageComicDetailsFragment.java 


public class RageComicDetailsFragment extends Fragment { 

private static final String ARGUMENT_IMAGE_RES_ID = "imageResId"; 
private static final String ARGUMENT_NAME = "name"; 
private static final String ARGUMENT_DESCRIPTION = "description"; 
private static final String ARGUMENT_URL = "url"; 

public static RageComicDetailsFragment newInstance(int imageResId, String name, String description, String url) { 

    final Bundle args = new Bundle(); 
    args.putInt(ARGUMENT_IMAGE_RES_ID, imageResId); 
    args.putString(ARGUMENT_NAME, name); 
    args.putString(ARGUMENT_DESCRIPTION, description); 
    args.putString(ARGUMENT_URL, url); 
    final RageComicDetailsFragment fragment = new RageComicDetailsFragment(); 
    fragment.setArguments(args); 
    return fragment; 
} 

public RageComicDetailsFragment() { 
} 

@Nullable 
@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    final View view = inflater.inflate(R.layout.fragment_rage_comic_details, container, false); 
    final ImageView imageView = (ImageView) view.findViewById(R.id.comic_image); 
    final TextView nameTextView = (TextView) view.findViewById(R.id.name); 
    final TextView descriptionTextView = (TextView) view.findViewById(R.id.description); 

    final Bundle args = getArguments(); 
    imageView.setImageResource(args.getInt(ARGUMENT_IMAGE_RES_ID)); 
    nameTextView.setText(args.getString(ARGUMENT_NAME)); 
    final String text = String.format(getString(R.string.description_format), args.getString(ARGUMENT_DESCRIPTION), args.getString(ARGUMENT_URL)); 
    descriptionTextView.setText(text); 
    return view; 
} 

} 

//content_main.xml 

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 
android:id="@+id/main_layout" 
xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:app="http://schemas.android.com/apk/res-auto" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
tools:context=".MainActivity"> 

<android.support.v7.widget.Toolbar 
    android:id="@+id/toolbar" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_alignParentTop="true" 
    android:background="?attr/colorPrimary" 
    android:elevation="6dp" 
    android:minHeight="?attr/actionBarSize" 
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" 
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/> 

<android.support.design.widget.TabLayout 
    android:id="@+id/tab_layout" 
    app:tabMode="fixed" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:background="?attr/colorPrimary" 
    android:elevation="6dp" 
    app:tabTextColor="#d3d3d3" 
    app:tabSelectedTextColor="#ffffff" 
    app:tabIndicatorColor="#ff00ff" 
    android:minHeight="?attr/actionBarSize" 
    android:layout_alignParentBottom="true" 
    /> 

<android.support.v4.view.ViewPager 
    android:id="@+id/viewpager" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_below="@id/toolbar"/> 
</RelativeLayout> 

//fragment_race_comic_list.xml 

<android.support.v7.widget.RecyclerView 
android:id="@+id/recycler_view" 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical"/> 


//fragment_race_comic_details.xml 
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:tools="http://schemas.android.com/tools" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:fillViewport="true" 
     tools:ignore="RtlHardcoded"> 

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:gravity="center" 
    android:orientation="vertical"> 

<TextView 
    android:id="@+id/name" 
    style="@style/TextAppearance.AppCompat.Title" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_marginBottom="0dp" 
    android:layout_marginTop="@dimen/rage_comic_name_margin_top" 
    tools:text="Freddie Mercury"/> 

<ImageView 
    android:id="@+id/comic_image" 
    android:layout_width="wrap_content" 
    android:layout_height="@dimen/rage_comic_image_size" 
    android:layout_marginBottom="@dimen/rage_comic_image_margin_vertical" 
    android:layout_marginTop="@dimen/rage_comic_image_margin_vertical" 
    android:adjustViewBounds="true" 
    android:contentDescription="@null" 
    android:scaleType="centerCrop" 
    android:src="@drawable/freddie_mercury"/> 

<TextView 
    android:id="@+id/description" 
    style="@style/TextAppearance.AppCompat.Body1" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
     android:layout_marginBottom="@dimen/rage_comic_description_margin_bottom" 
    android:layout_marginLeft="@dimen/rage_comic_description_margin_left" 
    android:layout_marginRight="@dimen/rage_comic_description_margin_right" 
    android:layout_marginTop="0dp" 
    android:autoLink="web" 
    tools:text="Freddie Mercury Rage Pose is a rage comic character made from a photo of deceased British musician and former lead vocalist for the rock band Queen Freddie Mercury. The image is typically used to indicate that an extraordinary feat has been accomplished, similar to the [email protected]# Yea illustration."/> 
</LinearLayout> 
+0

Jede Lösung, die Sie gefunden haben? – sumandas

+1

Ich fand, dass in diesem Fall verschachtelte Fragmente verwendet werden und ordnungsgemäß funktionierten. – starrystar

+0

Danke, es scheint, dass ich das Problem hatte, weil ich statische Fragmente in XML deklarierte, die durch das Entwerfen von Containern gelöst wurden. Prost! – sumandas

Antwort

0

Beim Ersetzen oder Hinzufügen Fragment nicht versuchen, die Eigenschaft addto Backstack und erstes Mal verwenden, um hinzuzufügen und beim nächsten Mal Gebrauch ersetzen, während Transaktion beispiele Durchführung

Fragment fragment= DetailImageFetch.newInstance(0,constants.BIG_IMAGE); 
     FragmentManager manager = getSupportFragmentManager(); 
     FragmentTransaction transaction = manager.beginTransaction(); 
     transaction.replace(R.id.container, fragment, "Frag"); 
     transaction.commit(); 
+0

Ich habe das versucht, aber immer noch alte Fragmentansicht auf dem Bildschirm hält. Danke für die Antwort :) – starrystar

+0

Sie haben ersetzen und legen Sie das Fragment in den Container R.id.container die ganze Zeit, und dieser Container ist Frame-Layout in Ihrer Aktivität. – Haroon

Verwandte Themen