2017年4月10日 星期一

Android studio 建立Tabbed Activity




上面影片就是Tabbed Activity效果,準備弄個漂亮的介面來寫擷取和錄製Screen的APP
A.
android studio新增Tabbed Activity














B.
public boolean onCreateOptionsMenu(Menu menu)這個methoid 會產生menu表單
要新增menu item在在menu目錄下menu_main.xml來新增(如下圖)
public boolean onOptionsItemSelected(MenuItem item) 處理選單事件



C.
mViewPager.addOnPageChangeListener(...)這是額外加上,處理ViewPaber更改頁面事件,譬如來更改toolbar的title,icon
D.
Fragment:
public View onCreateView(....)這裡來更改ViewPager裡面的原件或內容,
不要用getArguments().getInt(ARG_SECTION_NUMBER)去判斷目前viewPager當前的頁面
E.
FragmentPagerAdapter:
public int getCount() 設定幾個頁面
F.
menu icon不顯示(google上找到)

把MenuBuilder的setOptionalIconsVisible設為true就能顯示icon

values目錄下有styles.xml,string.xml,color.xml,dimens.xml
styles.xml自訂theme
color.xml自訂color對應styles.xml
string.xml自訂的文字
dimens.xml自訂的dimens




icon圖片放在drawable



package com.example.yplin.screenrecorder;
//res-value-styles.xml自訂style對應color.xml
//可將icon png複製到res-drawable,只能使用小寫會底線命名
//appbar的layout_behavior必須添加屬性@string/appbar_scrolling_view_behavior,不被攔截
//toolbar的layout_scroollFlags將scrool取消讓toolbar不能滑動
//增加menu item這裡加入選項,res-menu-menu_main.xml
//讓Icon 顯示,把MenuBuilder的setOptionalIconsVisible設為true就能顯示icon
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.menu.MenuBuilder;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import android.view.Window;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.lang.reflect.Method;

public class MainActivity 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;
    private static int mpage=0;//一開始第0頁    
    private String recorder_text="左右滑動來選擇錄製或截圖";
    

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

        final 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);                            
        toolbar.setTitle("全螢幕截圖");
        toolbar.setLogo(R.drawable.image_recorder);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);//add a button        
        fab.setOnClickListener(new View.OnClickListener() {
        @Override            
        public void onClick(View view) {                                        //listener  
              //由下而上滑動                
          Snackbar.make(view, recorder_text, Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
                //這裡放截圖事件            }
        });

        //我們用addOnPageChangeListeneraddOnPageChangeListener來取得當前page        
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override            
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }
            @Override            public void onPageSelected(int position) {
                Log.d("TAG","position:"+position);
                switch(position){
                    case 0:
                        toolbar.setTitle("截屏錄屏服務");
                        toolbar.setLogo(R.drawable.image_recorder);
                        recorder_text="左右滑動來選擇錄製或截圖";
                        break;
                    case 1:
                        toolbar.setTitle("全螢幕截屏");
                        toolbar.setLogo(R.drawable.capture1);
                        recorder_text="開始全螢幕截屏,按左上角開始擷取";
                        break;
                    case 2:
                        toolbar.setTitle("區域螢幕截屏");
                        toolbar.setLogo(R.drawable.ic_phone_android);
                        recorder_text="開始區域螢幕截屏,按左上角開始,點擊螢幕擷取";
                        break;
                    case 3:
                        toolbar.setTitle("全螢幕錄屏");
                        toolbar.setLogo(R.drawable.camera_photo);
                        recorder_text="開始全螢幕錄屏,按左上角開始錄屏";
                        break;
                }
            }
            @Override            public void onPageScrollStateChanged(int state) {

            }
        });




    }   
       //這裡加入選項,res-menu-menu_main.xml    
       @Override    
       public boolean onCreateOptionsMenu(Menu menu) {
        //讓Icon 顯示,把MenuBuilder的setOptionalIconsVisible設為true就能顯示icon        
       if(menu.getClass().getSimpleName().equals("MenuBuilder")){
            try{
                Method m=menu.getClass().getDeclaredMethod("setOptionalIconsVisible",Boolean.TYPE);
                m.setAccessible(true);
                m.invoke(menu,true);
            }catch(Exception e){}
        }

        /**這也行,但有紅線error但可運行        
        if(menu instanceof MenuBuilder){            
           MenuBuilder m=(MenuBuilder) menu;            
           m.setOptionalIconsVisible(true);        }        
         */        
        getMenuInflater().inflate(R.menu.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();
        Log.d("TAG MENU ID",String.valueOf(id));
        Log.d("TAG action ID",String.valueOf(R.id.menu2));
        //根據選項切換viewpager        
        if (id == R.id.menu1) {mViewPager.setCurrentItem(0,true);}//return true;}        
        if (id == R.id.menu2) {mViewPager.setCurrentItem(2,true);}//return true;}        
        if (id == R.id.menu3) {mViewPager.setCurrentItem(3,true);}//return true;}        
        if (id == R.id.menu4) {mViewPager.setCurrentItem(1,true);}//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";
        //private static final String ARG_SECTION_NUMBER = "ARG_PAGE";        
        private RelativeLayout mrelativelayout;  //主容器        
        private TextView mtextView;
        private View rootView=null;
        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);
            PlaceholderFragment fragment = new PlaceholderFragment();
            fragment.setArguments(args);
            return fragment;
        }

        @Override        
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            if(rootView==null) {
                rootView = inflater.inflate(R.layout.fragment_main, container, false);
            }
            mrelativelayout=(RelativeLayout) rootView.findViewById(R.id.RL);
            mtextView = (TextView) rootView.findViewById(R.id.textView);
            //mtextView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));            
            //注意不能用getArguments().getInt(ARG_SECTION_NUMBER)取得當前page取得當前page            
            //因為這會下到欲轉的頁面一開始會是0,1            
            //我們用addOnPageChangeListeneraddOnPageChangeListener來取得當前page            
            //textView.setText(String.valueOf(getArguments().getInt(ARG_SECTION_NUMBER)));            
            mrelativelayout.removeAllViews();//一開始先清除頁面上所有元件            
            //根據頁面需要加上元件            
            if(getArguments().getInt(ARG_SECTION_NUMBER)==1){add_pag1(rootView);}
            if(getArguments().getInt(ARG_SECTION_NUMBER)==2){add_pag2(rootView);}
            if(getArguments().getInt(ARG_SECTION_NUMBER)==3){add_pag3(rootView);}
            if(getArguments().getInt(ARG_SECTION_NUMBER)==4){add_pag4(rootView);}
            //Log.d("TAG",String.valueOf(getArguments().getString("title")));            
            //if(getArguments().getInt(ARG_SECTION_NUMBER)==2){add_pag2(rootView);}            
            return rootView;
        }
        //頁面1,新增元件位置時,xml不要相對會變動的元件,否則位置會跑掉        
        private void add_pag1(View v){
            mrelativelayout.removeAllViews();
            mrelativelayout.addView(mtextView);
            mtextView.setText("作者:Y.P.LIN");
            Log.d("TAG","screen 4");
        }
        //頁面2,新增元件位置時,xml不要相對會變動的元件,否則位置會跑掉        
        private void add_pag2(View v){
            mrelativelayout.removeAllViews();
            mrelativelayout.addView(mtextView);
            mtextView.setText("全螢幕截圖");
            Log.d("TAG","screen 1");
        }
        //頁面3,新增元件位置時,xml不要相對會變動的元件,否則位置會跑掉        
        private void add_pag3(View v){
            mrelativelayout.removeAllViews();
            mrelativelayout.addView(mtextView);
            mtextView.setText("區域螢幕截圖");
            Log.d("TAG","screen 2");

        }
        //頁面4,新增元件位置時,xml不要相對會變動的元件,否則位置會跑掉        
        private void add_pag4(View v){
            mrelativelayout.removeAllViews();
            mrelativelayout.addView(mtextView);
            mtextView.setText("全螢幕錄屏");
            Log.d("TAG","screen 3");
        }
    }//class  PlaceholderFragment
    /**     
    * 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 PlaceholderFragment (defined as a static inner class below).            
           return PlaceholderFragment.newInstance(position + 1);
        }
        //幾個頁面        @Override        public int getCount() {
            // Show 3 total pages.            return 4;
        }
        @Override        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "SECTION 0";
                case 1:
                    return "SECTION 1";
                case 2:
                    return "SECTION 2";
                case 3:
                    return "SECTION 3";

            }
            return null;
        }
    }
}

沒有留言: