Actionbarsherlock learning for Android open-source projects (1)

Source: Internet
Author: User

Recently, I learned about some well-known open-source projects in Android. Take notes as follows to facilitate future search.

These open-source projects can be downloaded through git. First, let's take a look at the actionbarshelllock project.

Due to its use of the native action bar and its related classes on ice cream sandwich, the Library requires that both it and your project are compiled with Android 4.0 or newer. the project also requires that you are compiling with JDK 1.6 in both your editor
And any build systems that you may be using.

Since the library is an extension of the official support library you must also haveandroid-support-v4.jarReferenced by your project.

On the home page of the project, there is such a paragraph, which means that it needs to be changed in android4.0 or later, and the JDK version is later than 1.6.

If you're using the eclipse
Development Environment with the ADT
Plugin version 0.9.7 or greater you can include actionbarsherlock as a library project. Create a new Android Project
In eclipse usingactionbarsherlock/Folder
As the existing source. Then, in your project properties, add the created Project under the 'libraries' section of the 'android' category

It is very easy to import an open-source project to your project: Create Your android project from the existing code, and select the root directory to actionbarsherlock, of course, there are still some details that need attention. We will not detail them here. Go to the topic and study the demo.

After running, the interface is as follows:

These examples are very classic.

1. Action Modes

    ActionMode mMode;    @Override    protected void onCreate(Bundle savedInstanceState) {        setTheme(SampleList.THEME); //Used for theme switching in samples        super.onCreate(savedInstanceState);        setContentView(R.layout.action_modes);        ((Button)findViewById(R.id.start)).setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                mMode = startActionMode(new AnActionModeOfEpicProportions());            }        });        ((Button)findViewById(R.id.cancel)).setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                if (mMode != null) {                    mMode.finish();                }            }        });    }    private final class AnActionModeOfEpicProportions implements ActionMode.Callback {        @Override        public boolean onCreateActionMode(ActionMode mode, Menu menu) {            //Used to put dark icons on light action bar            boolean isLight = SampleList.THEME == R.style.Theme_Sherlock_Light;            menu.add("Save")                .setIcon(isLight ? R.drawable.ic_compose_inverse : R.drawable.ic_compose)                .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);            menu.add("Search")                .setIcon(isLight ? R.drawable.ic_search_inverse : R.drawable.ic_search)                .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);            menu.add("Refresh")                .setIcon(isLight ? R.drawable.ic_refresh_inverse : R.drawable.ic_refresh)                .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);            menu.add("Save")                .setIcon(isLight ? R.drawable.ic_compose_inverse : R.drawable.ic_compose)                .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);            menu.add("Search")                .setIcon(isLight ? R.drawable.ic_search_inverse : R.drawable.ic_search)                .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);            menu.add("Refresh")                .setIcon(isLight ? R.drawable.ic_refresh_inverse : R.drawable.ic_refresh)                .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);            return true;        }        @Override        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {            return false;        }        @Override        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {            Toast.makeText(ActionModes.this, "Got click: " + item, Toast.LENGTH_SHORT).show();            mode.finish();            return true;        }        @Override        public void onDestroyActionMode(ActionMode mode) {        }    }}

After running, the interface is as follows:

This interface is very common in mobile phones, such as when you select an image on your mobile phone.

2. Action providers

public class ActionProviders extends SherlockActivity {    @Override    public void onCreate(Bundle savedInstanceState) {        setTheme(SampleList.THEME); //Used for theme switching in samples        super.onCreate(savedInstanceState);        setContentView(R.layout.text);        ((TextView)findViewById(R.id.text)).setText(R.string.action_providers_content);    }    /**     * {@inheritDoc}     */    @Override    public boolean onCreateOptionsMenu(Menu menu) {        super.onCreateOptionsMenu(menu);        getSupportMenuInflater().inflate(R.menu.settings_action_provider, menu);        return true;    }    /**     * {@inheritDoc}     */    @Override    public boolean onOptionsItemSelected(MenuItem item) {        // If this callback does not handle the item click, onPerformDefaultAction        // of the ActionProvider is invoked. Hence, the provider encapsulates the        // complete functionality of the menu item.        Toast.makeText(this, "Handling in onOptionsItemSelected avoided",                Toast.LENGTH_SHORT).show();        return false;    }    public static class SettingsActionProvider extends ActionProvider {        /** An intent for launching the system settings. */        private static final Intent sSettingsIntent = new Intent(Settings.ACTION_SETTINGS);        /** Context for accessing resources. */        private final Context mContext;        /**         * Creates a new instance.         *         * @param context Context for accessing resources.         */        public SettingsActionProvider(Context context) {            super(context);            mContext = context;        }        /**         * {@inheritDoc}         */        @Override        public View onCreateActionView() {            // Inflate the action view to be shown on the action bar.            LayoutInflater layoutInflater = LayoutInflater.from(mContext);            View view = layoutInflater.inflate(R.layout.settings_action_provider, null);            ImageButton button = (ImageButton) view.findViewById(R.id.button);            // Attach a click listener for launching the system settings.            button.setOnClickListener(new View.OnClickListener() {                @Override                public void onClick(View v) {                    mContext.startActivity(sSettingsIntent);                }            });            return view;        }        /**         * {@inheritDoc}         */        @Override        public boolean onPerformDefaultAction() {            // This is called if the host menu item placed in the overflow menu of the            // action bar is clicked and the host activity did not handle the click.            mContext.startActivity(sSettingsIntent);            return true;        }    }}

A menu file is used to create a menu. The content is as follows:

<menu xmlns:android="http://schemas.android.com/apk/res/android">    <item android:id="@+id/menu_item_action_provider_action_bar"        android:showAsAction="ifRoom"        android:title="Settings"        android:actionProviderClass="com.actionbarsherlock.sample.demos.ActionProviders$SettingsActionProvider"/>    <item android:id="@+id/menu_item_action_provider_overflow"        android:showAsAction="never"        android:title="Settings"        android:actionProviderClass="com.actionbarsherlock.sample.demos.ActionProviders$SettingsActionProvider"/></menu>

The running interface is as follows:

When you click the button in the upper-right corner, the settings page is displayed.

3. indeterminateprogress

public class IndeterminateProgress extends SherlockActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        setTheme(SampleList.THEME); //Used for theme switching in samples        super.onCreate(savedInstanceState);        //This has to be called before setContentView and you must use the        //class in com.actionbarsherlock.view and NOT android.view        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);        setContentView(R.layout.iprogress);        findViewById(R.id.enable).setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View arg0) {                setSupportProgressBarIndeterminateVisibility(true);            }        });        findViewById(R.id.disable).setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View arg0) {                setSupportProgressBarIndeterminateVisibility(false);            }        });    }}

3. Share action provider

public class ShareActionProviders extends SherlockActivity {    private static final String SHARED_FILE_NAME = "shared.png";    @Override    public void onCreate(Bundle savedInstanceState) {        setTheme(SampleList.THEME); //Used for theme switching in samples        super.onCreate(savedInstanceState);        setContentView(R.layout.text);        ((TextView)findViewById(R.id.text)).setText(R.string.share_action_providers_content);        copyPrivateRawResourceToPubliclyAccessibleFile();    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate your menu.        getSupportMenuInflater().inflate(R.menu.share_action_provider, menu);        // Set file with share history to the provider and set the share intent.        MenuItem actionItem = menu.findItem(R.id.menu_item_share_action_provider_action_bar);        ShareActionProvider actionProvider = (ShareActionProvider) actionItem.getActionProvider();        actionProvider.setShareHistoryFileName(ShareActionProvider.DEFAULT_SHARE_HISTORY_FILE_NAME);        // Note that you can set/change the intent any time,        // say when the user has selected an image.        actionProvider.setShareIntent(createShareIntent());        //XXX: For now, ShareActionProviders must be displayed on the action bar        // Set file with share history to the provider and set the share intent.        //MenuItem overflowItem = menu.findItem(R.id.menu_item_share_action_provider_overflow);        //ShareActionProvider overflowProvider =        //    (ShareActionProvider) overflowItem.getActionProvider();        //overflowProvider.setShareHistoryFileName(        //    ShareActionProvider.DEFAULT_SHARE_HISTORY_FILE_NAME);        // Note that you can set/change the intent any time,        // say when the user has selected an image.        //overflowProvider.setShareIntent(createShareIntent());        return true;    }    /**     * Creates a sharing {@link Intent}.     *     * @return The sharing intent.     */    private Intent createShareIntent() {        Intent shareIntent = new Intent(Intent.ACTION_SEND);        shareIntent.setType("image/*");        Uri uri = Uri.fromFile(getFileStreamPath("shared.png"));        shareIntent.putExtra(Intent.EXTRA_STREAM, uri);        return shareIntent;    }    /**     * Copies a private raw resource content to a publicly readable     * file such that the latter can be shared with other applications.     */    private void copyPrivateRawResourceToPubliclyAccessibleFile() {        InputStream inputStream = null;        FileOutputStream outputStream = null;        try {            inputStream = getResources().openRawResource(R.raw.robot);            outputStream = openFileOutput(SHARED_FILE_NAME,                    Context.MODE_WORLD_READABLE | Context.MODE_APPEND);            byte[] buffer = new byte[1024];            int length = 0;            try {                while ((length = inputStream.read(buffer)) > 0){                    outputStream.write(buffer, 0, length);                }            } catch (IOException ioe) {                /* ignore */            }        } catch (FileNotFoundException fnfe) {            /* ignore */        } finally {            try {                inputStream.close();            } catch (IOException ioe) {               /* ignore */            }            try {                outputStream.close();            } catch (IOException ioe) {               /* ignore */            }        }    }}

4 sub menus

public class SubMenus extends SherlockActivity {    @Override    public boolean onCreateOptionsMenu(Menu menu) {        SubMenu subMenu1 = menu.addSubMenu("Action Item");        subMenu1.add("Sample");        subMenu1.add("Menu");        subMenu1.add("Items");        MenuItem subMenu1Item = subMenu1.getItem();        subMenu1Item.setIcon(R.drawable.ic_title_share_default);        subMenu1Item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);        SubMenu subMenu2 = menu.addSubMenu("Overflow Item");        subMenu2.add("These");        subMenu2.add("Are");        subMenu2.add("Sample");        subMenu2.add("Items");        MenuItem subMenu2Item = subMenu2.getItem();        subMenu2Item.setIcon(R.drawable.ic_compose);        return super.onCreateOptionsMenu(menu);    }    @Override    protected void onCreate(Bundle savedInstanceState) {        setTheme(SampleList.THEME); //Used for theme switching in samples        super.onCreate(savedInstanceState);        setContentView(R.layout.text);        ((TextView)findViewById(R.id.text)).setText(R.string.submenus_content);    }            @Override    public boolean onOptionsItemSelected(MenuItem item) {    // TODO Auto-generated method stub    if(!item.hasSubMenu())    Toast.makeText(this, item.getTitle(), 3000).show();    return super.onOptionsItemSelected(item);    }}

5 tabnavigation

public class TabNavigation extends SherlockActivity implements ActionBar.TabListener {    private TextView mSelected;    @Override    public void onCreate(Bundle savedInstanceState) {        setTheme(SampleList.THEME); //Used for theme switching in samples        super.onCreate(savedInstanceState);        setContentView(R.layout.tab_navigation);        mSelected = (TextView)findViewById(R.id.text);        getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);        for (int i = 1; i <= 3; i++) {            ActionBar.Tab tab = getSupportActionBar().newTab();            tab.setText("Tab " + i);            tab.setTabListener(this);            getSupportActionBar().addTab(tab);        }    }    @Override    public void onTabReselected(Tab tab, FragmentTransaction transaction) {    }    @Override    public void onTabSelected(Tab tab, FragmentTransaction transaction) {        mSelected.setText("Selected: " + tab.getText());    }    @Override    public void onTabUnselected(Tab tab, FragmentTransaction transaction) {    }}

6 tab navigationcollapse

public class TabNavigationCollapsed extends TabNavigation {    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        //The following two options trigger the collapsing of the main action bar view.        //See the parent activity for the rest of the implementation        getSupportActionBar().setDisplayShowHomeEnabled(false);        getSupportActionBar().setDisplayShowTitleEnabled(false);    }}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.