选项卡片段内的卡片视图

Posted

技术标签:

【中文标题】选项卡片段内的卡片视图【英文标题】:Cardview inside tab fragment 【发布时间】:2016-02-04 18:34:29 【问题描述】:

我正在开发带有滑动标签的材料设计导航抽屉,并且我已经实现了相同的功能。 现在我想在标签片段之一中添加cardviewrecycler view,但不知道该怎么做。

有人可以帮我解决这个问题吗?

这是我的标签片段代码:-

    public class TabFragment extends Fragment 

    public static TabLayout tabLayout;
    public static ViewPager viewPager;
    public static int int_items = 2 ;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
        /**
         *Inflate tab_layout_tens and setup Views.
         */
        View x =  inflater.inflate(R.layout.tab_layout_tens,null);
        tabLayout = (TabLayout) x.findViewById(R.id.tabs);
        viewPager = (ViewPager) x.findViewById(R.id.viewpager);

        /**
         *Set an Apater for the View Pager
         */
        viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));

        /**
         * Now , this is a workaround ,
         * The setupWithViewPager dose't works without the runnable .
         * Maybe a Support Library Bug .
         */

        tabLayout.post(new Runnable() 
            @Override
            public void run() 
                tabLayout.setupWithViewPager(viewPager);
            
        );

        return x;

    

    class MyAdapter extends FragmentPagerAdapter

        public MyAdapter(FragmentManager fm) 
            super(fm);
        

        /**
         * Return fragment with respect to Position .
         */

        @Override
        public Fragment getItem(int position)
        
            switch (position)
                case 0 : return new CurrentFragment();
                case 1 : return new FavouriteFragment();

            
            return null;
        

        @Override
        public int getCount() 

            return int_items;

        

        /**
         * This method returns the title of the tab according to the position.
         */

        @Override
        public CharSequence getPageTitle(int position) 

            switch (position)
                case 0 :
                    return "Current";
                case 1 :
                    return "Favourite";

            
            return null;
        
    

这是我的片段类,我在其中添加了回收器视图,但它在设置适配器时给出了NULL Point exception

 public class FavouriteFragment extends Fragment 
    private List<Person> persons;
    private RecyclerView rv;

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

    

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
        View rootView = inflater.inflate(R.layout.favourite_layout,container,false);

        RecyclerView rv = (RecyclerView)rootView.findViewById(R.id.rv);
        final LinearLayoutManager llm = new LinearLayoutManager(getActivity());
        rv.setLayoutManager(llm);

        initializeData();
        initializeAdapter();
        return rootView;
    
    private void initializeData()
        persons = new ArrayList<>();
        persons.add(new Person("XYZ", "jhxdjksd", R.drawable.profilepic));
        persons.add(new Person("ABC", "bsxhbs", R.drawable.profilepic));
        persons.add(new Person("PQR", "bsahxb", R.drawable.profilepic));
    

    private void initializeAdapter()
        RVAdapter adapter = new RVAdapter(persons);
        rv.setAdapter(adapter);
    

MainActivity

    public class Tens extends AppCompatActivity 

    DrawerLayout mDrawerLayout;
    NavigationView mNavigationView;
    FragmentManager mFragmentManager;
    FragmentTransaction mFragmentTransaction;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tens);

        /**
         *Setup the DrawerLayout and NavigationView
         */

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        mNavigationView = (NavigationView) findViewById(R.id.shitstuff) ;

        /**
         * Lets inflate the very first fragment
         * Here , we are inflating the TabFragmentTens as the first Fragment
         */

        mFragmentManager = getSupportFragmentManager();
        mFragmentTransaction = mFragmentManager.beginTransaction();
        mFragmentTransaction.replace(R.id.containerView,new TabFragmentTens()).commit();
        /**
         * Setup click events on the Navigation View Items.
         */

        mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() 
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) 

                Fragment fragment = null;

                Class fragmentClass = null;
                switch(menuItem.getItemId()) 
                    case R.id.nav_item_tracker:
                        Intent intent = new Intent(
                        Tens.this, Tracker.class);
                startActivity(intent);
                        break;
                    case R.id.nav_item_clinic:
                        fragmentClass = ClinicFragment.class;
                        break;
                    case R.id.nav_item_about:
                        Intent intent0 = new Intent(
                                Tens.this, AboutFragment.class);
                        startActivity(intent0);
                        break;
                    case R.id.nav_item_settings:
                        Intent intent1 = new Intent(
                                Tens.this, SettingsFragment.class);
                        startActivity(intent1);
                        break;

                    case R.id.nav_item_logout:
                        Intent intent2 = new Intent(
                                Tens.this, MainActivity.class);
                        startActivity(intent2);

                        break;
                

                try 
                    fragment = (Fragment) fragmentClass.newInstance();
                 catch (Exception e) 
                    e.printStackTrace();
                

                FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
                    xfragmentTransaction.replace(R.id.containerView, new TabFragmentTens()).commit();

                mDrawerLayout.closeDrawers();


                return false;
            

        );


        android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
        ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout, toolbar,R.string.app_name,
                R.string.app_name);

        mDrawerLayout.setDrawerListener(mDrawerToggle);

        mDrawerToggle.syncState();

    

这是我的 recyclerview 课程:-

 public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder> 

    public static class PersonViewHolder extends RecyclerView.ViewHolder 

        CardView cv;
        TextView personName;
        TextView personAge;
        ImageView personPhoto;

        PersonViewHolder(View itemView) 
            super(itemView);
            cv = (CardView)itemView.findViewById(R.id.cv);
            personName = (TextView)itemView.findViewById(R.id.person_name);
            personAge = (TextView)itemView.findViewById(R.id.person_age);
            personPhoto = (ImageView)itemView.findViewById(R.id.person_photo);
        
    

    List<Person> persons;

    RVAdapter(List<Person> persons)
        this.persons = persons;
    

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) 
        super.onAttachedToRecyclerView(recyclerView);
    

    @Override
    public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) 
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_view_tens_fvrt, viewGroup, false);
        PersonViewHolder pvh = new PersonViewHolder(v);
        return pvh;
    

    @Override
    public void onBindViewHolder(PersonViewHolder personViewHolder, int i) 
        personViewHolder.personName.setText(persons.get(i).name);
        personViewHolder.personAge.setText(persons.get(i).age);
        personViewHolder.personPhoto.setImageResource(persons.get(i).photoId);
    

    @Override
    public int getItemCount() 
        return persons.size();
    

我想在Favourite 片段中添加cardviewrecycler view。我知道如何实现cardview,但无法在片段中实现。

【问题讨论】:

你能把你的整个代码贴出来吗。 您的片段是否有父活动..? 完成@RubinNellikunnathu 我希望你有 mainactivity..不是吗? 如果是。将 tablayout 和 viewpager 的代码移动到 mainactivity。然后为每个选项卡创建片段。仅将 recyclerview 添加到片段类..(现在您​​在 Tabfragment 中添加了 tablayout 和 viewpager)。 【参考方案1】:

首先在您的 mainactivity 中进行更改。 这里我在 mainactivity 中添加了一个导航抽屉和 tablayout。

public class HomeActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener 


    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        TabLayout tabLayout1 = (TabLayout) findViewById(R.id.tab_layout1);
        tabLayout1.addTab(tabLayout1.newTab().setIcon(R.drawable.tab_ic_home));
        tabLayout1.addTab(tabLayout1.newTab().setIcon(R.drawable.tab_ic_map));
        tabLayout1.addTab(tabLayout1.newTab().setIcon(R.drawable.tab_ic_login));

        tabLayout1.setTabGravity(TabLayout.GRAVITY_FILL);

        final ViewPager viewPager1 = (ViewPager) findViewById(R.id.pager1);
        final PagerAdapter1 adapter = new PagerAdapter1
                (getSupportFragmentManager(), tabLayout1.getTabCount());
        viewPager1.setAdapter(adapter);
        viewPager1.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout1));
        tabLayout1.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() 
            @Override
            public void onTabSelected(TabLayout.Tab tab) 
                viewPager1.setCurrentItem(tab.getPosition());
            

            @Override
            public void onTabUnselected(TabLayout.Tab tab) 

            

            @Override
            public void onTabReselected(TabLayout.Tab tab) 

            
        );
    

    @Override
    public void onBackPressed() 
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) 
            drawer.closeDrawer(GravityCompat.START);
         else 
            super.onBackPressed();
        
    

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) 
            return true;
        

        return super.onOptionsItemSelected(item);
    

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) 
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        RelativeLayout mainLayout=(RelativeLayout)findViewById(R.id.main_layout);

           if (id == R.id.nav_project) 
            ProjectFragment fragment = new ProjectFragment();
            fragmentTransaction.replace(R.id.mainlayout, fragment);
            fragmentTransaction.addToBackStack(null).commit();
            
        

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    

然后创建一个寻呼机适配器。 在这里你可以为你的标签添加片段.. 我将其命名为 PagerAdapter1.java。

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

public class PagerAdapter1 extends FragmentStatePagerAdapter 
    int mNumOfTabs;

    public PagerAdapter1(FragmentManager fm, int NumOfTabs) 
        super(fm);
        this.mNumOfTabs = NumOfTabs;
    

    @Override
    public Fragment getItem(int position) 

        switch (position) 
            case 0:
                HomeTabFragment1 tab1 = new HomeTabFragment1();
                return tab1;
            case 1:
                HomeTabFragment2 tab2 = new HomeTabFragment2();
                return tab2;
            case 2:
                HomeTabFragment3 tab3 = new HomeTabFragment3();
                return tab3;
            default:
                return null;
        
    

    @Override
    public int getCount() 
        return mNumOfTabs;
    

我只想在第一个选项卡中显示 Recycler 视图。所以我在 HomeTabFragment1.java 中添加了 recyclerview 的代码。

public class HomeTabFragment1 extends Fragment 

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
        View v=inflater.inflate(R.layout.home_tab_fragment_1, container, false);
        RecyclerView rv = (RecyclerView)v.findViewById(R.id.home_recyclerview);
        setupRecyclerView(rv);
        return v;

我希望剩下的你能做到..

【讨论】:

谢谢@Rubin,但我知道如何实现一个recyclerview。问题是如何在片段中实现它。 是的,但调用 getItemCount() 方法时出错。记录 cat 错误 - java.lang.NullPointerException:尝试在 com.ediode.graphics3d.RVAdapter.getItemCount(RVAdapter.java:60) 是getItemCount()还是getCount().? 你的 tablayout 是否在没有 recyclerview 的情况下使用 viewpager 正常工作? 是的带有视图寻呼机的选项卡布局在没有 Recyclerview 的情况下可以正常工作【参考方案2】:

看起来字段“rv”从未在 FavouriteFragment 类中初始化,您确实在方法 onCreateView 中初始化了局部变量“rv”。

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    View rootView = inflater.inflate(R.layout.favourite_layout,container,false);

    RecyclerView rv = (RecyclerView)rootView.findViewById(R.id.rv);
    final LinearLayoutManager llm = new LinearLayoutManager(getActivity());
    rv.setLayoutManager(llm);

    initializeData();
    initializeAdapter();
    return rootView;
 

【讨论】:

以上是关于选项卡片段内的卡片视图的主要内容,如果未能解决你的问题,请参考以下文章

刷新片段内的视图

检测片段内的 ViewPager 选项卡更改

检测片段内的 ViewPager 选项卡更改

如何从使用视图寻呼机创建的选项卡片段转移到另一个片段

以编程方式使用选项卡更改片段的选项卡索引

Fragment中的ViewPager,只有选项卡才能在第一个视图上加载选项卡