Android: findViewById returns Null even if is after setContentView

前端 未结 2 605
南方客
南方客 2020-12-12 03:50

Here\'s my code in LoginActivity:

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


        
相关标签:
2条回答
  • 2020-12-12 04:32

    Try declaring the button inside onCreate, rather than declaring it outside of it (which is what I'm assuming you're doing).

    Oh, and if you haven't tried this already, use "VIEW.findViewById(R.id.loginButton)", rather than just "findViewById(R.id.loginButton);". I think that's more likely your problem; I forget about it a lot too.

    0 讨论(0)
  • 2020-12-12 04:37

    It seems that your Button is in fragment layout, so your on click method might be in your fragment (PlaceholderFragment) instead of your activity. You need to declare another Class extends with Fragment..

    First, create a new Class named PlaceHolderFragment. Extend it with Fragment and add this code below to it:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_login, container, false);
        // ...
        loginButton = (Button) rootView.findViewById(R.id.loginButton);
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onLoginButtonClicked();
            }
        });
        // ...
        return rootView;
    }  
    
    // put your method onLoginButtonClicked here.
    

    Then, your layout activity for MainActivity (named activity_main) might have a FrameLayout with the id container like this:

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity" >
    
        <!-- other views -->
    
    </FrameLayout>  
    

    Finally, your MainActivity will only have:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        if (savedInstanceState == null) {
            // you add you fragment here in id container
            getSupportFragmentManager().beginTransaction()
                 .add(R.id.container, new PlaceholderFragment()).commit();
        }
    
        // ... without loginButton
        // and some more stuff
    }
    
    0 讨论(0)
提交回复
热议问题