我是android開發的新手。我在tabview中有3個片段。 BlankFragment,Map Fragment和RageComicListFragment。在RageComicListFragment中,當用戶單擊列表中的某個項目時,我想將片段更改爲RageComicDetailsFragment。但是現在,當用戶點擊並在RageComicListFragment上顯示圖像時,RageComicDetailsFragment出現在屏幕上,但舊片段仍然可見。我在互聯網上搜索並找到可能導致此問題的一些原因。我想,我必須動態地將片段添加到tabview。但是我無法在我的主要活動中找到正確的方法來做到這一點。我的代碼是這樣的。用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>
任何解決方案你發現下一次使用更換? – sumandas
我發現在這種情況下使用嵌套片段並正常工作。 – starrystar
感謝看來我有問題,因爲在XML中聲明靜態片段,通過設計容器解決了這個問題。乾杯! – sumandas