本文介绍了尝试 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在一个单独的片段中,我有:

I get a NPE when I try to invoke findViewByID for R.id.loginButton, and I'm guessing this is because loginButton is within a separate Fragment, which I have as:

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_mainLinearLayout 中包含几个按钮,而 activity_main 只有一个 FrameLayout.

However, I am unsure of how to fix this so that I can find the loginButton ID. I haven't worked with fragments before, so I realize I may be using them/implementing them incorrectly. fragment_main contains a few buttons in a LinearLayout, and activity_main has nothing but a single 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;
}

并从ActivityonCreate中删除登录按钮相关的代码.

And remove the login button related code from onCreate of Activity.

这篇关于尝试 findViewById 时抛出 Nullpointerexception的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-09 22:22