我的代码似乎在我的交换机案例

时间:2016-11-18 23:59:37

标签: android android-fragments android-viewpager switch-statement

我将网上看到的示例应用到我的代码中,以实现一个介绍页面(ViewPager有4页)。 为此,我在创建新活动时使用Android Studio提供的本机代码。

我根据我们所依赖的片段改编了以下编写texte的代码:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }

以下代码,使用开关,根据我们所依赖的片段显示不同的内容(按钮颜色,文本,图标):

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Context context = getContext();

        View rootView = inflater.inflate(R.layout.fragment_welcome, container, false);
        TextView textViewTitle = (TextView) rootView.findViewById(R.id.txtViewWelcomeTitle);
        TextView textViewDesc = (TextView) rootView.findViewById(R.id.txtViewWelcomeDesc);
        ImageView imageView = (ImageView) rootView.findViewById(R.id.imageViewWelcome);

        switch (getArguments().getInt(ARG_SECTION_NUMBER))
        {
            case 1:

                imageView.setImageResource(R.drawable.ic_menu_camera);
                textViewTitle.setText(R.string.fragment_1_title);
                textViewDesc.setText(R.string.fragment_1_desc);

                rootView.setBackgroundColor(ContextCompat.getColor(context, R.color.bg_screen1));
                btnNext.setText(R.string.next);
                btnSkip.setVisibility(View.VISIBLE);

                /*btnNext.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // launch next page of the fragment.

                    }
                });*/

                break;

            case 2:

                imageView.setImageResource(R.drawable.ic_menu_gallery);
                textViewTitle.setText(R.string.fragment_2_title);
                textViewDesc.setText(R.string.fragment_2_desc);

                rootView.setBackgroundColor(ContextCompat.getColor(context, R.color.bg_screen2));
                btnNext.setText(R.string.next);
                btnSkip.setVisibility(View.VISIBLE);

                break;

            case 3:

                imageView.setImageResource(R.drawable.ic_menu_manage);
                textViewTitle.setText(R.string.fragment_3_title);
                textViewDesc.setText(R.string.fragment_3_desc);

                rootView.setBackgroundColor(ContextCompat.getColor(context, R.color.bg_screen3));
                btnNext.setText(R.string.next);
                btnSkip.setVisibility(View.VISIBLE);

                break;

            case 4:

                imageView.setImageResource(R.drawable.ic_menu_send);
                textViewTitle.setText(R.string.fragment_4_title);
                textViewDesc.setText(R.string.fragment_4_desc);

                rootView.setBackgroundColor(ContextCompat.getColor(context, R.color.bg_screen4));
                btnNext.setText(R.string.start);
                btnSkip.setVisibility(View.INVISIBLE);

                break;
        }
        return rootView;
    }

我要看的是4页,其中3页有两个按钮(跳过和下一个),第4页有“开始”按钮。

我看到的内容:2个首页仅显示2个按钮,"开始"第3页和第4页上的按钮。

当我调试我的应用程序时,似乎我的代码通过案例1,然后通过案例2,然后我的应用程序显示案例1页面。 这意味着,当我切换时,我的页面似乎是他们应该位置的+1(我的页面1最终是2,2是3,......)。 奇怪的是,我显示的texte和图标是正确的。

以下是完整的WelcomActivity:

public class WelcomeActivity extends AppCompatActivity {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

    public static final String PREFS_NAME = "StartPref";
    private PrefManager prefManager;
    private static LinearLayout dotsLayout;
    private static TextView[] dots;
    private static Button btnSkip, btnNext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        // Checking for first time launch - before calling setContentView()
/*        prefManager = new PrefManager(this);
        if (!prefManager.isFirstTimeLaunch()) {
            goToHomePage();
            finish();
        }
*/
        if (Build.VERSION.SDK_INT >= 21) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        }

        setContentView(R.layout.activity_welcome);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

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

        dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
        btnSkip = (Button) findViewById(R.id.btn_skip);
        btnNext = (Button) findViewById(R.id.btn_next);

        // making notification bar transparent
        changeStatusBarColor();

        btnSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToHomePage(v);
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_welcome, 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);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            Context context = getContext();

            View rootView = inflater.inflate(R.layout.fragment_welcome, container, false);
            TextView textViewTitle = (TextView) rootView.findViewById(R.id.txtViewWelcomeTitle);
            TextView textViewDesc = (TextView) rootView.findViewById(R.id.txtViewWelcomeDesc);
            ImageView imageView = (ImageView) rootView.findViewById(R.id.imageViewWelcome);

            switch (getArguments().getInt(ARG_SECTION_NUMBER))
            {
                case 1:

                    imageView.setImageResource(R.drawable.ic_menu_camera);
                    textViewTitle.setText(R.string.fragment_1_title);
                    textViewDesc.setText(R.string.fragment_1_desc);

                    rootView.setBackgroundColor(ContextCompat.getColor(context, R.color.bg_screen1));
                    btnNext.setText(R.string.next);
                    btnSkip.setVisibility(View.VISIBLE);

                    /*btnNext.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            // launch next page of the fragment.

                        }
                    });*/

                    break;

                case 2:

                    imageView.setImageResource(R.drawable.ic_menu_gallery);
                    textViewTitle.setText(R.string.fragment_2_title);
                    textViewDesc.setText(R.string.fragment_2_desc);

                    rootView.setBackgroundColor(ContextCompat.getColor(context, R.color.bg_screen2));
                    btnNext.setText(R.string.next);
                    btnSkip.setVisibility(View.VISIBLE);

                    break;

                case 3:

                    imageView.setImageResource(R.drawable.ic_menu_manage);
                    textViewTitle.setText(R.string.fragment_3_title);
                    textViewDesc.setText(R.string.fragment_3_desc);

                    rootView.setBackgroundColor(ContextCompat.getColor(context, R.color.bg_screen3));
                    btnNext.setText(R.string.next);
                    btnSkip.setVisibility(View.VISIBLE);

                    break;

                case 4:

                    imageView.setImageResource(R.drawable.ic_menu_send);
                    textViewTitle.setText(R.string.fragment_4_title);
                    textViewDesc.setText(R.string.fragment_4_desc);

                    rootView.setBackgroundColor(ContextCompat.getColor(context, R.color.bg_screen4));
                    btnNext.setText(R.string.start);
                    btnSkip.setVisibility(View.INVISIBLE);

                    break;
            }
            return rootView;
        }
    }

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

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

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position + 1);
        }

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

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "SECTION 1";
                case 1:
                    return "SECTION 2";
                case 2:
                    return "SECTION 3";
                case 3:
                    return "SECTION 4";
            }
            return null;
        }
    }

    public void goToHomePage(View view) {
        prefManager.setFirstTimeLaunch(false);
        Intent intent = new Intent(this, HomePageActivity.class);
        startActivity(intent);
    }

    /**
     * Making notification bar transparent
     */
    private void changeStatusBarColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
    }

    private void addBottomDots(int currentPage) {
        dots = new TextView[mSectionsPagerAdapter.getCount()];

        int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);
        int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);

        dotsLayout.removeAllViews();
        for (int i = 0; i < dots.length; i++) {
            dots[i] = new TextView(this);
            dots[i].setText(Html.fromHtml("&#8226;"));
            dots[i].setTextSize(35);
            dots[i].setTextColor(colorsInactive[currentPage]);
            dotsLayout.addView(dots[i]);
        }

        if (dots.length > 0)
            dots[currentPage].setTextColor(colorsActive[currentPage]);
    }
}

这里是fragment_welcome.xml,然后是activity_welcome.xml

<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:background="@color/bg_screen1"
tools:context="com.example.avescera.remindme.WelcomeActivity$PlaceholderFragment" >

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <ImageView
        android:layout_width="@dimen/img_width_height"
        android:layout_height="@dimen/img_width_height"
        android:src="@drawable/ic_menu_manage"
        android:id="@+id/imageViewWelcome" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@android:color/white"
        android:textSize="@dimen/slide_title"
        android:textStyle="bold"
        android:id="@+id/txtViewWelcomeTitle" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:paddingLeft="@dimen/desc_padding"
        android:paddingRight="@dimen/desc_padding"
        android:textAlignment="center"
        android:textColor="@android:color/white"
        android:textSize="@dimen/slide_desc"
        android:id="@+id/txtViewWelcomeDesc" />

</LinearLayout>

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.avescera.remindme.WelcomeActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/appbar_padding_top"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay">

        </android.support.v7.widget.Toolbar>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <LinearLayout
        android:id="@+id/layoutDots"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dots_height"
        android:layout_marginBottom="@dimen/dots_margin_bottom"
        android:gravity="center"
        android:orientation="horizontal"
        android:layout_alignParentBottom="false"
        android:layout_below="@+id/viewDots"
        android:layout_gravity="bottom|center_horizontal"></LinearLayout>

    <View
        android:id="@+id/viewDots"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:alpha=".5"
        android:background="@android:color/white"
        android:layout_gravity="bottom|center" />

    <Button
        android:id="@+id/btn_next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:background="@null"
        android:text="@string/next"
        android:textColor="@android:color/white"
        android:layout_gravity="bottom|left" />

    <Button
        android:id="@+id/btn_skip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:background="@null"
        android:text="@string/skip"
        android:textColor="@android:color/white"
        android:layout_gravity="bottom|right" />

</android.support.design.widget.CoordinatorLayout>

如果您需要任何信息,请不要犹豫。

亚历

1 个答案:

答案 0 :(得分:1)

最后我找到了如何回答我的问题(对那些有兴趣解决这个问题的人)。

首先,更多细节。我使用了android studio(2.2)提供的内置活动tabbed-activity。这个允许使用片段寻呼机,并且似乎行为(例如显示第一个片段,但在你的代码中,你已经在第二个片段中,没有正确理解它是如何工作的。)

对我来说,我想要4页(我的片段寻呼机有4个部分)和2个按钮在底部(附加到活动xml而不是片段xml)。

解决方案是simlpe:在onCreateView()部分添加片段文本更新,在OnCreate()部分添加按钮文本更新(和onClickListener)。

在OnCreate()部分,要知道使用了哪个页面片段,您必须使用ViewPager,并在其上添加addOnPageChangeListener。然后没关系,你可以在其中添加一个开关来知道哪个页面,检查位置的值(从0到你有的页数-1)。

希望这有帮助。