解决方案 »
- 怎么为一个学校教务信息网站做一个手机(先选android)客户端?
- Android 如何在treeview中加checkbox
- android从数据库提取时,换行符直接输出
- help,求救
- listview长按菜单内容的问题
- android 自主创业的那点伤心事
- 现在有两个画面a,和画面b。b半透明显示在a的前端。如何实现?
- 求助!困扰一天一夜了!有关http发送list容器的问题!
- 布局问题新手
- 毕业设计的两个知识点不会,求助大佬
- 求android studio 下载地址,最好有中文的
- 在eclipse上的2.2的模拟器运行程序正常,可是在4.4.2的S4手机上运行停止,logcat提示添加INTERACT_ACROSS_USERS_FULL
你的setContentView加载的是R.layout.activity_main
但是你的button的实际位置是R.layout.fragment_main
所以你用findviewbyid获得的是null,最后运行报的是空指针
只要把第24行改为setContentView(R.layout.fragment_main);
import android.app.Fragment;
import android.graphics.Color;
import android.os.Bundle;
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;
import android.widget.TextView;public class MainActivity extends Activity { private TextView textView;
private Button button;
int count = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.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);
return true;
}
class ButtonListener implements OnClickListener { @Override
public void onClick(View arg0) {
count ++;
textView.setTag(count + "");
}
} @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); textView = (TextView)rootView.findViewById(R.id.textView);
button = (Button)rootView.findViewById(R.id.button);
ButtonListener buttonListener = new ButtonListener();
button.setOnClickListener(buttonListener);
//textView.setText("Hello Jie");
//textView.setBackgroundColor(Color.BLUE);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
return rootView;
}
}}
不知道你看懂了没
我当时下载的是adt-bundle-windows-x86_64-20140321.zip,新建项目后默认给我打开的是fragment_main的编辑页面,我就在上面修改了,以为java文件里加载layout.activity_main会自动关联到fragment_main。后来换了版本直接出现的是activity_main,不存在fragment_main,就没问题了
感谢你的回答,让我明白了出错的原理!