Android 添加按钮和应用程序
我试着制作一个可以进入网页的按钮,但当我使用午餐应用程序时,它被压碎了。没有错误。怎么办?Mby XML中有问题吗Android 添加按钮和应用程序,android,Android,我试着制作一个可以进入网页的按钮,但当我使用午餐应用程序时,它被压碎了。没有错误。怎么办?Mby XML中有问题吗 public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
addButtonClickListener(); //Soc network buttons
}
public void addButtonClickListener() //soc network buttons
{
Button facebook = (Button)findViewById(R.id.Facebookpoga); //Facebook pogai
facebook.setOnClickListener(new OnClickListener(){
public void onClick(View arg)
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.facebook.com"));
startActivity(intent);
}
});
}
在学习Android开发的基础知识时,我遇到过很多类似的问题。我可以看出问题在于,出于某些原因,
findViewById(id)
返回null。当eclipse开始为每个活动
包含主布局
的片段布局
时,这在更新之后开始发生。
我通过将所有此类调用放入onStart()
而不是onCreate()
来解决问题。我相信这会帮你解决问题。
这样做:
protected void onStart(){
addButtonClickListener(); //Soc network buttons
}
在onCreate()之后添加此函数,希望对您有所帮助。是的,删除侦听器调用addButtonClickListener()代码>来自onCreate()。
我猜问题可能是因为Fragment layout
没有在setContentView()
之后立即实例化,从而导致findViewById(R.id.Facebookpoga)
返回null,因为还没有创建id为R.id.Facebookpoga的视图。LogCat中没有错误
?发布日志,按钮是否在片段中?问题很可能是布局活动
中没有id为Facebookpoga的按钮。
“崩溃”word没有为我们提供信息,当你的应用程序崩溃时,你要问问题,因此,你应该包括LogCat
的一些部分以及相关的代码片段,因此请将你的LogCat包括在帖子中