簡體   English   中英

在viewPager中啟動新片段而不隱藏ac

[英]Start new fragment inside viewPager without hiding ac

我有一個MainActivity,它是一個帶有ViewPager的ActionBarActivity。 然后,我有3頁。 在第一頁中,有一個tableLayout與tableRow clickListener(在內部塊中),在這里我想在不隱藏TabBar的情況下開始意圖到另一個布局。 這是我的代碼:

MainActivity.java

     @TargetApi(Build.VERSION_CODES.HONEYCOMB) 
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {

    /**
     * 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}.
     */
    SectionsPagerAdapter mSectionsPagerAdapter;

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

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

        // Set up the action bar.
        final ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // 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.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        // When swiping between different sections, select the corresponding
        // tab. We can also use ActionBar.Tab#select() to do this if we have
        // a reference to the Tab.
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position);
            }
        });

        // For each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
            // Create a tab with text corresponding to the page title defined by
            // the adapter. Also specify this Activity object, which implements
            // the TabListener interface, as the callback (listener) for when
            // this tab is selected.
            actionBar.addTab(
                    actionBar.newTab()
                    .setText(mSectionsPagerAdapter.getPageTitle(i))
                    .setTabListener(this));
        }
    }


    @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;
    }

    @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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
        // When the given tab is selected, switch to the corresponding page in
        // the ViewPager.
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    /**
     * 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) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a FirstFragment (defined as a static inner class below).
            //return FirstFragment.newInstance(position + 1);
            switch(position) {
            case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
            case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
            case 2: return ThirdFragment.newInstance("ThirdFragment, Instance 1");
            default: return ThirdFragment.newInstance("ThirdFragment, Default");
            }

        }

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

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
            case 0:
                return getString(R.string.title_section1).toUpperCase(l);
            case 1:
                return getString(R.string.title_section2).toUpperCase(l);
            case 2:
                return getString(R.string.title_section3).toUpperCase(l);
            }
            return null;
        }
    }

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

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.first_fragment, container, false);
            createTable(rootView);
            return rootView;
        }

        public static FirstFragment newInstance(String string) {
            FirstFragment fragment = new FirstFragment();
            Bundle args = new Bundle();
            args.putString("msg", "PROVA 1");

            fragment.setArguments(args);
            return fragment;
        }

        void createTable(View rootView){
            TableLayout ll = (TableLayout) rootView
                    .findViewById(R.id.tableLayout);


            String categorie[];

            //          MyDatabase db=new MyDatabase(getActivity().getApplicationContext());
            //            db.open();  //apriamo il db
            MyDatabase db = new MyDatabase(getActivity().getApplicationContext());

            try {

                db.createDataBase();

            } catch (IOException ioe) {

                throw new Error("Unable to create database");

            }

            try {

                db.openDataBase();

            }catch(SQLException sqle){

                throw sqle;

            }



            Cursor c=db.fetchCategorie(); // query


            //startManagingCursor(c);





            //qui vediamo invece come reperire i dati e usarli, in questo caso li stampiamo in una textview

            int categoriaColumn=c.getColumnIndex(MyDatabase.CategorieMetaData.PRODUCT_CATEGORIA_KEY);  //indici delle colonne
            //int priceCol=c.getColumnIndex(MyDatabase.ProductsMetaData.PRODUCT_PRICE_KEY);       

            ArrayList<String> categorieList = new ArrayList<String>();

            if(c.moveToFirst()){  //se va alla prima entry, il cursore non è vuoto
                do {


                    categorieList.add(c.getString(categoriaColumn)); //add to arraylist

                    //productsTv.append("Product Name:"+c.getString(nameCol)+", Price:"+c.getInt(priceCol)+"\n"); //estrazione dei dati dalla entry del cursor
                    //Log.d("Prova", "PROVA:"+ "Product Name:"+c.getString(categoriaColumn)+", Price:"+c.getInt(priceCol)+"\n");
                } while (c.moveToNext());//iteriamo al prossimo elemento
            }




            db.close();

            categorie = categorieList.toArray(new String[categorieList.size()]);


            for (int i = 0; i < categorie.length; i++) {
                TableRow tbRow = new TableRow(getActivity().getApplicationContext());
                tbRow.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

                TextView tv1 = new TextView(getActivity().getApplicationContext());
                tv1.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                tbRow.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);

                ImageView imageView = new ImageView(getActivity().getApplicationContext());
                imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher));
                tv1.setLayoutParams(new TableRow.LayoutParams(
                        TableRow.LayoutParams.MATCH_PARENT,
                        TableRow.LayoutParams.WRAP_CONTENT));
                tv1.setId(i);

                tv1.setText(categorie[i]);
                tv1.setTextColor(Color.parseColor("#000000"));

                tbRow.addView(imageView);
                tbRow.addView(tv1);

                ll.addView(tbRow, new TableLayout.LayoutParams(
                        LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

                final String finalCategorie[] = categorie;
                final int finalI = i;
                final View finalRootView = rootView;

                tbRow.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View arg0) {

                        //             Intent newIntent = new Intent(MainActivity.this, detailActivity.class);
                        //             newIntent.putExtra("key", strings[finalI]);
                        Log.d("TEST", "Row selected: " + finalCategorie[finalI]);
                        //             startActivity(newIntent);

                        //     Intent intent = new Intent(getActivity(), EventiFragment.class);
                        //     startActivity(intent);



                    }
                });
            }

        }
    }



    public static class SecondFragment extends Fragment  {

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.second_fragment, container, false);

            TextView tv = (TextView) v.findViewById(R.id.FragmentSecond);
            tv.setText(getArguments().getString("msg"));

            return v;
        }

        public static SecondFragment newInstance(String string) {

            SecondFragment f = new SecondFragment();
            Bundle b = new Bundle();
            b.putString("msg", "Prova 2");

            f.setArguments(b);

            return f;
        }
    }

    public static class ThirdFragment extends Fragment {

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.third_fragment, container, false);

            TextView tv = (TextView) v.findViewById(R.id.FragmentThird);      
            tv.setText(getArguments().getString("msg"));

            return v;
        }

        public static ThirdFragment newInstance(String text) {

            ThirdFragment f = new ThirdFragment();
            Bundle b = new Bundle();
            b.putString("msg", "Prova 3");

            f.setArguments(b);

            return f;
        }
    }

    public static class EventiFragment extends Fragment  {

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.eventi_fragment, container, false);

            TextView tv = (TextView) v.findViewById(R.id.FragmentEventi);
            tv.setText(getArguments().getString("msg"));

            return v;
        }

        public static EventiFragment newInstance(String string) {

            EventiFragment f = new EventiFragment();
            Bundle b = new Bundle();
            b.putString("msg", "Prova 2");

            f.setArguments(b);

            return f;
        }
    }
}

first_fragment.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/relativeLayout1"
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.alain.ama.caccamo.MainActivity$PlaceholderFragment" >

<ScrollView
    android:id="@+id/scrollView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:contentDescription="@string/main_photo_description"
            android:scaleType="centerCrop"
            android:src="@drawable/main_photo" />

        <TableLayout
            android:id="@+id/tableLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
        </TableLayout>
    </LinearLayout>
</ScrollView>

eventi_fragment.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: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.alain.ama.caccamo.MainActivity$PlaceholderFragment" >
<TextView
    android:id="@+id/FragmentEventi"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="TextView"
    android:textSize="26sp"/>

因此,我將創建一個單獨的布局,而不是將布局放入兩個單獨的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:orientation="vertical" >

<RelativeLayout
    android:id="@+id/intent_replacement"
    android:layout_width="match_parent"
    android:layout_height="match_parent" > 
    <!-- Here's the stuff for the supposed intent -->

</RelativeLayout>
</RelativeLayout>

因此,在此方法中,您可以擁有一個稱為visible屬性,然后以編程方式將Layout作為一個對象,然后使用intentLayoutObject.setVisibility(true)單擊表中的某個項目時即可。

同樣,當您取回按鈕時按下intentLayoutObject.setVisibility(false)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM