用TabLayout中的新片段替换片段

时间:2016-04-26 16:52:01

标签: android android-fragments android-tablayout

我是android开发的新手。我在tabview中有3个片段。 BlankFragment,Map Fragment和RageComicListFragment。在RageComicListFragment中,当用户单击列表中的一个项目时,我想将片段更改为RageComicDetailsFragment。但是现在,当用户在RageComicListFragment上单击并显示图像时,RageComicDetailsFragment会出现在屏幕中,但旧片段仍然可见。我在互联网上搜索并找到可能导致此问题的一些原因。我想,我必须动态地将片段添加到tabview。但是我在主要活动中找不到合适的方法。我的代码是这样的。

//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 F!@# Yea illustration."/>
</LinearLayout>

1 个答案:

答案 0 :(得分:0)

替换或添加片段时不要使用属性addto backstack并且第一次尝试添加并在下次执行事务时使用replace e.g

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