不是封闭类错误 Android Studio

30

我是Android开发的新手,对Java没有深入的了解。我已经卡在一个问题上很长时间了。我想在按钮点击时打开一个新的活动。但是我遇到了一个错误:error: not an enclosing class: Katra_home

这是MainActivity.java的代码:

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button btn=(Button)findViewById(R.id.bhawan1);
   btn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent myIntent = new Intent(Katra_home.this, Katra_home.class);
            Katra_home.this.startActivity(myIntent);
        }
    });

这是Katra_home.java的代码。

public class Katra_home extends BaseActivity {

protected static final float MAX_TEXT_SCALE_DELTA = 0.3f;

private ViewPager mPager;
private NavigationAdapter mPagerAdapter;
private SlidingTabLayout mSlidingTabLayout;
private int mFlexibleSpaceHeight;
private int mTabHeight;


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

    ActionBar ab = getSupportActionBar();
    if (ab != null) {
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setHomeButtonEnabled(true);
    }

虽然我在stackoverflow上看到了很多答案,但由于我是Android开发的新手,所以无法理解它们。因此,我想问一下,我需要在我的代码中做哪些更改才能使其正常工作。

6个回答

41

应该是这样的

Intent myIntent = new Intent(this, Katra_home.class);
startActivity(myIntent);

您必须使用现有的活动上下文来启动新的活动,新活动尚未创建,因此您无法使用其上下文或调用其方法。

由于您使用了this关键字,因此会抛出not an enclosing class错误。 this是对当前对象的引用——正在调用其方法或构造函数的对象。使用this只能在实例方法或构造函数内部引用当前对象的任何成员。

Katra_home.this是无效的结构。


7
Intent myIntent = new Intent(MainActivity.this, Katra_home.class);
startActivity(myIntent);

这应该是完美的一个 :)

2
您正在调用不存在的活动上下文...所以只需将您的代码替换为 onClick(View v):
Intent intent=new Intent(MainActivity.this,Katra_home.class);
startActivity(intent);

它一定会有效...


1
String user_email = email.getText().toString().trim();
firebaseAuth
    .createUserWithEmailAndPassword(user_email,user_password)
    .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if(task.isSuccessful()) {
                Toast.makeText(RegistraionActivity.this, "Registration sucessful", Toast.LENGTH_SHORT).show();
                startActivities(new Intent(RegistraionActivity.this,MainActivity.class));
            }else{
                Toast.makeText(RegistraionActivity.this, "Registration failed", Toast.LENGTH_SHORT).show();
            }
        }
    });

请添加一个解释,说明这段代码是如何解决问题的。谢谢。 - Reg

0

将 onClick() 方法中的代码替换为以下内容:

Intent myIntent = new Intent(this, Katra_home.class);
startActivity(myIntent);

0
startActivity(new Intent(this, Katra_home.class));

试试这个,它会起作用的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接