安卓专题

安卓开发教程之三 开始一个新的Activity

上页

  通过之前案例,我们有了一个发送消息的功能,下面我们开发接受这个发送消息的功能。

  为了响应点击按钮的功能,需要在activity_main.xml增加android:onClick 属性:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_send"
    android:onClick="sendMessage" />

"sendMessage"是方法名称,当用户点按这个按钮,系统用来调用的。

咋MainActivity 类我们增加一个方法:

/** Called when the user clicks the Send button */
public void sendMessage(View view) {
    // Do something in response to button
} 这个方法必须是public,必须有返回值,必须有一个输入参数View


建立一个意图Intent

  Intent提供了一种通用的消息系统,相当于消息或事件,它允许在你的应用组件如Activity与其它的应用组件间传递Intent来执行动作和产生事件。

  在sendMessage方法内加入

Intent intent = new Intent(this, DisplayMessageActivity.class);

意图的构造函数中第一参数this是 Context, Activity是Context子类。

第二参数就是需要处理事件的消费者类名称。

一个意图可以携带 key-value形式的数据集合,称为extras,为了能从extras中查询数据,规定一个键。

public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";

开始创建第二个Activity

  调用startActivity() 传递给意图,能够调用第二Activity,系统会接受到通知启动意图提供的那个Activity。

/** Called when the user clicks the Send button */
public void sendMessage(View view) {
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.edit_message);
    String message = editText.getText().toString();    //将消息传递到下一个活动
    intent.putExtra(EXTRA_MESSAGE, message);     //启动下一个活动
    startActivity(intent);
}

 

创建第二个Activity

  在eclipse里选择new ->Andorid中选择Activity,选择Blank Activity:

按图中选择,这个活动的名称是DisplayMessageActivity,Eclipse会自动将layoutname改为activity_display_message。

打开新建的活动类,里面有:

 onCreate()  这是需要的。

onCreateOptionsMenu() 不需要,删除

onOptionsItemSelected()是处理Action bar的up行为,留着。

因为ActionBar只存在 HONEYCOMB或更高版本,你必须判断,使用getActionBar()检查当前版本。

加入@SuppressLint("NewApi") 避免lint 错误。

最后这个活动的代码如下:

@SuppressLint("NewApi")
public class DisplayMessageActivity extends Activity {

   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display_message);
        // Show the Up button in the action bar.
        setupActionBar();
    }

    /**
     * Set up the {@link android.app.ActionBar}, if the API is available.
     */
    @SuppressLint("NewApi")
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void setupActionBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            getActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            // This ID represents the Home or Up button. In the case of this
            // activity, the Up button is shown. Use NavUtils to allow users
            // to navigate up one level in the application structure. For
            // more details, see the Navigation pattern on Android Design:
            //
            // http://developer.android.com/design/patterns/navigation.html#up-vs-back
            //
            NavUtils.navigateUpFromSameTask(this);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}

唯一错误的地方是   setContentView(R.layout.activity_display_message); ,因为我们没有定义。

增加标题字符串

  打开 strings.xml,加入:

<resources>
    ...
    <string name="title_activity_display_message">My Message</string>
</resources>

注册Activity到manifest中

  正如我们在AngularJS中将服务注册到模块中一样,我们需要注册活动到 AndroidManifest.xml文件。当然Eclipse一般在你创建完成后帮助你自动加入。

<application ... >
    ...
    <activity
        android:name="com.javacodegeeks.android.helloword.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.example.myfirstapp.MainActivity" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myfirstapp.MainActivity" />
</application>

接受意图

  在 DisplayMessageActivity class’s onCreate()方法中加入:

Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

每一项活动是由一个Intent调用的,不管用户如何导航。通过getIntent你可以得到你启动的活动那个意图,获取其中包含的数据。

显示信息

  为了显示信息,需要调用 TextView widget 使用 setText(). 设置文本信息。然后再调用setContentView()就设置到当前布局中。

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

    // Get the message from the intent
    Intent intent = getIntent();
    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

    // Create the text view
    TextView textView = new TextView(this);
    textView.setTextSize(40);
    textView.setText(message);

    // Set the text view as the activity layout
    setContentView(textView);
}

运行结果:

如果有关No resource found that matches the given name (at 'title' with value '@string/menu_settings')之类出错,可能是Eclipse在res/下多创建了一个menu目录,将其删除即可。

该项目源码下载

返回安卓首页