在点击监听器上设置按钮,然后才能在屏幕上显示?

时间:2014-12-28 20:45:49

标签: java android android-fragments

我有一个按钮,我试图听,但按钮不在屏幕上。我正在使用许多不同的片段,我想要收听的按钮最初没有出现在屏幕上,因此当我启动应用程序时它会立即崩溃。我在想,因为它还没有出现在屏幕上,它正试图听一些不存在的东西,它开始崩溃。如何使用它,以便按钮可以在屏幕上显示按钮所在的片段时开始收听?

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

1 个答案:

答案 0 :(得分:0)

确定主要问题是你发现按钮的视图不在你在Listener上设置它的位置。所以请声明它应该与你的Listener一起使用。第二个解决方案是在你的位置添加一行查找按钮的视图主要是这个单词finalstatic或两个final static一般来说,您的代码必须如下所示。final Button akbutton = (Button) findViewById(R.id.akbutton);您可以将final更改为我上面写的变量。