我正在使用TabLayout显示三个选项卡,并选择每个调用FragmentTransaction.replace方法。现在我的问题是前两个片段被正确替换但是第三个片段特别是没有被替换,虽然我调试并发现第三个片段的所有相应方法都被调用并且没有错误。现在我的智慧,请帮助!!。
这是我主要活动的onCreate()方法中的代码,我将显示三个标签。
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Home"));
tabLayout.addTab(tabLayout.newTab().setText("Explore"));
tabLayout.addTab(tabLayout.newTab().setText("Me"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
HomeTabFragment htf = new HomeTabFragment();
transaction.replace(R.id.tab_content_fragment, htf);
transaction.commit();
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
int position = tab.getPosition();
if (position == 0) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
HomeTabFragment htf = new HomeTabFragment();
transaction.replace(R.id.tab_content_fragment, htf);
//transaction.commitAllowingStateLoss();
transaction.addToBackStack(null);
transaction.commit();
} else if (position == 1) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
ItemListFragment ilf = new ItemListFragment();
transaction.replace(R.id.tab_content_fragment, ilf);
//transaction.commitAllowingStateLoss();
transaction.addToBackStack(null);
transaction.commit();
} else if (position == 2) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
MeTabFragment meTabFragment = new MeTabFragment();
transaction.replace(R.id.tab_content_fragment, meTabFragment);
transaction.addToBackStack(null);
transaction.commit();
//transaction.commitAllowingStateLoss();
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
这是我的MeTabFragment ......
public class MeTabFragment extends Fragment implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
private DisplayDensity display;
private int profilePicSizeInPx;
private final float percentageOfScreenHeightOfProfilePic = 0.15f;
private CheckInternetConnection connection;
private ImageView userProfilePic;
private TextView userName;
private ProgressBar profilePicPB;
private String personPhotoUrl;
private String PROFILE_PIC_SIZE = "400";
private SharedPreferences sPrefs;
private SharedPreferences.Editor editor;
ListView m_homeOfferLV = null;
MeTabAdapter m_meTabAdapter = null;
ArrayList<MeData> m_ArrayList;
private GoogleApiClient mGoogleApiClient;
// Creating a listener interface to communicate back to the calling activity
//OnLogOutButtonClickListener mCallback;
private Analytics analytics;
private Tracker t;
// Container Activity must implement this interface
public static MeTabFragment newInstance() {
MeTabFragment fragment = new MeTabFragment();
//fragment.setArguments(bundle);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
analytics = new Analytics(getActivity(),getActivity().getString(R.string.MeTabFragment));
t = analytics.getTrackerInstance();
}
@Override
public void onResume() {
super.onResume();
if(Analytics.analytics_enabled && Analytics.lastTabStripPositionValue==2)
t.send(new HitBuilders.ScreenViewBuilder().build());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
sPrefs = getActivity().getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
editor = sPrefs.edit();
mGoogleApiClient = ApiClientGoogle.mApiClientGoogle;
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
connection = new CheckInternetConnection(getActivity());
display = new DisplayDensity(getActivity());
profilePicSizeInPx = (int) (percentageOfScreenHeightOfProfilePic * (float) display.getScreenHeightInPixels());
//mAnalytics = new Analytics(getActivity(),"Me");
return inflater.inflate(R.layout.fragment_me_tab, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
m_homeOfferLV = (ListView) view.findViewById(R.id.me_tab_list_view);
userProfilePic = (ImageView) view.findViewById(R.id.profile_pic);
userName = (TextView) view.findViewById(R.id.user_name_tv);
userProfilePic.getLayoutParams().height = profilePicSizeInPx;
userProfilePic.getLayoutParams().width = profilePicSizeInPx;
tracker.send(new HitBuilders.EventBuilder()
.setCategory("MeScreen")
.setAction("click")
.setLabel("Me")
.build());*/
userName.setText(sPrefs.getString(getString(R.string.user_name), "User Name"));
personPhotoUrl = sPrefs.getString(getString(R.string.user_profile_pic_url), null);
if (sPrefs.getBoolean(getString(R.string.is_google_logged_in), false) && personPhotoUrl != null) {
personPhotoUrl = personPhotoUrl.substring(0, personPhotoUrl.length() - 2) + PROFILE_PIC_SIZE;
}
//if user is connected to internet and has profile pic url then fetch the url and show his profile pic.
if (personPhotoUrl != null && connection.isConnectedToInternet()) {
//show progress bar till the image is fetched and don't show the profile pic for now.
profilePicPB.setVisibility(View.VISIBLE);
new LoadProfileImage(userProfilePic).execute(personPhotoUrl);
} else {
//show default pic only and set progress bar visiblity to null.
Log.v("Debug", "Profile pic url is null");
profilePicPB.setVisibility(View.INVISIBLE);
}
m_ArrayList = new ArrayList<MeData>();
MeData meData = new MeData();
meData.mPageRank = 1;
meData.mTitle = "My Collections";
meData.mDetail = "";
m_ArrayList.add(meData);
meData = new MeData();
meData.mPageRank = 2;
meData.mTitle = "My Offers";
meData.mDetail = "";
m_ArrayList.add(meData);
meData = new MeData();
meData.mPageRank = 3;
meData.mTitle = "My Store List";
meData.mDetail = "";
m_ArrayList.add(meData);
meData = new MeData();
meData.mPageRank = 4;
meData.mTitle = "Settings";
meData.mDetail="";
m_ArrayList.add(meData);
//adding an empty item in the list to draw the bottom border.
meData = new MeData();
meData.mPageRank = 5;
meData.mTitle = "";
meData.mDetail="";
m_ArrayList.add(meData);
m_meTabAdapter = new MeTabAdapter(getActivity(), R.layout.fragment_me_tab_template, m_ArrayList);
m_homeOfferLV.setAdapter(m_meTabAdapter);
m_homeOfferLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (m_ArrayList.get(position).mPageRank == 1) {
Intent i = new Intent(getActivity(), MyProductsActivity.class);
getActivity().startActivity(i);
} else if (m_ArrayList.get(position).mPageRank == 2) {
Intent i = new Intent(getActivity(), MyOffersActivity.class);
getActivity().startActivity(i);
} else if (m_ArrayList.get(position).mPageRank == 3) {
if (connection.isConnectedToInternet()) {
Intent i = new Intent(getActivity(), MyStoresActivity.class);
getActivity().startActivity(i);
} else {
Toast.makeText(getActivity(), getActivity().getString(R.string.check_internet_connection_try_again), Toast.LENGTH_SHORT).show();
}
}else if (m_ArrayList.get(position).mPageRank ==4){
Intent i = new Intent(getActivity(),SettingsActivity.class);
getActivity().startActivity(i);
}
}
});
m_homeOfferLV.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
v.getParent().requestDisallowInterceptTouchEvent(true);
return false;
}
});
setListViewHeightBasedOnChildren(m_homeOfferLV);
}
//***************************************
// GOOGLE CONNECTION METHODS
//***********************************
@Override
public void onConnected(Bundle bundle) {
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public LoadProfileImage(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
profilePicPB.setVisibility(View.GONE);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
}
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null)
return;
int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.UNSPECIFIED);
int totalHeight = 0;
View view = null;
for (int i = 0; i < listAdapter.getCount(); i++) {
view = listAdapter.getView(i, view, listView);
if (i == 0)
view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, listView.getLayoutParams().WRAP_CONTENT));
view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
totalHeight += view.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
listView.requestLayout();
}
编辑: 包含第3个片段的布局
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="0dp"
android:fillViewport="true"
android:gravity="top">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="@drawable/customborder">
<ImageView
android:id="@+id/profile_pic"
android:layout_width="400px"
android:layout_height="400px"
android:layout_marginBottom="3dp"
android:background="@drawable/com_facebook_profile_picture_blank_square" />
<ProgressBar
android:id="@+id/profile_pic_progress_bar"
style="@android:style/Widget.ProgressBar.Small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</FrameLayout>
<TextView
android:id="@+id/user_name_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="5dp"
android:textSize="15sp"
android:textStyle="bold" />
<ListView
android:id="@+id/me_tab_list_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:divider="@null"
android:dividerHeight="0dp" />
</LinearLayout>
答案 0 :(得分:0)
由于您的代码对于每个片段都是相同的,因此在第三个片段的布局中查找原因 首先更改根ScrollView参数,如下所示:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scroll_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true" >
我认为原始的android:layout_height="0dp"
未按预期处理,因此片段实际上已被充气并添加,但您只是看不到它。