简体   繁体   中英

Android Dev problems with android.R

I am having trouble linking my interface with my java.

    package com.example.game;

import android.os.Bundle;
import android.R;
import android.app.Activity;
import android.view.Menu;
import android.widget.Button;

public class MainActivity extends Activity {

   Button btn1 = (Button) findViewById(R.id.button1);


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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu); <--- main
        return true;
    }

}

I am having trouble with the layout. I can link my buttons ect. but it always throws an error on the generated code? why does it do this? I did the suggested fixes and ran it, which resulted into a crash... I am new to java and android development. I am learning as I go. I do have other experience in visual basic and what not.

Suggested fixes: change to activity_list_ item and can not be resolved.

Your btn1 assignment is incorrect. When you're assigning it on initialization, there is no view, as the code is run prior to onCreate. Instead, it should look like this:

Button btn1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main); <---- activity_main
    btn1 = (Button) findViewById(R.id.button1);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM