Android SDK Samples讲解之ActionBarCompat-Basic

为什么会选择这个开始学呢?我也不知道,纯属缘分。
首先,不是新建project,而是看看这个sample运行出来是什么样,有没有信心来学习。

在这个例子中我学到了:

  • 如何更换Launcher Icon
  • 如何更换theme(系统自带,非自定义)
  • 如何制作9patch,俗称点9图
  • 如何确定第一个启动的Activity
  • XML中CDATA的作用是什么
  • 如何通过XML和后台代码的方式添加menu
  • -

如果你也跟着sample做完并实现了效果,把你学到的知识也写下来吧。

好了,还是新建一个Project慢慢来学习吧,我的项目名称叫LTY-ActionBarCompat-Basic。

把Sample里面的图片文件拷贝到相同目录,省得你找不到一模一样的
drawable
看看这几文件夹都有些啥:
drawable-mdpi:图标32*32 launcher48*48
这里写图片描述
drawable-hdpi:图标48*48 launcher72*72 9patch:14*18
这里写图片描述
drawable-xhdpi:图标64*64 launcher96*96
这里写图片描述
drawable-xxhdpi:launcher144*144
这里写图片描述

我现在对mdpi、hdpi之类属于一知半解,分析了一下几个文件夹里的图标对应的大小,肯定是有说法的,我要去百度。

先换个图标吧。打开manifests下的AndroidManifest.xml,找到

android:icon="@mipmap/ic_launcher"

换成:

android:icon="@drawable/ic_launcher"

什么也不做,点击运行,手机上的图标是不是这个?
icon

看看Sample中的启动Activity吧,
还是在AndroidManifest.xml里,找到

<activity android:name=".MainActivity">

根据这个,再到java下找到MainActivity里看到这个:

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

纳尼?我好像没有sample_main啊?再等等,

public class MainActivity extends ActionBarActivity

我自己新建的项目里是这样的啊:

public class MainActivity extends AppCompatActivity 

不如改成和sample一样的吧。这一改不要紧,改成一样的之后,给我在ActionBarActivity上加了删除线,提示已过时,百度了一下,原来用AppCompatActivity就可以,确实过时了。

回到sample_main的问题,到layout目录中新建一个sample_main.xml。

<?xml version="1.0" encoding="utf-8"?>

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    android:text="@string/intro_message"
    android:gravity="center" />

对,全部文件就是这么多,没布局的事儿。
有没有看到android:text=”@string/intro_message”是红色的,因为咱没有啊,到sample里找到intro_message是在values下的base-strings.xml中。base-strings.xml也没有,没关系,新建一个,把sample中的intro_message定义抄过来。

    <string name="intro_message">
        <![CDATA[


            This sample shows you how to use ActionBarCompat to create a basic Activity which
            displays action items. It covers inflating items from a menu resource, as well as adding
            an item in code. Items that are not shown as action items on the Action Bar are
            displayed in the action bar overflow.


        ]]>
    </string>

等等,孤陋寡闻的我不太能理解CDATA是个啥意思,百度,哦~原来放在这里面的内容会被解析器忽略,秒懂了。

这些都整完以后,该修改R.layout啦

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

把原有的activity_main果断地修改成sample_main。
不如预览看看效果吧。

嗯,显示了appname,textview里的内容也显示了。看到这里,你不禁要问:为什么sample是黑的,这个是蓝的呢?头上的LTY-ActionBarCompat-Basic又是哪来的呢,我也没设置啊。

不急不急,黑的咱到最后再说,先把主要目的达到,顺便讲一下LTY-ActionBarCompat-Basic是怎么来的,在strings.xml中找到啦:

<string name="app_name">LTY-ActionBarCompat-Basic</string>

看看sample,人家不写在strings.xml中,而是放在base-strings.xml中,虽然我现在也不明白为什么要这样放,但是跟着做了,可能是一种良好的习惯?也有可能是写这个sample的人喜欢这么干?这是我的理解,如果你知道最确切的原因,还请告诉我哦!

Next,跟着sample新建一个menu文件夹,并在menu文件夹中新建main.xml,以下是该文件中所有代码:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:support="http://schemas.android.com/apk/res-auto" >


    <item
        android:id="@+id/menu_refresh"
        android:icon="@drawable/ic_action_refresh"
        android:title="@string/menu_refresh"
        support:showAsAction="ifRoom"/>

    <item
        android:id="@+id/menu_settings"
        android:icon="@drawable/ic_action_settings"
        android:title="@string/menu_settings"
        support:showAsAction="never"/>
</menu>

可以看出,在这里有两个item,定义了它们各自的id,使用哪个图作图标,名称,还有最具差异的support:showAsAction,refresh是ifRoom,settings是never,等会运行的时候看看各自有什么不一样吧。(我只复制了menu_refresh这一段,menu_settings这一段没有复制,主要是想一点一点地变)
android:title是不是红字啦?因为咱没有menu_refresh和menu_settings啊,跟着sample到strings.xml中添加以下代码吧:

<string name="menu_refresh">Refresh</string>
<string name="menu_location">Location</string>
<string name="menu_settings">Settings</string>

下面,在.java里写一段代码来加载main.xml,要不然,咱们的menu永远也不会出现哦。

@Override
public boolean onCreateOptionsMenu(Menu menu){
    getMenuInflater().inflate(R.menu.main,menu);
    return true;
}

预览看效果吧:

上面我已经说过了,我在main.xml里只复制了menu_refresh这一段,所以这里只出现了refresh一个图标,哇,是不是有点小小地激动与成就感呢,毕竟跟着sample做出点东西来了。趁着还有自信,接着往下做吧。这个就是通过xml的方式增加了一个menu,接下来的location图标则是通过后台代码的方式添加上去的。
在刚才代码的基本上增加

MenuItem locationItem=menu.add(0,R.id.menu_location,0,"Location");
    locationItem.setIcon(R.drawable.ic_action_location);

全部是这样滴:

@Override
public boolean onCreateOptionsMenu(Menu menu){
    getMenuInflater().inflate(R.menu.main,menu);

    MenuItem locationItem=menu.add(0,R.id.menu_location,0,"Location");
    locationItem.setIcon(R.drawable.ic_action_location);

    return true;
}

R.drawable.ic_action_location咱早就复制图片来了,R.id.menu_location似乎还没有添加过,还是跟着sample在Values目录下新建一个ids.xml,加入<item name="menu_location" type="id"/>

这样就算是动态添加了一个menu啦,是不是好简单。
预览,refresh旁边多出三个点,点开三个点,显示“Location”
这里写图片描述

这里写图片描述

这个和sample里有点不一样,sample里是个图标,和refresh一样,不着急,接着往下做。
还在是.java里添加代码MenuItemCompat.setShowAsAction(locationItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);

完整的是这样:

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.main,menu);

        MenuItem locationItem=menu.add(0,R.id.menu_location,0,"Location");
        locationItem.setIcon(R.drawable.ic_action_location);

        MenuItemCompat.setShowAsAction(locationItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
        return true;
    }

这一句话决定了它是否以图标形式显示,预览。refresh旁边的三个点没有了,取而代之的是一个Location的图标
这里写图片描述

好了,把之前没有加上的menu_settings段加入到main.xml中,就完整啦。
settings是不是和刚才没有设置location的showAsAction一样呢,要点开三个点才能看见。
这里写图片描述

sample里还有一段这样的代码:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menu_refresh:
            // Here we might start a background refresh task
            return true;

        case R.id.menu_location:
            // Here we might call LocationManager.requestLocationUpdates()
            return true;

        case R.id.menu_settings:
            // Here we would open up our settings activity
            return true;
    }

    return super.onOptionsItemSelected(item);
}
// END_INCLUDE(menu_item_selected)

我研究了一下,目前没什么用,不用将来你要用到的时候,就可以直接拿来啦。

到现在为止,menu都已添加好,还差最后一步:theme,下面就来改成和sample一样的黑色吧。
打开manifests下的AndroidManifest.xml,找到

android:theme="@style/AppTheme"

改成:

android:theme="@style/Theme.AppCompat"

预览:

哇,实现了!和sample一模一样。
点九图没发现用在哪里,不过特地去研究了一下点九图。

下载本文中的原法原味的sample

附上完整的.java

package com.lty.asus.lty_actionbarcompat_basic;

import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

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


    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.main,menu);

        MenuItem locationItem=menu.add(0,R.id.menu_location,0,"Location");
        locationItem.setIcon(R.drawable.ic_action_location);

        MenuItemCompat.setShowAsAction(locationItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_refresh:
                // Here we might start a background refresh task
                return true;

            case R.id.menu_location:
                // Here we might call LocationManager.requestLocationUpdates()
                return true;

            case R.id.menu_settings:
                // Here we would open up our settings activity
                return true;
        }

        return super.onOptionsItemSelected(item);
    }
    // END_INCLUDE(menu_item_selected)
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
List of Sample Apps The list below provides a summary of the sample applications that are available with the Android SDK. Using the links on this page, you can view the source files of the sample applications in your browser. You can also download the source of these samples into your SDK, then modify and reuse it as you need. For more information, see Getting the Samples. API Demos A variety of small applications that demonstrate an extensive collection of framework topics. Backup and Restore A simple example that illustrates a few different ways for an application to implement support for the Android data backup and restore mechanism. Bluetooth Chat An application for two-way text messaging over Bluetooth. BusinessCard An application that demonstrates how to launch the built-in contact picker from within an activity. This sample also uses reflection to ensure that the correct version of the contacts API is used, depending on which API level the application is running under. Contact Manager An application that demonstrates how to query the system contacts provider using the ContactsContract API, as well as insert contacts into a specific account. Home A home screen replacement application. JetBoy A game that demonstrates the SONiVOX JET interactive music technology, with JetPlayer. Live Wallpaper An application that demonstrates how to create a live wallpaper and bundle it in an application that users can install on their devices. Lunar Lander A classic Lunar Lander game. Multiple Resolutions A sample application that shows how to use resource directory qualifiers to provide different resources for different screen configurations. Note Pad An application for saving notes. Similar (but not identical) to the Notepad tutorial. SampleSyncAdapter Demonstrates how an application can communicate with a cloud-based service and synchronize its data with data stored locally in a content provider. The sample uses two related parts of the Android framework — the account manager and the synchronization manager (through a sync adapter). Searchable Dictionary A sample application that demonstrates Android's search framework, including how to provide search suggestions for Quick Search Box. Snake An implementation of the classic game "Snake." Soft Keyboard An example of writing an input method for a software keyboard. Spinner A simple application that serves as an application-under-test for the SpinnerTest sample application. SpinnerTest An example test application that contains test cases run against the Spinner sample application. To learn more about the application and how to run it, please read the Activity Testing tutorial. TicTacToeLib An example of an Android library project that provides a game-play Activity to any dependent application project. For an example of how an application can use the code and resources in an Android library project, see the TicTacToeMain sample application. TicTacToeMain An example of an Android application that makes use of code and resources provided in an Android library project. Specifically, this application uses code and resources provided in the TicTacToeLib library project. Wiktionary An example of creating interactive widgets for display on the Android home screen. Wiktionary (Simplified) A simple Android home screen widgets example.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值