在我的应用程序中,我有一个带有一些片段的活动。其中一个片段我有列表视图和我想创建监听器来监听onLong点击活动中的Listview项目,例如,如果最终用户长按listview项目到片段我必须显示Toast in活性
对于此操作,我创建了接口侦听器,例如:
public interface IOnLongClickReceiveSmsMaster {
public void onLogin(Integer position);
}
在活动i中创建BroadcastReceiver
为:
方法:
IntentFilter filter = new IntentFilter(M.ACTION_BROADCAST_LONGCLICK_LISTVIEW);
registerReceiver(NotifyLongClickOnItems, filter);
广播功能:
private final BroadcastReceiver NotifyLongClickOnItems = new BroadcastReceiver() {
@Override
public void onReceive(Context ctxt, Intent i) {
Toast.makeText(MainView.this, "LongClick", Toast.LENGTH_SHORT).show();
}
现在进入Fragment我必须设置定义到LongClick
的接口:
private static IOnLongClickReceiveSmsMaster mOnLongClickReceiveSmsMaster;
public View onCreateView( ... ){
listview= (ListView) view.findViewById(R.id.listView);
listview.setOnLongListener(new IOnLongClickReceiveSmsMaster() {
@Override
public void onLogin(Integer position) {
}
});
};
.
.
.
}
public static void setOnLongListener(IOnLongClickReceiveSmsMaster l) {
mOnLongClickReceiveSmsMaster = l;
}
不幸的是我的代码不正确,我收到了这个错误:
The method setOnLongListener(new IOnLongClickReceiveSmsMaster(){}) is undefined for the type ListView
我认为我的分析有这种能力是不正确的,请帮我解决这个问题
答案 0 :(得分:1)
如果您只使用AdapterView.OnItemLongClickListener
,那将会容易得多。这是如何:
getListView().setOnItemLongClickListener(new OnItemLongClickListener(){
public boolean onItemLongClick( AdapterView<?> arg0, View v, int position, long id){
/* Do whatever you want here, e.g. go to next Activity etc. */
return false;
}
};
要通知您的Activity
,请在Fragment
班级
public interface LongClickNotifier{
public void notifyOnLongClick(int position, View v);
}
让Activity
实现此界面
public class MainActivity extends Activity implements LongClickNotifier{
...
...
@Override
public void notifyOnLongClick(int position, View v){
/* Do whatever you want here with "position" and "v". */
}
}
现在在Fragment
,
getListView().setOnItemLongClickListener(new OnItemLongClickListener(){
public boolean onItemLongClick( AdapterView<?> arg0, View v, int position, long id){
((LongClickNotifier)getActivity()).notifyOnLongClick(position, v);
return false;
}
};
你去吧!无需创建BroadcastReceiver
或其他任何内容!
答案 1 :(得分:0)
首先,您只需使用列表视图对象。
ListView listView = (ListView)findViewById(R.id.yout_list_view_layout_id_here);
之后,只需定义一个列表视图的监听器。
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
Log.v("List view long clicked ","position : " + pos);
return true;
}
});