Android 开发————5、Activity

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/Fly_hps/article/details/80201141

Activity的四个重要状态


Activity的生命周期

Activity的回调函数

onStart()方法:启动Activity时被回调,也就是当一个Activity变为显示时被回调。

onRestart()方法:重新启动Activity时被回调,该方法总是在onStart()方法以后执行。

onPause()方法:暂停Activity时被回调。该方法需要被非常快速地执行,因为直到该方法执行完毕之后,下一个Activity才能被恢复。在改方法中,通常用于持久保存数据。

onResume()方法:当Activity由暂停状态恢复为活动状态时调用。调用该方法后,该Activity位于Activity栈的栈顶。该方法总是在onPause()方法之后执行。

onStop()方法:停止Activity时被回调。

onDestroy()方法:销毁Activity时被回调。

Activity的创建、配置、启动、关闭

创建部分:

A、创建一个Activity一般是继承android.app包中的Activity类,不过在不同的应用场景下,也可以继承Activity的子类。创建一个继承Activity类的Activity,名称为MainActivity的具体代码如下:

import android.app.Activity;
public class MainActivity extends Activity {
}

B、之后需要重写需要的回调函数,一般情况下都需要重写onCreate()方法,并且在该方法中调用setContentView()方法设置要显示的视图。
例如,在步骤(1)中创建的Activity中,重写onCreate()方法,并且设置要显示的视图的具体代码如下:

import android.app.Activity;
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

}

配置部分(在使用工具编程是会自动完成此操作):

创建Activity后,还需要在AndroidManifest.xml文件中配置该Activity,

具体的配置方法是在<application></application>标记中添加<activity></activity>标记实现。<activity>标记的基本格式如下:

<activity
        android:icon="@drawable/图标文件名"
        android:name="实现类"
        android:label="说明性文字"
        android:theme="要应用的主题"
    …
    >
    …
</activity>

例如上面的例子中:

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".LinearlayoutActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
        </intent-filter>
    </activity>
</application>

启动部分:

import android.app.Activity;
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        setContentView(R.layout.main);
        Button  button=(Button)findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                Intent intent=new Intent(MainActivity.this,DetailActivity.class);//创建Intent对象
                startActivity(intent);                               //启动Activity
            }
            
        });
    }

关闭Activity

import android.app.Activity;
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);
        Button  button=(Button)findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                finish();                           //关闭Activity
            }
        });
    }

Bundle在多个Activity中交换数据

实例:

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button submit=(Button)findViewById(R.id.submit);   //获取提交按钮
        submit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                String user=((EditText)findViewById(R.id.user)).getText().toString();  //获取输入的用户
                String pwd=((EditText)findViewById(R.id.pwd)).getText().toString();    //获取输入的密码
                String repwd=((EditText)findViewById(R.id.repwd)).getText().toString();    //获取输入的确认密码
                String email=((EditText)findViewById(R.id.email)).getText().toString();    //获取输入的E-mail地址
                if(!"".equals(user) && !"".equals(pwd) && !"".equals(email)){

                    if(!pwd.equals(repwd)){    //判断两次输入的密码是否一致
                        Toast.makeText(MainActivity.this, "两次输入的密码不一致,请重新输入!", Toast.LENGTH_LONG).show();
                        ((EditText)findViewById(R.id.pwd)).setText("");    //清空密码编辑框
                        ((EditText)findViewById(R.id.repwd)).setText("");  //清空确认密码编辑框
                        ((EditText)findViewById(R.id.pwd)).requestFocus(); //让密码编辑框获得焦点
                    }else{ //将输入的信息保存到Bundle中,并启动一个新的Activity显示输入的用户注册信息
                        Intent intent=new Intent(MainActivity.this,RegisterActivity.class);
                        Bundle bundle=new Bundle();    //创建并实例化一个Bundle对象
                        bundle.putCharSequence("user", user);  //保存用户名
                        bundle.putCharSequence("pwd", pwd);    //保存密码
                        bundle.putCharSequence("email", email);    //保存E-mail地址
                        intent.putExtras(bundle);  //将Bundle对象添加到Intent对象中
                        startActivity(intent); //启动新的Activity

                    }
                }else{
                    Toast.makeText(MainActivity.this, "请将注册信息输入完整!", Toast.LENGTH_LONG).show();
                }

            }
        });
    }
}

获取部分:

public class RegisterActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register); //设置该Activity中要显示的内容视图
        Intent intent=getIntent(); //获取Intent对象
        Bundle bundle=intent.getExtras();  //获取传递的数据包
        TextView user=(TextView)findViewById(R.id.user);      //获取显示用户名的TextView组件
        user.setText("用户名:"+bundle.getString("user"));    //获取输入的用户名并显示到TextView组件中
        TextView pwd=(TextView)findViewById(R.id.pwd);    //获取显示密码的TextView组件
        pwd.setText("密码:"+bundle.getString("pwd"));       //获取输入的密码并显示到TextView组件中
        TextView email=(TextView)findViewById(R.id.email);    //获取显示E-mail的TextView组件
        email.setText("E-mail:"+bundle.getString("email"));       //获取输入的E-mail并显示到TextView组件中

    }

}
展开阅读全文

android 开发Activity转换问题

05-19

错误:rn05-19 04:08:45.885: E/AndroidRuntime(743): FATAL EXCEPTION: mainrn05-19 04:08:45.885: E/AndroidRuntime(743): java.lang.RuntimeException: Unable to start activity ComponentInfocom.zhenglingkun.myfilemanage/com.zhenglingkun.myfilemanage.FileActivity: java.lang.NullPointerExceptionrn05-19 04:08:45.885: E/AndroidRuntime(743): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)rn05-19 04:08:45.885: E/AndroidRuntime(743): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)rn05-19 04:08:45.885: E/AndroidRuntime(743): at android.app.ActivityThread.access$600(ActivityThread.java:123)rn05-19 04:08:45.885: E/AndroidRuntime(743): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)rn05-19 04:08:45.885: E/AndroidRuntime(743): at android.os.Handler.dispatchMessage(Handler.java:99)rn05-19 04:08:45.885: E/AndroidRuntime(743): at android.os.Looper.loop(Looper.java:137)rn05-19 04:08:45.885: E/AndroidRuntime(743): at android.app.ActivityThread.main(ActivityThread.java:4424)rn05-19 04:08:45.885: E/AndroidRuntime(743): at java.lang.reflect.Method.invokeNative(Native Method)rn05-19 04:08:45.885: E/AndroidRuntime(743): at java.lang.reflect.Method.invoke(Method.java:511)rn05-19 04:08:45.885: E/AndroidRuntime(743): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)rn05-19 04:08:45.885: E/AndroidRuntime(743): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)rn05-19 04:08:45.885: E/AndroidRuntime(743): at dalvik.system.NativeStart.main(Native Method)rn05-19 04:08:45.885: E/AndroidRuntime(743): Caused by: java.lang.NullPointerExceptionrn05-19 04:08:45.885: E/AndroidRuntime(743): at com.zhenglingkun.myfilemanage.FileActivity.onCreate(FileActivity.java:26)rn05-19 04:08:45.885: E/AndroidRuntime(743): at android.app.Activity.performCreate(Activity.java:4465)rn05-19 04:08:45.885: E/AndroidRuntime(743): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)rn05-19 04:08:45.885: E/AndroidRuntime(743): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)rn05-19 04:08:45.885: E/AndroidRuntime(743): ... 11 morern描述:要实现从一个Activity跳转到另一个Activity,要跳转到的Activity代码如下:rnpublic class FileActivity extends Activity rn //声明TabHost对象rn TabHost mTabHost;rn /** Called when the activity is first created. */rn @Overridern public void onCreate(Bundle savedInstanceState)rn rn super.onCreate(savedInstanceState);rn setContentView(R.layout.main);rn rn //取得TabHost对象rn //mTabHost = getTabHost();rn rn mTabHost = (TabHost)this.findViewById(android.R.id.tabhost);rn mTabHost.setup();rn rn /* 为TabHost添加标签 */rn //新建一个newTabSpec(newTabSpec)rn //设置其标签和图标(setIndicator)rn //设置内容(setContent)rn mTabHost.addTab(mTabHost.newTabSpec("tab_test1")rn .setIndicator("TAB 1"));rn mTabHost.addTab(mTabHost.newTabSpec("tab_test2")rn .setIndicator("TAB 2"));rn mTabHost.addTab(mTabHost.newTabSpec("tab_test3")rn .setIndicator("TAB 3"));rn rn //设置TabHost的背景颜色rn mTabHost.setBackgroundColor(Color.argb(150, 22, 70, 150));rn //设置TabHost的背景图片资源rn //mTabHost.setBackgroundResource(R.drawable.bg0);rn rn //设置当前显示哪一个标签rn mTabHost.setCurrentTab(0);rn rn //标签切换事件处理,setOnTabChangedListener rn mTabHost.setOnTabChangedListener(new OnTabChangeListener()rn rn // TODO Auto-generated method stubrn @Overridern public void onTabChanged(String tabId) rn rn Dialog dialog = new AlertDialog.Builder(FileActivity.this)rn .setTitle("提示")rn .setMessage("当前选中:"+tabId+"标签")rn .setPositiveButton("确定",rn new DialogInterface.OnClickListener() rn rn public void onClick(DialogInterface dialog, int whichButton)rn rn dialog.cancel();rn rn ).create();//创建按钮rn rn dialog.show();rn rn );rn rn 论坛

Android 开发问题,Activity失去响应.

08-20

症状: 模拟器有时失去响应(有时可以正常运行)。rn网上查,WARN/KeyCharacterMap(885): No keyboard for id 0,有的说是什么权限不对。rn现在我不知道是我程序的问题,还是权限什么的设置问题。rn以下是出错时的catlog信息,哪位高手可从中得出什么有用的线索,或者断言是程序的问题还是设置问题。rnrnrn08-20 03:22:54.728: INFO/ActivityManager(61): Displayed activity com.founder.apabi.reader/.view.CEBXReaderActivity: 2808 ms (total 2808 ms)rn08-20 03:22:56.508: INFO/ActivityManager(61): Starting activity: Intent cmp=com.founder.apabi.reader/.view.CatalogActivity (has extras) rn08-20 03:22:57.367: INFO/ActivityManager(61): Displayed activity com.founder.apabi.reader/.view.CatalogActivity: 767 ms (total 767 ms)rn08-20 03:22:58.687: WARN/KeyCharacterMap(885): No keyboard for id 0rn08-20 03:22:58.687: WARN/KeyCharacterMap(885): Using default keymap: /system/usr/keychars/qwerty.kcm.binrn08-20 03:23:04.037: WARN/WindowManager(61): Key dispatching timed out sending to com.founder.apabi.reader/com.founder.apabi.reader.view.CatalogActivityrn08-20 03:23:04.037: WARN/WindowManager(61): Previous dispatch state: KeyEventaction=1 code=20 repeat=0 meta=0 scancode=108 mFlags=8 to Window44013028 com.founder.apabi.reader/com.founder.apabi.reader.view.CatalogActivity paused=false @ 1282274579020 lw=Window44013028 com.founder.apabi.reader/com.founder.apabi.reader.view.CatalogActivity paused=false lb=android.os.BinderProxy@44010cf8 fin=false gfw=true ed=true tts=0 wf=false fp=false mcf=Window44013028 com.founder.apabi.reader/com.founder.apabi.reader.view.CatalogActivity paused=falsern08-20 03:23:04.047: WARN/WindowManager(61): Current dispatch state: KeyEventaction=0 code=20 repeat=0 meta=0 scancode=108 mFlags=8 to Window44013028 com.founder.apabi.reader/com.founder.apabi.reader.view.CatalogActivity paused=false @ 1282274584046 lw=Window44013028 com.founder.apabi.reader/com.founder.apabi.reader.view.CatalogActivity paused=false lb=android.os.BinderProxy@44010cf8 fin=false gfw=true ed=true tts=0 wf=false fp=false mcf=Window44013028 com.founder.apabi.reader/com.founder.apabi.reader.view.CatalogActivity paused=falsern08-20 03:23:04.058: INFO/Process(61): Sending signal. PID: 885 SIG: 3rn08-20 03:23:04.058: INFO/dalvikvm(885): threadid=3: reacting to signal 3rn08-20 03:23:04.278: INFO/Process(61): Sending signal. PID: 61 SIG: 3rn08-20 03:23:04.278: INFO/dalvikvm(61): threadid=3: reacting to signal 3rn08-20 03:23:04.478: INFO/dalvikvm(61): Wrote stack traces to '/data/anr/traces.txt'rn08-20 03:23:04.478: INFO/Process(61): Sending signal. PID: 121 SIG: 3rn08-20 03:23:04.488: INFO/dalvikvm(121): threadid=3: reacting to signal 3rn08-20 03:23:04.528: INFO/dalvikvm(121): Wrote stack traces to '/data/anr/traces.txt'rn08-20 03:23:04.528: INFO/Process(61): Sending signal. PID: 621 SIG: 3rn08-20 03:23:04.528: INFO/dalvikvm(621): threadid=3: reacting to signal 3rn08-20 03:23:04.617: INFO/dalvikvm(621): Wrote stack traces to '/data/anr/traces.txt'rn08-20 03:23:04.758: INFO/Process(61): Sending signal. PID: 265 SIG: 3rn08-20 03:23:04.788: INFO/dalvikvm(265): threadid=3: reacting to signal 3rn08-20 03:23:04.968: INFO/Process(61): Sending signal. PID: 196 SIG: 3rn08-20 03:23:05.148: INFO/dalvikvm(196): threadid=3: reacting to signal 3rn08-20 03:23:05.178: INFO/Process(61): Sending signal. PID: 448 SIG: 3rn08-20 03:23:05.348: INFO/dalvikvm(448): threadid=3: reacting to signal 3rn08-20 03:23:05.378: INFO/Process(61): Sending signal. PID: 128 SIG: 3rn08-20 03:23:05.418: INFO/dalvikvm(128): threadid=3: reacting to signal 3rn08-20 03:23:05.588: INFO/Process(61): Sending signal. PID: 193 SIG: 3rn08-20 03:23:05.768: INFO/dalvikvm(193): threadid=3: reacting to signal 3rn08-20 03:23:05.798: INFO/Process(61): Sending signal. PID: 125 SIG: 3rn08-20 03:23:05.798: INFO/dalvikvm(125): threadid=3: reacting to signal 3rn08-20 03:23:05.878: INFO/dalvikvm(125): Wrote stack traces to '/data/anr/traces.txt'rn08-20 03:23:05.948: ERROR/ActivityManager(61): ANR in com.founder.apabi.reader (com.founder.apabi.reader/.view.CatalogActivity)rn08-20 03:23:05.948: ERROR/ActivityManager(61): Reason: keyDispatchingTimedOutrn08-20 03:23:05.948: ERROR/ActivityManager(61): Load: 1.58 / 0.53 / 0.3rn08-20 03:23:05.948: ERROR/ActivityManager(61): CPU usage from 5941ms to 44ms ago:rn08-20 03:23:05.948: ERROR/ActivityManager(61): er.apabi.reader: 91% = 91% user + 0% kernelrn08-20 03:23:05.948: ERROR/ActivityManager(61): system_server: 3% = 1% user + 2% kernel / faults: 213 minorrn08-20 03:23:05.948: ERROR/ActivityManager(61): adbd: 1% = 0% user + 1% kernelrn08-20 03:23:05.948: ERROR/ActivityManager(61): re-initialized>: 0% = 0% user + 0% kernel / faults: 146 minorrn08-20 03:23:05.948: ERROR/ActivityManager(61): re-initialized>: 0% = 0% user + 0% kernel / faults: 102 minorrn08-20 03:23:05.948: ERROR/ActivityManager(61): d.process.media: 0% = 0% user + 0% kernel / faults: 311 minorrn08-20 03:23:05.948: ERROR/ActivityManager(61): emo.android.bmi: 0% = 0% user + 0% kernel / faults: 87 minorrn08-20 03:23:05.948: ERROR/ActivityManager(61): events/0: 0% = 0% user + 0% kernelrn08-20 03:23:05.948: ERROR/ActivityManager(61): logcat: 0% = 0% user + 0% kernelrn08-20 03:23:05.948: ERROR/ActivityManager(61): id.defcontainer: 0% = 0% user + 0% kernel / faults: 70 minorrn08-20 03:23:05.948: ERROR/ActivityManager(61): com.svox.pico: 0% = 0% user + 0% kernel / faults: 90 minorrn08-20 03:23:05.948: ERROR/ActivityManager(61): ndroid.settings: 0% = 0% user + 0% kernel / faults: 197 minorrn08-20 03:23:05.948: ERROR/ActivityManager(61): TOTAL: 100% = 94% user + 5% kernel + 0% softirqrn08-20 03:23:08.038: INFO/dalvikvm(448): Wrote stack traces to '/data/anr/traces.txt'rn08-20 03:23:08.278: INFO/dalvikvm(196): Wrote stack traces to '/data/anr/traces.txt'rn08-20 03:23:08.398: INFO/dalvikvm(265): Wrote stack traces to '/data/anr/traces.txt'rn08-20 03:23:08.468: INFO/dalvikvm(128): Wrote stack traces to '/data/anr/traces.txt'rn08-20 03:23:08.588: INFO/dalvikvm(193): Wrote stack traces to '/data/anr/traces.txt'rn08-20 03:23:37.428: DEBUG/dalvikvm(61): GC_FOR_MALLOC freed 3380 objects / 581568 bytes in 258msrn08-20 03:24:43.148: WARN/WindowManager(61): Key dispatching timed out sending to com.founder.apabi.reader/com.founder.apabi.reader.view.CatalogActivity 论坛

没有更多推荐了,返回首页