java – 尝试findViewById时抛出Nullpointerexception

我有以下活动:

public class MainActivity extends ActionBarActivity {

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

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new StartFragment())
                .commit();
    }

    Button login = (Button) findViewById(R.id.loginButton);

    login.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent intent = new Intent(MainActivity.this,LoginActivity.class);
            startActivity(intent);
        }
    });

}

当我尝试为R.id.loginButton调用findViewByID时,我得到一个NPE,我猜这是因为loginButton在一个单独的片段中,我有:

public static class StartFragment extends Fragment {

    public StartFragment() {
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_main, container, false);

    }
}

但是,我不确定如何解决这个问题,以便找到loginButton ID.我以前没有使用过片段,所以我意识到我可能正在使用它们/错误地实现它们. fragment_main包含LinearLayout中的几个按钮,而activity_main只包含一个FrameLayout.

解决方法:

编写代码来从片段初始化按钮,因为你的按钮是片段布局而不是活动的布局.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_main, container,
            false);
    Button login = (Button) rootView.findViewById(R.id.loginButton);
    login.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent intent = new Intent(MainActivity.this,
                    LoginActivity.class);
            startActivity(intent);
        }
    });

    return rootView;
}

并从onCreate of Activity中删除登录按钮相关代码.

上一篇:java – 尝试定义自定义PropertyMap时出现NullPointerException


下一篇:java – 找出以编程方式抛出NullPointerException的变量