Intent对象显示错误Android

时间:2017-07-04 15:07:17

标签: java android android-intent

我正在使用android活动,并尝试在上一个活动上点击一个按钮时启动一个活动,问题从intent对象开始,因为第一个参数是;意图构造函数的context参数不能与" this,MainActivity.this,getApplicationContext(),getBaseContext"我尝试了intent构造函数对象的第一个参数中的所有参数。以下是我的代码。

package com.example.nadeemahmad.guitest;


import android.content.Intent;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;


public class MainActivity extends AppCompatActivity {
    Button ma_sub_btn,prof_sub_btn;
    RelativeLayout ma_rel_lay2,ma_rel_lay3,ma_dots_ly;

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

        ma_sub_btn = (Button)findViewById(R.id.ma_sub_btn);
        ma_rel_lay2 = (RelativeLayout)findViewById(R.id.ma_rel_lay2);
        ma_rel_lay3 = (RelativeLayout)findViewById(R.id.ma_rel_lay3);
        ma_dots_ly = (RelativeLayout)findViewById(R.id.ma_dots_ly);

        ma_sub_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ma_rel_lay2.setVisibility(View.GONE);
                ma_rel_lay3.setVisibility(View.VISIBLE);
                ma_dots_ly.setVisibility(View.GONE);
            }
        });

        prof_sub_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(this, profile.class);
                startActivity(i);
            }
        });


    }




}

Image

3 个答案:

答案 0 :(得分:2)

按钮NullPointerException您获得prof_sub_btn。问题是您在设置prof_sub_btn之前没有初始化Button OnClickListener ..

试试这个:

prof_sub_btn = (Button) findViewById(R.id.prof_sub_btn);
prof_sub_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i = new Intent(MainActivity.this, profile.class);
            startActivity(i);
        }
    });

答案 1 :(得分:0)

您已在this内写了onClick ...尝试撰写MainActivity.this并且它应该有效..更多关于使用this关键字click here

Intent i = new Intent(MainActivity.this, profile.class);

在你的情况下看完堆栈跟踪后应该将prof_sub_btn按钮绑定到xml。

答案 2 :(得分:0)

在设置内容视图后添加此行:

prof_sub_btn = (Button)findViewById(R.id.prof_sub_btn);