1

我的活动中有多个片段。它应该在启动时只启动第一个片段。它也初始化第二个。此外,我通过滑动动作从一个片段移动到另一个片段。当我从第一个片段滑动到下一个片段时,也会启动该行中的第三个片段。

我必须从服务器获取数据,然后填充该片段。网络请求已发送,但不是针对我要发送的请求,而是针对它旁边的片段。

请建议我在哪里弄错了...

提前致谢。

以下是代码:

注意:正在使用示例代码,请考虑其他片段及其布局与Fragment1.

主要活动

package com.example.fragments;


import java.util.List;
import java.util.Vector;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.HorizontalScrollView;
import android.widget.TableLayout;
import android.widget.TextView;

public class MainActivity extends FragmentActivity implements OnClickListener {

/**
 * Constants for tabs
 */
public static final int TAB_SCORES      = 0;
public static final int TAB_PAVILION    = 1;
public static final int TAB_FRIENDS     = 2;
public static final int TAB_OTHER       = 3;
public static final int TAB_CROWD       = 4;
public static final int TAB_SOCIAL      = 5;

private List<Fragment> fragments=null;
private FragmentsAdaptor _adapter;

/** The context object. */
public static Object contextObject = null;

private TableLayout scoresTab, socialTab, pavilionTab, friendsTab, othersTab, crowdTab;

private TextView mScoresTv, mPavilionTv, mFriendsTv, mOtherTv, mCrowdTv, mSocialTv;

private HorizontalScrollView tabsLayout;
private int fragmentPosition;

public ViewPager mViewPager;

private int moveRight = 100;

@Override
protected void onStart() {
    super.onStart();
}

/**
/* (non-Javadoc)
 * @see android.app.Activity#onCreate(android.os.Bundle)
 */
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.activity_main);
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    mViewPager = (ViewPager)findViewById(R.id.viewPager);

    setViews();
    addListeners();
    setTab();

    addFragments();
}

private void setViews() {
    scoresTab   = (TableLayout)findViewById(R.id.scores_tab);
    pavilionTab = (TableLayout)findViewById(R.id.pavilion_tab);
    friendsTab  = (TableLayout)findViewById(R.id.friends_tab);
    othersTab   = (TableLayout)findViewById(R.id.others_tab);
    crowdTab    = ((TableLayout)findViewById(R.id.crowd_tab));
    socialTab   = (TableLayout)findViewById(R.id.social_tab);

    tabsLayout = (HorizontalScrollView)findViewById(R.id.tabs_layout);

    mScoresTv   = (TextView)findViewById(R.id.scores);
    mPavilionTv = (TextView)findViewById(R.id.pavilion);
    mFriendsTv  = (TextView)findViewById(R.id.friends);
    mOtherTv    = (TextView)findViewById(R.id.other);
    mCrowdTv    = (TextView)findViewById(R.id.crowd);
    mSocialTv   = (TextView)findViewById(R.id.social);

}

private void addListeners() {
    mScoresTv.setOnClickListener(MainActivity.this);
    mPavilionTv.setOnClickListener(MainActivity.this);
    mFriendsTv.setOnClickListener(MainActivity.this);
    mOtherTv.setOnClickListener(MainActivity.this);
    mCrowdTv.setOnClickListener(MainActivity.this);
    mSocialTv.setOnClickListener(MainActivity.this);

}

private void addFragments(){
    fragments = new Vector<Fragment>();
    fragments.add(new Fragment1(this));
    fragments.add(new Fragment2(this));
    fragments.add(new Fragment3(this));
    fragments.add(new Fragment4(this));
    fragments.add(new Fragment5(this));
    fragments.add(new Fragment6(this));

    this._adapter  = new FragmentsAdaptor(super.getSupportFragmentManager(), fragments);
    mViewPager.setAdapter(this._adapter);
}

@Override
public void onClick(View v){
    onTabsClick(v);
}

public void onTabsClick(View v) {
    //reset layout of all the text views
    resetlayouts();

    if(v == mScoresTv) {
        if(mViewPager.getCurrentItem() != TAB_SCORES) {
            changeTab(TAB_SCORES);
                scoresTab.setBackgroundColor(getResources().getColor(android.R.color.black));
                mScoresTv.setTextColor(getResources().getColor(android.R.color.white));
        }
    } else if(v == mCrowdTv) {
        if(mViewPager.getCurrentItem() != TAB_CROWD) {
            changeTab(TAB_CROWD);
            crowdTab.setBackgroundColor(getResources().getColor(android.R.color.black));
            mCrowdTv.setTextColor(getResources().getColor(android.R.color.white));
        }
    } else if(v == mFriendsTv) {
        if(mViewPager.getCurrentItem() != TAB_FRIENDS) {
            changeTab(TAB_FRIENDS);
            friendsTab.setBackgroundColor(getResources().getColor(android.R.color.black));
            mFriendsTv.setTextColor(getResources().getColor(android.R.color.white));
        }
    } else if(v == mOtherTv) {
        if(mViewPager.getCurrentItem() != TAB_OTHER) {
            changeTab(TAB_OTHER);
            othersTab.setBackgroundColor(getResources().getColor(android.R.color.black));
            mOtherTv.setTextColor(getResources().getColor(android.R.color.white));
        }
    } else if(v == mPavilionTv) {
        if(mViewPager.getCurrentItem() != TAB_PAVILION) {
            changeTab(TAB_PAVILION);
            pavilionTab.setBackgroundColor(getResources().getColor(android.R.color.black));
            mPavilionTv.setTextColor(getResources().getColor(android.R.color.white));
        }

    } else if(v == mSocialTv) {
        if(mViewPager.getCurrentItem() != TAB_SOCIAL) {
            changeTab(TAB_SOCIAL);
            socialTab.setBackgroundColor(getResources().getColor(android.R.color.black));
            mSocialTv.setTextColor(getResources().getColor(android.R.color.white));
        }
    }
}

private void changeTab(int tabType) {
    mViewPager.setCurrentItem(tabType);
    System.out.println("tab to change to: " + tabType);
}

private void resetlayouts(){
    scoresTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
    pavilionTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
    friendsTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
    othersTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
    crowdTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
    socialTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));

    mScoresTv.setTextColor(getResources().getColor(android.R.color.black));
    mPavilionTv.setTextColor(getResources().getColor(android.R.color.black));
    mFriendsTv.setTextColor(getResources().getColor(android.R.color.black));
    mOtherTv.setTextColor(getResources().getColor(android.R.color.black));
    mCrowdTv.setTextColor(getResources().getColor(android.R.color.black));
    mSocialTv.setTextColor(getResources().getColor(android.R.color.black));

}

private void setTab() {
    mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

        @Override
        public void onPageScrollStateChanged(int position) { }
        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) { }
        @Override
        public void onPageSelected(int position) {
            System.out.println("setTab:::::::::::::::::::::::::::::::::::" + position);
            int previousFragment = fragmentPosition;

            if(previousFragment < position ) {
                tabsLayout.scrollTo(tabsLayout.getScrollX() + moveRight*fragmentPosition, tabsLayout.getScrollY());
                tabsLayout.requestLayout();
            }

            if(previousFragment > position ) {
                tabsLayout.scrollTo(tabsLayout.getScrollX() - moveRight*fragmentPosition, tabsLayout.getScrollY());
                tabsLayout.requestLayout();

            }

            fragmentPosition = position;
            resetlayouts();
            System.out.println("In on tab change listener!");

            switch(position) {
                case TAB_SCORES:
                    System.out.println("scores");
                    scoresTab.setBackgroundColor(getResources().getColor(android.R.color.black));
                    mScoresTv.setTextColor(getResources().getColor(android.R.color.white));
                    //give a call to netmanager and repaint livescorescreen on the basis of selected fragment
                    break;

                case TAB_PAVILION:{
                    System.out.println("pavilion");
                    pavilionTab.setBackgroundColor(getResources().getColor(android.R.color.black));
                    mPavilionTv.setTextColor(getResources().getColor(android.R.color.white));
                    //give a call to netmanager and repaint livescorescreen on the basis of selected fragment
                    break;
                }
                case TAB_FRIENDS:{
                    System.out.println("friends");
                    friendsTab.setBackgroundColor(getResources().getColor(android.R.color.black));
                    mFriendsTv.setTextColor(getResources().getColor(android.R.color.white));
                    //give a call to netmanager and repaint livescorescreen on the basis of selected fragment
                    break;
                }
                case TAB_OTHER:{
                    System.out.println("others");
                    othersTab.setBackgroundColor(getResources().getColor(android.R.color.black));
                    mOtherTv.setTextColor(getResources().getColor(android.R.color.white));
                    //give a call to netmanager and repaint livescorescreen on the basis of selected fragment
                    break;
                }
                case TAB_CROWD:{
                    System.out.println("crowd");
                    crowdTab.setBackgroundColor(getResources().getColor(android.R.color.black));
                    mCrowdTv.setTextColor(getResources().getColor(android.R.color.white));
                    //give a call to netmanager and repaint livescorescreen on the basis of selected fragment
                    break;
                }
                case TAB_SOCIAL:{
                    System.out.println("social");
                    socialTab.setBackgroundColor(getResources().getColor(android.R.color.black));
                    mSocialTv.setTextColor(getResources().getColor(android.R.color.white));
                    //give a call to netmanager and repaint livescorescreen on the basis of selected fragment
                    break;
                }
            }
            Fragment fragment = _adapter.getFragment(previousFragment);
            if(fragment != null) 
                fragment.onPause();

        }
    });
}

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

}

片段适配器

package com.example.fragments;

import java.util.List;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class FragmentsAdaptor extends FragmentPagerAdapter {


private List<Fragment> fragments;
/**
 * @param fm
 * @param fragments
 */
public FragmentsAdaptor(FragmentManager fm, List<Fragment> fragments) {
    super(fm);
    this.fragments = fragments;
}
/* (non-Javadoc)
 * @see android.support.v4.app.FragmentPagerAdapter#getItem(int)
 */
@Override
public Fragment getItem(int position) {
    return this.fragments.get(position);
}

/* (non-Javadoc)
 * @see android.support.v4.view.PagerAdapter#getCount()
 */
@Override
public int getCount() {
    return this.fragments.size();
}

public Fragment getFragment(int position) {
    return this.fragments.get(position);
}

}

片段1

package com.example.fragments;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;

public class Fragment1 extends Fragment implements OnClickListener {
private Context context;

public Fragment1() {}

public Fragment1(Context contex) {
    this.context=contex;
}

@Override
public void onClick(View arg0) {

}

@Override
public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
    super.onInflate(activity, attrs, savedInstanceState);
    System.out.println("Fragment1.onInflate() called................");
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    System.out.println("Fragment1.onAttach() called................");
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    System.out.println("Fragment1.onCreate() called................");
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        System.out.println("Fragment1.onCreateView() called................");

        View root = (View) inflater.inflate(R.layout.fragment1_screen, null);
        updateArticleView(root);

        return root;
    }


@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    System.out.println("Fragment1.onActivityCreated() called................");
}

@Override
public void onStart() {
    super.onStart();
    System.out.println("Fragment1.onStart() called................");
}

@Override
public void onResume() {
    super.onResume();
    System.out.println("Fragment1.onResume() called................");
}

@Override
public void onPause() {
    super.onPause();
    System.out.println("Fragment1.onPause() called................");
    onDestroyView();
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    System.out.println("Fragment1.onDestroyView() called................");
    onDestroy();
}

@Override
public void onDestroy() {
    super.onDestroy();
    System.out.println("Fragment1.onDestroy() called................");
    onDetach();
}

@Override
public void onDetach() {
    super.onDetach();
    System.out.println("Fragment1.onDetach() called................");
}

public void updateArticleView(View view) {

}

}

主要活动布局

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" >

<HorizontalScrollView
    android:id="@+id/tabs_layout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent"
    android:paddingLeft="2dp"
    android:paddingRight="2dp" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"
        android:orientation="horizontal" >

        <!-- First Tab -->

        <TableLayout
            android:id="@+id/scores_tab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@android:color/black" >

            <TableRow
                android:id="@+id/tableRow1"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:gravity="center_vertical" >

                <TextView
                    android:id="@+id/scores"
                    android:layout_width="fill_parent"
                    android:layout_height="30dp"
                    android:gravity="center_vertical"
                    android:paddingLeft="30dp"
                    android:paddingRight="30dp"
                    android:text="Scores"
                    android:textColor="@android:color/white"
                    android:textSize="11sp" />

                <TextView
                    android:layout_width="1px"
                    android:layout_height="fill_parent"
                    android:text=""
                    android:textColor="@android:color/black" />
            </TableRow>
        </TableLayout>

        <!-- Second Tab -->

        <TableLayout
            android:id="@+id/pavilion_tab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/transparent" >

            <TableRow
                android:id="@+id/tableRow2"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:gravity="center_vertical" >

                <TextView
                    android:id="@+id/pavilion"
                    android:layout_width="fill_parent"
                    android:layout_height="30dp"
                    android:gravity="center_vertical"
                    android:paddingLeft="30dp"
                    android:paddingRight="25dp"
                    android:text="Pavilion"
                    android:textColor="@android:color/black"
                    android:textSize="11sp" />

                <TextView
                    android:layout_width="1px"
                    android:layout_height="fill_parent"
                    android:text=""
                    android:textColor="@android:color/black" />
            </TableRow>
        </TableLayout>

        <!-- Third Tab -->

        <TableLayout
            android:id="@+id/friends_tab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/transparent" >

            <TableRow
                android:id="@+id/tableRow3"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:gravity="center_vertical" >

                <TextView
                    android:id="@+id/friends"
                    android:layout_width="fill_parent"
                    android:layout_height="30dp"
                    android:gravity="center_vertical"
                    android:paddingLeft="30dp"
                    android:paddingRight="30dp"
                    android:text="Friends"
                    android:textColor="@android:color/black"
                    android:textSize="11sp" />

                <TextView
                    android:layout_width="1px"
                    android:layout_height="fill_parent"
                    android:text=""
                    android:textColor="@android:color/black" />
            </TableRow>
        </TableLayout>

        <!-- Fourth Tab -->

        <TableLayout
            android:id="@+id/others_tab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/transparent" >

            <TableRow
                android:id="@+id/tableRow4"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:gravity="center_vertical" >

                <TextView
                    android:id="@+id/other"
                    android:layout_width="fill_parent"
                    android:layout_height="30dp"
                    android:gravity="center_vertical"
                    android:paddingLeft="30dp"
                    android:paddingRight="30dp"
                    android:text="Other"
                    android:textColor="@android:color/black"
                    android:textSize="11sp" />

                <TextView
                    android:layout_width="1px"
                    android:layout_height="fill_parent"
                    android:text=""
                    android:textColor="@android:color/black" />
            </TableRow>
        </TableLayout>

        <!-- Fifth Tab -->

        <TableLayout
            android:id="@+id/crowd_tab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/transparent" >

            <TableRow
                android:id="@+id/tableRow5"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:gravity="center_vertical" >

                <TextView
                    android:id="@+id/crowd"
                    android:layout_width="fill_parent"
                    android:layout_height="30dp"
                    android:gravity="center_vertical"
                    android:paddingLeft="30dp"
                    android:paddingRight="30dp"
                    android:text="Crowd"
                    android:textColor="@android:color/black"
                    android:textSize="11sp" />

                <TextView
                    android:layout_width="0px"
                    android:layout_height="fill_parent"
                    android:text=""
                    android:textColor="@android:color/black" />
            </TableRow>
        </TableLayout>

        <!-- Sixth Tab -->

        <TableLayout
            android:id="@+id/social_tab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:textColor="@android:color/transparent" >

            <TableRow
                android:id="@+id/tableRow6"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:gravity="center_vertical" >

                <TextView
                    android:id="@+id/social"
                    android:layout_width="fill_parent"
                    android:layout_height="30dp"
                    android:gravity="center_vertical"
                    android:paddingLeft="30dp"
                    android:paddingRight="30dp"
                    android:text="Social"
                    android:textColor="@android:color/black"
                    android:textSize="12sp" />
            </TableRow>
        </TableLayout>
    </LinearLayout>
</HorizontalScrollView>

<android.support.v4.view.ViewPager
    android:id="@+id/viewPager"
    android:layout_width="match_parent"
    android:layout_height="300dp"
    android:layout_below="@id/tabs_layout"
    android:layout_marginBottom="10dp"
    android:layout_marginTop="10dp" >
</android.support.v4.view.ViewPager>

片段布局

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

<TextView
    android:id="@+id/text1"
    android:text="Fragment1 Text"
    android:textColor="@android:color/black"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</RelativeLayout>
4

3 回答 3

1

我通过将以下代码放在末尾来实现它OnPageChangeListener.onPageSelected()

Fragment fragment = _adapter.getFragment(previousFragment);
if(fragment != null) {
   fragment.onPause();
}

我正在使用onPause()以下方式

public void onPause(){
    super.onPause();

    onDestroyView();
}

public void onDestroyView() {
    super.onDestroyView();

    onDestroy();
}

public void onDestroy() {
    super.onDestroy();

    onDetach();
}

public void onDetach() {
    super.onDetach();

}
于 2013-09-16T12:38:58.997 回答
0

这是一个已知问题, ViewPager(FragmentAdapter(Fragements)) 根据实际页面创建和销毁。我也遇到过这种情况,而且数据(对象)没有被引用,因为销毁会被GC收集,所以这很难。

我将在主 Activity 中使用静态对象,并使用onRetainNonConfigurationInstance方法保存和加载 Fragment 状态。

还找到了另一种解决方案,该解决方案集中在片段(A,B 和传递的字符串数据)之间的传递数据here

我希望这些解决方案之一适合您!

于 2013-09-13T12:54:18.873 回答
0

只需调用(setOffscreenPageLimit()onCreate()初始化 ViewPager 之后)。OffscreenPageLimit 设置应保留到当前页面任一侧的页面数。设置要在任一侧启动的最小片段数。

于 2013-09-13T14:10:33.193 回答