码迷,mamicode.com
首页 > 其他好文 > 详细

ActionBar的一些理解

时间:2015-02-02 19:28:36      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

1.基本理解

ActionBar是android中的一个控件,从名字可以知道,是一种tab分页式的控件。

当你想要分页的显示的时候,它就派上用场了。

 

2.另一种理解

我假设我自己要设计一个这样的控件,我会有些什么需求呢?

【UI】

我希望每个tab页都有自己的“名字”。

我希望每个tab页都有自己的“界面”。

 

【响应】

我希望每个tab点击的时候,tab页可以发生一些变化,这种变化是我可以自己控制的。

 

3.标准“解释”

【UI】

创建一个ActionBar

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final ActionBar bar = getActionBar();
        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
        ......      
}

增加一个tab页:

用函数addTab来增加一个tab页;参数Tab类,可以用下面的方法设置该tab页的一些属性,比如名称等。

bar.addTab(bar.newTab()
                .setText("QuickSend")
                .setTabListener(new TabListener<FragmentQuickSend>(
                        this, "QuickSend", FragmentQuickSend.class)));

【响应】

tab页切换时做的动作:

如果希望在切换到新页有所响应的话,需要向tab页注册响应类TabListener。该类中需要实现一些函数,这些函数就会在特定时刻被调用。

    public static class TabListener implements ActionBar.TabListener {
public TabListener() {
           
        }public void onTabSelected(Tab tab, FragmentTransaction ft) {
           
        }

        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
           
        }

        public void onTabReselected(Tab tab, FragmentTransaction ft) {
           
        }
    }

 

4.一个例子

MainActivity.java

package com.example.tabtest;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ActionBar.Tab;


public class MainActivity extends Activity {
    public String m_strFilePath;
    FragmentQuickSend m_fragQSend;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final ActionBar bar = getActionBar();
        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);

        bar.addTab(bar.newTab()
                .setText("Photo")
                .setTabListener(new TabListener<FragmentPhoto>(
                        this, "Photo", FragmentPhoto.class)));
      
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
    }

    public static class TabListener<T extends Fragment> implements ActionBar.TabListener {
        private final Activity mActivity;
        private final String mTag;
        private final Class<T> mClass;
        private final Bundle mArgs;
        private Fragment mFragment;

        public TabListener(Activity activity, String tag, Class<T> clz) {
            this(activity, tag, clz, null);
        }

        public TabListener(Activity activity, String tag, Class<T> clz, Bundle args) {
            mActivity = activity;
            mTag = tag;
            mClass = clz;
            mArgs = args;

            // Check to see if we already have a fragment for this tab, probably
            // from a previously saved state.  If so, deactivate it, because our
            // initial state is that a tab isn‘t shown.
            mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag);
            if (mFragment != null && !mFragment.isDetached()) {
                FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction();
                ft.detach(mFragment);
                ft.commit();
            }
        }

        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            if (mFragment == null) {
                mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs);
                ft.add(android.R.id.content, mFragment, mTag);
            } else {
                ft.attach(mFragment);
            }
        }

        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            if (mFragment != null) {
                ft.detach(mFragment);
            }
        }

        public void onTabReselected(Tab tab, FragmentTransaction ft) {
            Toast.makeText(mActivity, "Reselected!", Toast.LENGTH_SHORT).show();
        }
    }
}

FragmentPhoto.java

/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.tabtest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import com.example.tabtest.R;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class FragmentPhoto extends Fragment {
        
    private final static String TAG = "CameraActivity";
    private SurfaceView surfaceView;
    private SurfaceHolder surfaceHolder;
    private Camera camera;
    private File picture;
    private Button btnSave;
    
    /**
     * When creating, retrieve this instance‘s number from its arguments.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
    }

    public void onActivityCreated(Bundle savedInstanceState) {  
        super.onActivityCreated(savedInstanceState);
        
        setupViews();
    }
    
    /**
     * The Fragment‘s UI is just a simple text view showing its
     * instance number.
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.layout_photo, container, false);
    }
    
    private void setupViews(){
        surfaceView = (SurfaceView) getView().findViewById(R.id.surCameraView); // Camera interface to instantiate components
        surfaceHolder = surfaceView.getHolder(); // Camera interface to instantiate components
        surfaceHolder.addCallback(surfaceCallback); // Add a callback for the SurfaceHolder
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        
        btnSave = (Button) getView().findViewById(R.id.btnPhoto);
        
        btnSave.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                //takePic();
            }
        });
    }

    private void takePic() {

        camera.stopPreview();// stop the preview

        camera.takePicture(null, null, pictureCallback); // picture
    }

    // Photo call back
    Camera.PictureCallback pictureCallback = new Camera.PictureCallback() {
        //@Override
        public void onPictureTaken(byte[] data, Camera camera) {
            new SavePictureTask().execute(data);
            camera.startPreview();
        }
    };

    // save pic
    class SavePictureTask extends AsyncTask<byte[], String, String> {
        @Override
        protected String doInBackground(byte[]... params) {
            String fname = DateFormat.format("yyyyMMddhhmmss", new Date()).toString()+".jpg";
            
            Log.i(TAG, "fname="+fname+";dir="+Environment.getExternalStorageDirectory());
            //picture = new File(Environment.getExternalStorageDirectory(),fname);// create file
            
            picture = new File(Environment.getExternalStorageDirectory()+"/"+fname);
            
            try {
                FileOutputStream fos = new FileOutputStream(picture.getPath()); // Get file output stream
                fos.write(params[0]); // Written to the file
                fos.close(); 
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    // SurfaceHodler Callback handle to open the camera, off camera and photo size changes
    SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {

        public void surfaceCreated(SurfaceHolder holder) {
            Log.i(TAG, "surfaceCallback====");
            camera = Camera.open(); // Turn on the camera
            try {
                camera.setPreviewDisplay(holder); // Set Preview
            } catch (IOException e) {
                camera.release();// release camera
                camera = null;
            }
        }

        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                int height) {
            Log.i(TAG,"====surfaceChanged");
            Camera.Parameters parameters = camera.getParameters(); // Camera parameters to obtain
            parameters.setPictureFormat(PixelFormat.JPEG);// Setting Picture Format
//                parameters.set("rotation", 180); // Arbitrary rotation
            camera.setDisplayOrientation(0);
//                parameters.setPreviewSize(400, 300); // Set Photo Size
            camera.setParameters(parameters); // Setting camera parameters
            camera.startPreview(); // Start Preview
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            Log.i(TAG,"====surfaceDestroyed");
            camera.stopPreview();// stop preview
            camera.release(); // Release camera resources
            camera = null;
        }
    };

}

layout_photo.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <SurfaceView
        android:id="@+id/surCameraView"
        android:layout_width="match_parent"
        android:layout_height="139dp"
        android:layout_weight="0.00" />

    <Button
        android:id="@+id/btnPhoto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.08"
        android:text="Button" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.19"
        android:text="          " />

</LinearLayout>

 

ActionBar的一些理解

标签:

原文地址:http://www.cnblogs.com/bluebbc/p/4268282.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!