代码中红色显示的这句为按钮设置监听器的语句导致的程序异常,注释后程序就能正常运行了,请问这是为什么啊,之前也是这样用的,今天升级了一下sdk,就成这样了,请问有关系么,,还是只是巧合,,
package com.example.wocao;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class MainActivity extends ActionBarActivity implements OnClickListener{
private Button btn;
@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();
}
btn=(Button)findViewById(R.id.btn);
btn.setOnClickListener(this);
}
@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);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
@Override
public void onClick(View v){
if(v==btn){
}
}
}
------解决方案--------------------
又是空指针错误。。。
------解决方案--------------------
btn=(Button)findViewById(R.id.btn);
这句正常返回对象没
------解决方案--------------------
如果Button是在fragment的xml布局文件里面,那么你在activity的oncreate里面去find是不行的,因为fragment都还未加载进来。
解决方案:在fragment的oncreateview方法里面初始化这个button,并且将onclicklistener接口实现在fragment上,而不是activity上。