【问题标题】:View Pager with huge number of fragment查看具有大量片段的寻呼机
【发布时间】:2014-11-20 10:54:13
【问题描述】:

我必须更改滑动视图。这可以通过查看寻呼机获得。但是我有 60 个视图并创建 60 个不同的片段不是一个好方法。 请有人指导我什么是设计滑动 60 视图的最佳方式。

【问题讨论】:

  • 只需要一个片段类。将参数从 FragmentPagerAdapter 传递给片段。这样就可以为不同的参数创建同一个类的不同实例。
  • @Ali 那并没有解决内存使用问题。仍然会创建该特定类的许多实例。看我的回答。

标签: android android-viewpager fragment


【解决方案1】:

首先创建一个片段,您可以在其中使用“位置”参数为不同的视图充气,如下所示..

public class SuperAwesomeCardFragment extends Fragment {

private static final String ARG_POSITION = "position";

private int position;
View mainView;

public static SuperAwesomeCardFragment newInstance(int position) {
    SuperAwesomeCardFragment f = new SuperAwesomeCardFragment();
    Bundle b = new Bundle();
    b.putInt(ARG_POSITION, position);
    f.setArguments(b);
    return f;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    position = getArguments().getInt(ARG_POSITION);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)          {

  if(position==1){

  mainview = inflater.inflate(R.layout.layout1, null);

  }else if(position==2){

  mainview =inflater.inflate(R.layout.layout2, null);
  .
  .
  .
  .
  }else if(position==50){

  mainview =inflater.inflate(R.layout.layout50, null);
  }

return mainView;    
}

}

现在在您的 MainActivity 中创建一个扩展 FragmentPagerAdpater 的适配器,并在 getItem() 方法中创建先前创建片段的实例,如下所示

public class MyPagerAdapter extends FragmentPagerAdapter {

    private final String[] TITLES = { "Title1", "Title2"...., "Title50"};

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return TITLES[position];
    }

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

    @Override
    public Fragment getItem(int position) {
        return SuperAwesomeCardFragment.newInstance(position);
    }

}

}

然后最后在你的 Activity 的 OnCreat() 方法中添加这个...

MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
yourViewPager.setAdapter(adapter);

因此,您必须创建单个片段并将其用于多个视图。 谢谢你。希望对您有所帮助..!!

【讨论】:

  • 不会造成内存泄漏吗?
  • 不,不会。当 GC 清除不可见的片段时,除非您设置 offscreenlimit。
【解决方案2】:

您可以安全地使用ViewPagerFragmentStatePagerAdapter 的实现。适配器将通过销毁在给定时刻不可见的片段来优化内存使用。 Check the documentation 获取详细信息和代码示例。

【讨论】:

    【解决方案3】:

    以下是将片段添加到视图寻呼机的完整代码。 由于这只是一个演示,我只使用了一个 textView 并且添加的每个片段都将具有随机颜色。单击按钮时,您可以添加任意数量的片段。单击页面时,您可以将其从视图寻呼机中删除。您可以在 View Pager 中通过向右或向左滑动从一个页面移动到另一个页面。

    MainActivity.java

    import android.graphics.Color;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentActivity;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentStatePagerAdapter;
    import android.support.v4.view.ViewPager;
    import android.view.View;
    import android.widget.Button;
    import java.util.ArrayList;
    import java.util.Random;
    
    public class MainActivity extends FragmentActivity {
    
        private MyPagerAdapter mpg;
        private ArrayList<MyFragment> fragmentlist = new ArrayList<>();
        public FragmentManager fmr    = getSupportFragmentManager();
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            final ViewPager pager  = (ViewPager) findViewById(R.id.viewPager);
            mpg = new MyPagerAdapter(fmr,fragmentlist);
            pager.setAdapter(mpg);
    
            for (int q = 0; q < 5; q++) {
                int r = new Random().nextInt(100) + 155;
                int g = new Random().nextInt(100) + 155;
                int b = new Random().nextInt(100) + 155;
                fragmentlist.add(MyFragment.newInstance(q, "Page number: " + (q + 1), Color.rgb(r, g, b)));
                mpg.notifyDataSetChanged();
            }
    
            Button  B1 = (Button) findViewById(R.id.button);
            B1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    int r = new Random().nextInt(100) + 155;
                    int g = new Random().nextInt(100) + 155;
                    int b = new Random().nextInt(100) + 155;
                    int count = mpg.getCount();
                    fragmentlist.add(MyFragment.newInstance(count, "Page number: " + (count+1), Color.rgb(r, g, b)));
                    mpg.notifyDataSetChanged();
    
                }
            });
        }
    
        public void delete(int pos) {
    
            int i = 0;
            while (i <= fragmentlist.size()) {
                if (pos == fragmentlist.get(i).getPosition()) break;
                i++;
    
            }
    
            fragmentlist.remove(i);
            mpg.notifyDataSetChanged();
        }
    
        public class MyPagerAdapter extends FragmentStatePagerAdapter {
    
            private ArrayList<MyFragment> fragmentList;
            public MyPagerAdapter(FragmentManager fm, ArrayList<MyFragment> f) {
                super(fm);
                this.fragmentList = f;
            }
    
            @Override
            public Fragment getItem(int pos) {
                return fragmentlist.get(pos);
            }
    
            @Override
            public int getCount() {
                return fragmentlist.size();
            }
    
            @Override
            public int getItemPosition(Object object) {
                return POSITION_NONE;
            }
        }
    }
    

    MyFragment.java

    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.FrameLayout;
    import android.widget.TextView;
    
    import java.util.List;
    
    public class MyFragment extends Fragment {
    
        int pos;
    
        @Override
        public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.f_1, container, false);
            pos = getArguments().getInt("num");
            v.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    Log.v("MainActivity", "Deleting at pos - " + pos);
                    MainActivity activity = (MainActivity) getActivity();
                    activity.delete(pos);
                }
            });
    
            TextView tv = (TextView) v.findViewById(R.id.tvFragFirst);
            FrameLayout fl = (FrameLayout) v.findViewById(R.id.frame_layout);
            tv.setText(getArguments().getString("msg"));
            fl.setBackgroundColor(getArguments().getInt("colour"));
            return v;
        }
    
        public int getPosition() {
            return pos;
        }
    
        public static MyFragment newInstance(int num,String text,int clr) {
    
            MyFragment f = new MyFragment();
            Bundle b = new Bundle();
            b.putString("msg", text);
            b.putInt("colour", clr);
            b.putInt("num",num);
            f.setArguments(b);
            return f;
        }
    }
    

    还有 xml.files,

    activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <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"
        tools:context="com.example.shakthivels.assingment10.MainActivity"
        android:id="@+id/r_v"
        >
    
        <android.support.v4.view.ViewPager
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/viewPager"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"/>
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="ADD a fragment"
            android:id="@+id/button"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true" />
    
    </RelativeLayout>
    

    f_1.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/av"
         >
    
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:id="@+id/frame_layout">
    
            <TextView
                android:id="@+id/tvFragFirst"
                android:layout_width="203dp"
                android:layout_height="127dp"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:textSize="26sp"
                android:text="TextView"
                android:layout_gravity="center"
                android:textColor="#000000" />
    
        </FrameLayout>
    </RelativeLayout>
    

    1 2

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-24
      • 1970-01-01
      相关资源
      最近更新 更多