我有一个片段,它有一个带有两个按钮的标题和一个列表。我想获得关于这些项目的事件。该片段是动态添加到 UI 中的,我的应用程序适用于 android 16 及更高版本,因此我不必使用支持库。我决定为 MainActivity 上的按钮和列表实现单击侦听器,因为这些会触发数据库查找,并且我想将我的数据库查找保留在一个地方。所以,我做了一个实现这两者的主要活动: OnClickListener 和 OnItemClickListener 并添加了以下方法:
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "List Click", Toast.LENGTH_SHORT).show();
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(getApplicationContext(), "List Click"+arg2, Toast.LENGTH_SHORT).show();
}
要调用我做的片段:
//get a list of the data
Fragment sideFormations=sideFragment.newInstance(list);
sideFormations.setClickListeners(this,this); //<--important bit
Toast.makeText(getApplicationContext(), "listeners set", Toast.LENGTH_SHORT).show();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.side_frame,sideFormations);
ft.commit();
在frag的setClickListener的方法中,我将传入的值设置为click listeners。frag的相关部分是:
onCreateView: //nflate the views, setAdapter for the list, ensure clickability of the views
onStart: //assign click listeners which were passed in to the list, and to the header.
我仍然无法在主要活动中点击点击,即。零但没有错误。任何想法都将受到高度欢迎和赞赏。谢谢你。
编辑:在我定义视图的侦听器的地方添加代码。
//This is the latest iteration. As I mentioned, I have tried to set these at different places in the frag's lifecycle without much success:
public void onStart() {
super.onStart();
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!");
Log.d("CLICK-VIEW","List Clicked");
main.onItemClick(arg0,arg1,arg2,arg3);
}
});
mHeaderView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!");
Log.d("CLICK-VIEW","Header Clicked");
//main.onClick(v);
}
});
}