片段中按钮的语法是什么,单击它时会进入列表视图活动?
任何回复都将不胜感激。感谢。
答案 0 :(得分:1)
在上面评论中提供的代码中:
public class Exerfrag extends Fragment{
private Button button1;
Context context;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.exer, container, false);
button1 = (Button) view.findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(context, Listview.class);
startActivity(intent);
}
});
return view;
}
}
context
永远不会被初始化。请改用getActivity()
,以便onClick
方法如下所示:
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(getActivity(), Listview.class);
startActivity(intent);
}
});
修改强>:
您的第二个Activity
也会出现问题:
public class Listview extends Activity {
ExpandableListView exv;
public Listview() {
// TODO Auto-generated constructor stub
exv=(ExpandableListView)findViewById(R.id.expandableListView1);
exv.setAdapter(new MyAdapter(this));
}
}
您永远不会致电onCreate()
,您应该在其中放置其余的设置代码,包括setContentView(R.layout.-)
以确定您的布局。
编辑2:
public class Listview extends Activity {
ExpandableListView exv;
protected void onCreate(android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
};
public Listview() {
// TODO Auto-generated constructor stub
exv=(ExpandableListView)findViewById(R.id.expandableListView1);
exv.setAdapter(new MyAdapter(this));
}
以下几行:
exv=(ExpandableListView)findViewById(R.id.expandableListView1);
exv.setAdapter(new MyAdapter(this));
需要放在onCreate()
内。部分内容如下:
public Listview(){
....
}
称为constructor
。在这种情况下实际上根本不需要它,所以我的建议是完全删除它,以便你的整个班级看起来像这样:
public class Listview extends Activity {
ExpandableListView exv;
protected void onCreate(android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
exv=(ExpandableListView)findViewById(R.id.expandableListView1);
exv.setAdapter(new MyAdapter(this));
}
对于Android来说,这是相当基本的东西,所以我建议您查看Activity
类的developer文档以及Vogella <等网站/ p>