大家好,又见面了,我是你们的朋友全栈君。
随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)
官方文档解释:
If set in an Intent passed to Context.startActivity()
, this flag will cause any existing task that would be associated with the activity to be cleared before the activity is started. That is, the activity becomes the new root of an otherwise empty task, and any old activities are finished. This can only be used in conjunction with FLAG_ACTIVITY_NEW_TASK
.
翻译:如果在通过Context.startActivity()启动activity时为Intent设置了此标识,这个标识将导致:在此activity启动之前,任何与此activity相关联的task都会被清除。也就是说,此
activity将变成一个空栈中新的最底端的activity,所有的旧activity都会被finish掉,这个标识仅仅和FLAG_ACTIVITY_NEW_TASK联合起来才能使用。
下面给一个例子,看看设置了此标识和不设置有什么区别:
MainActivity:
package com.hom.testflag;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.app.Activity;
import android.content.Intent;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
Button btn = new Button(this);
btn.setText("跳转到A");
layout.addView(btn);
setContentView(layout);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ActivityA.class);
startActivity(intent);
}
});
}
}
ActivityA:
package com.hom.testflag;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
public class ActivityA extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
Button btn = new Button(this);
btn.setText("跳转到B");
layout.addView(btn);
setContentView(layout);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
}
ActivityB:
package com.hom.testflag;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.LinearLayout;
public class ActivityB extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
Button btn = new Button(this);
btn.setText("ActivityB");
layout.addView(btn);
setContentView(layout);
}
}
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/160721.html原文链接:https://javaforall.cn