Nullpointerexception thrown when trying to findViewById

前端 未结 3 1026
[愿得一人]
[愿得一人] 2020-12-07 06:15

I have the following Activity:

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    supe         


        
3条回答
  •  -上瘾入骨i
    2020-12-07 06:50

    Write code to initialize button from fragment becuase your button is into fragment layout not into activity's layout.

    @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;
    }
    

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

提交回复
热议问题