Activity的跳转

建好安卓项目后,在layout新建两个布局xml,新建一个xml都要在AndroidMainfest上注册。如:

        <activity 
            android:name="com.example.test.Other" />

此标签是在前一个activity下进行的。

在java端,主要文件是:

package com.example.test;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获得buttonID
        Button button = (Button)findViewById(R.id.myBytton);
        //监听Button
        button.setOnClickListener(new Button.OnClickListener()
        {
            @Override
            public void onClick(View v) {
                //实现显示消息
                //DisplayToast("事件触发了");
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, Other.class);
                MainActivity.this.startActivity(intent);
            }
        });
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    private void DisplayToast(String string) {
        // TODO Auto-generated method stub
        Toast.makeText(this, string, Toast.LENGTH_LONG).show();
    }
}

在要跳转到的类中,写成:

package com.example.test;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Other extends Activity{
    private TextView myTextView = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.other);  // 导入的是other.xml布局
        myTextView = (TextView)findViewById(R.id.myTextView);
    }

}

运行即可。

源码

原文地址:https://www.cnblogs.com/newlooker/p/2999119.html