简体   繁体   中英

Setting a buttons on click listener before it is on the screen?

I have a button I am trying to to listen to but the button is not on the screen yet. There are many different Fragments that I am using and the button that I want to listen to doesn't appear on the screen at first, so when I start the app it crashes right away. I am thinking that because it isn't on the screen yet and it is trying to listen to something that isn't there it begins to crash. How do I use it so that the button can begin listening once the fragment that the button is in appears on the screen?

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

    // This button is not in the main fragment
    Button akbutton = (Button) findViewById(R.id.akbutton);

    akbutton.setOnClickListener(new View.OnClickListener() {
        FragmentManager fragmentManager = getFragmentManager();
        Fragment fragment = null;
        public void onClick(View v) {
            fragment = new ak47();
            fragmentManager.beginTransaction()
                    .replace(R.id.container, ak47.newInstance(0))
                    .commit();
        }
    });

Ok What the MAIN problem is that your finding the View of your Button not inside where your setting it on Listener.So Please Declare it where it should be used with your Listener.Second solution is to add a single line to where your finding the view of button mainly this word final or static or both final static in general your code must look like this. final Button akbutton = (Button) findViewById(R.id.akbutton); where you can change final to my above written varialiables.

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