视图中的getSupportFragmentManager()错误

时间:2017-07-27 04:36:02

标签: java android

为什么我收到显示更改的错误消息 getSupportFragmentManager()

中的view
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPropertyAnimatorListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;

import java.util.ArrayList;
import java.util.Random;

import activity.rama.navigationtaskbartraining.R;
import activity.rama.navigationtaskbartraining.flycodialog.IOSTaoBaoDialog;
import activity.rama.navigationtaskbartraining.tabbed.Tab1Contact;
import activity.rama.navigationtaskbartraining.tabbed.Tab2Chat;
import activity.rama.navigationtaskbartraining.tabbed.Tab3Online;
import activity.rama.navigationtaskbartraining.tabbed.TabbedActivity;
import butterknife.Bind;
import cn.pedant.SweetAlert.SweetAlertDialog;
import devlight.io.library.ntb.NavigationTabBar;

import static android.content.ContentValues.TAG;

/**
 * Created by GIGAMOLE on 28.03.2016.
 */
public class HorizontalCoordinatorNtbAndTabbedActivity extends Activity implements View.OnClickListener {

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    private ExpandableListView.OnChildClickListener view2;

    private TabbedActivity.SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;

    private FragmentActivity myContext;

    private FragmentManager FragManager;

    @Bind(R.id.elv)
    ExpandableListView mElv;

    private Context mContext = this;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_horizontal_coordinator_ntb);
        initUI();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    private void initUI() {
        final ViewPager viewPager = (ViewPager) findViewById(R.id.vp_horizontal_ntb);
        viewPager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return 5;
            }

            @Override
            public boolean isViewFromObject(final View view, final Object object) {
                return view.equals(object);
            }

            @Override
            public void destroyItem(final View container, final int position, final Object object) {
                ((ViewPager) container).removeView((View) object);
            }

            @Override
            public Object instantiateItem(final ViewGroup container, final int position) {
                if (position == 0) {
                    try{
                        final View view = LayoutInflater.from(
                                getBaseContext()).inflate(R.layout.tabbed_main, null, false);
                        container.addView(view);

                        final Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
//                        setSupportActionBar(toolbar);
                        toolbar.setOnClickListener(HorizontalCoordinatorNtbAndTabbedActivity.this);

                        // Create the adapter that will return a fragment for each of the three
                        // primary sections of the activity.
                        mSectionsPagerAdapter = new TabbedActivity.SectionsPagerAdapter(getActivity().getSupportFragmentManager());

                        // Set up the ViewPager with the sections adapter.
                        mViewPager = (ViewPager) view.findViewById(R.id.container);
                        mViewPager.setAdapter(mSectionsPagerAdapter);

                        final TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabs);
                        tabLayout.setupWithViewPager(mViewPager);

                        return view;
                    } catch (ClassCastException e) {
                        Log.d(TAG, "Can't get the fragment manager with this");
                        return null;
                    }
                }else if (position == 2) {
                    final View view = LayoutInflater.from(
                        getBaseContext()).inflate(R.layout.item_vp_list, null, false);
                    final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.rv);
                    recyclerView.setHasFixedSize(true);
                    recyclerView.setLayoutManager(new LinearLayoutManager(
                                    getBaseContext(), LinearLayoutManager.VERTICAL, false
                            )
                    );
                    recyclerView.setAdapter(new RecycleAdapter());

                    container.addView(view);
                    return view;
                } else if (position == 4) {
                    final View view = LayoutInflater.from(
                            getBaseContext()).inflate(R.layout.test, null, false);
                    container.addView(view);
                    final TextView txt_test = (TextView) view.findViewById(R.id.txt_test);
                    txt_test.setOnClickListener(HorizontalCoordinatorNtbAndTabbedActivity.this);
                    return view;
                } else {
                    final View view = LayoutInflater.from(
                            getBaseContext()).inflate(R.layout.item_vp, null, false);

                    final TextView txtPage = (TextView) view.findViewById(R.id.txt_vp_item_page);
                    txtPage.setText(String.format("Page #%d", position));

                    container.addView(view);
                    return view;
                }
            }
        });

        final String[] colors = getResources().getStringArray(R.array.default_preview);

        final NavigationTabBar navigationTabBar = (NavigationTabBar) findViewById(R.id.ntb_horizontal);
        final ArrayList<NavigationTabBar.Model> models = new ArrayList<>();
        models.add(
                new NavigationTabBar.Model.Builder(
                        getResources().getDrawable(R.drawable.ic_first),
                        Color.parseColor(colors[0]))
                        .title("MyHeart")
                        .build()
        );
        models.add(
                new NavigationTabBar.Model.Builder(
                        getResources().getDrawable(R.drawable.ic_second),
                        Color.parseColor(colors[1]))
                        .title("Cup")
                        .build()
        );
        models.add(
                new NavigationTabBar.Model.Builder(
                        getResources().getDrawable(R.drawable.ic_third),
                        Color.parseColor(colors[2]))
                        .title("Diploma")
                        .build()
        );
        models.add(
                new NavigationTabBar.Model.Builder(
                        getResources().getDrawable(R.drawable.ic_fourth),
                        Color.parseColor(colors[3]))
                        .title("Flag")
                        .build()
        );
        models.add(
                new NavigationTabBar.Model.Builder(
                        getResources().getDrawable(R.drawable.ic_fifth),
                        Color.parseColor(colors[4]))
                        .title("Medal")
                        .build()
        );

        navigationTabBar.setModels(models);
        navigationTabBar.setViewPager(viewPager, 2);

        //IMPORTANT: ENABLE SCROLL BEHAVIOUR IN COORDINATOR LAYOUT
        navigationTabBar.setBehaviorEnabled(true);

        navigationTabBar.setOnTabBarSelectedIndexListener(new NavigationTabBar.OnTabBarSelectedIndexListener() {
            @Override
            public void onStartTabSelected(final NavigationTabBar.Model model, final int index) {
            }

            @Override
            public void onEndTabSelected(final NavigationTabBar.Model model, final int index) {
                model.hideBadge();
            }
        });
        navigationTabBar.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(final int position, final float positionOffset, final int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(final int position) {

            }

            @Override
            public void onPageScrollStateChanged(final int state) {

            }
        });

        final CoordinatorLayout coordinatorLayout = (CoordinatorLayout) findViewById(R.id.parent);
        findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                for (int i = 0; i < navigationTabBar.getModels().size(); i++) {
                    final NavigationTabBar.Model model = navigationTabBar.getModels().get(i);
                    navigationTabBar.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            final String title = String.valueOf(new Random().nextInt(15));
                            if (!model.isBadgeShowed()) {
                                model.setBadgeTitle(title);
                                model.showBadge();
                            } else model.updateBadgeTitle(title);
                        }
                    }, i * 100);
                }

                coordinatorLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        final Snackbar snackbar = Snackbar.make(navigationTabBar, "Coordinator NTB", Snackbar.LENGTH_SHORT);
                        snackbar.getView().setBackgroundColor(Color.parseColor("#9b92b3"));
                        ((TextView) snackbar.getView().findViewById(R.id.snackbar_text))
                                .setTextColor(Color.parseColor("#423752"));
                        snackbar.show();
                    }
                }, 1000);

                Toast.makeText(HorizontalCoordinatorNtbAndTabbedActivity.this, "fab Button Click Event", Toast.LENGTH_SHORT).show();
            }
        });

        final CollapsingToolbarLayout collapsingToolbarLayout =
                (CollapsingToolbarLayout) findViewById(R.id.toolbar);
        collapsingToolbarLayout.setExpandedTitleColor(Color.parseColor("#009F90AF"));
        collapsingToolbarLayout.setCollapsedTitleTextColor(Color.parseColor("#9f90af"));
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("HorizontalCoordinatorNtb Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }

    public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.ViewHolder> {

        @Override
        public ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
            final View view = LayoutInflater.from(getBaseContext()).inflate(R.layout.item_list, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(final ViewHolder holder, final int position) {
            holder.txt.setText(String.format("Navigation Item #%d", position));
        }

        @Override
        public int getItemCount() {
            return 20;
        }

        public class ViewHolder extends RecyclerView.ViewHolder {

            public TextView txt;

            public ViewHolder(final View itemView) {
                super(itemView);
                txt = (TextView) itemView.findViewById(R.id.txt_vp_item_list);
            }
        }
    }


//    @Override
    public void onClick(final View v) {
        ViewCompat.animate(v)
                .setDuration(200)
                .scaleX(0.9f)
                .scaleY(0.9f)
                .setInterpolator(new HorizontalCoordinatorNtbAndTabbedActivity.CycleInterpolator())
                .setListener(new ViewPropertyAnimatorListener() {
                    @Override
                    public void onAnimationStart(final View view) {
//                        Toast.makeText(HorizontalNtbActivity.this, "function onAnimationStart()",
//                                Toast.LENGTH_LONG).show();
//                        Log.d("function onAnimationStart", "function");
                    }

                    @Override
                    public void onAnimationEnd(final View view) {
                        switch (v.getId()) {
                            case R.id.txt_test:
//                                startActivity(
//                                        new Intent(HorizontalNtbActivity.this, SamplesNtbActivity.class)
//                                );

                                Toast.makeText(HorizontalCoordinatorNtbAndTabbedActivity.this, "Test Button Click Event",
                                        Toast.LENGTH_LONG).show();
//Toast.m
                                new SweetAlertDialog(HorizontalCoordinatorNtbAndTabbedActivity.this, SweetAlertDialog.CUSTOM_IMAGE_TYPE)
                                        .setTitleText("Sweet!")
                                        .setContentText("Here's a custom image test.")
                                        .setCustomImage(R.drawable.custom_img)
                                        .show();

                                final IOSTaoBaoDialog dialog = new IOSTaoBaoDialog(HorizontalCoordinatorNtbAndTabbedActivity.this, (View) view2);
                                dialog.show();
                                break;
                            default:
                                break;
                        }
                    }

                    @Override
                    public void onAnimationCancel(final View view) {
                    }
                })
                .withLayer()
                .start();
    }

    private class CycleInterpolator implements android.view.animation.Interpolator {

        private final float mCycles = 0.5f;

        @Override
        public float getInterpolation(final float input) {
            return (float) Math.sin(2.0f * mCycles * Math.PI * input);
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    Tab1Contact tab1Contact = new Tab1Contact();
                    return tab1Contact;
                case 1:
                    Tab2Chat tab2Chat = new Tab2Chat();
                    return tab2Chat;
                case 2:
                    Tab3Online tab3Online = new Tab3Online();
                    return tab3Online;
                default:
                    return null;
            }
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "CONTACT";
                case 1:
                    return "CHAT";
                case 2:
                    return "ONLINE";
            }
            return null;
        }
    }
}

非常感谢

2 个答案:

答案 0 :(得分:0)

  1. 尝试使用FragmentStatePagerAdapter而不是FragmentPagerAdapter。它可以并且可能解决一些可能的问题。
  2. 将SupportFrogmentManager传递给FragmentStatePagerAdapter,如果在其中,则使用支持库中的片段。在其他情况下 - 传递FragmentManager。
  3. 根据您的视图层次结构,您可以尝试获取ChildFragmentManager。
  4. 尝试将ViewPager从片段移动到活动。

答案 1 :(得分:0)

您的活动不会从支持库中延伸FragmentActivity,因此您无法拨打this method

所以你需要这样的东西:

public class HorizontalCoordinatorNtbAndTabbedActivity extends FragmentActivity implements View.OnClickListener {

然后施放:

((HorizontalCoordinatorNtbAndTabbedActivity)getActivity()).getSupportFragmentManager()

在ViewPager中加上ViewPager - 这不是一个好主意。