我无法在我的应用程序中执行“setOnItemLongClickListener”功能。请帮帮我。我怎么能这样做? 我有一个寻呼机和pageradapter
pager = (ViewPager) findViewById(R.id.pager);
Log.d(Tag,"pager 2");
pagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
Log.d(Tag,"pager 3");
pager.setOffscreenPageLimit(0);
pager.setAdapter(pagerAdapter);
Log.d(Tag,"pager 4");
setListTitle(0);
pager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
Log.d(Tag,"ПЕРЕЛИСТНУЛИ СТРАНИЦУ");
//pager.invalidate();
setNameList(position);
//****
}
@Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
这是MyFragmentPagerAdapter
private class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
Log.d(Tag, "getItem");
return PageFragment.newInstance(position);
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
@Override
public int getCount() {
MySqlCursorAdapter.prevDate = null;
Log.d(Tag, "getCount.. получаем количество страниц"+PAGE_COUNT);
return PAGE_COUNT;
}
@Override
public CharSequence getPageTitle(int position) {
Log.d(Tag, "getPageTitle");
return "Title " + position;
}
// Код из FragmentPagerAdapter.java
private String makeFragmentName(int viewId, long id) {
Log.d(Tag, "makeFragmentName");
return "android:switcher:" + viewId + ":" + id;
}
}
PageFragment.java
public class PageFragment extends Fragment {
static PageFragment newInstance(int page) {
Log.d(Tag1, "page="+page);
test=page;
PageFragment pageFragment = new PageFragment();
Bundle arguments = new Bundle();
arguments.putInt(ARGUMENT_PAGE_NUMBER, page);
pageFragment.setArguments(arguments);
return pageFragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(Tag1, "FRAGMENT onCreate0");
pageNumber = getArguments().getInt(ARGUMENT_PAGE_NUMBER);
Log.d(Tag1, "FRAGMENT onCreate!!!!!!!!");
// dlg1 = new dialog_edit();
}
@Override
public boolean onContextItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case M_EDIT1:
dlg1.show(getFragmentManager(), "dlg1");
break;
case M_EDIT2:
Toast.makeText(getActivity(), "Изменение во втором списке", Toast.LENGTH_SHORT).show();
break;
case M_DELETE:
//dlg2.show(getFragmentManager(), "dlg2");
break;
case M_ADD:
break;
default:
return super.onContextItemSelected(item);
}
return true;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(Tag, "onCreateView1");
View view = inflater.inflate(R.layout.activity_page_fragment, null);
lvMain_today = (ListView) view.findViewById(R.id.list);
//tv = (TextView) view.findViewById(R.id.tv);
Log.d(Tag, "onCreateView2");
Log.d(Tag, "onCreateView4 id_for_listtsk="+ListTsk.id_for_listtsk);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String id_for_listtsk_today = sdf.format(new Date());
ContentValues cv = new ContentValues();
DBHelper dbHelper = new DBHelper(getActivity());
// final SQLiteDatabase db = dbHelper.getWritableDatabase();
OnCreateContextMenuListener occm1 = new OnCreateContextMenuListener() {
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
AdapterContextMenuInfo aMenuInfo = (AdapterContextMenuInfo) menuInfo;
itemselected = aMenuInfo.position;
id_itemselected = (int) aMenuInfo.id;
menu.add(Menu.NONE, M_EDIT1, Menu.NONE, "Изменить1");
menu.add(Menu.NONE, M_DELETE, Menu.NONE, "Удалить1");
menu.add(Menu.NONE, M_ADD, Menu.NONE, Integer.toString(id_itemselected));
}
};
Log.d(Tag, "onCreateView3");
OnCreateContextMenuListener occm2 = new OnCreateContextMenuListener() {
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
AdapterContextMenuInfo aMenuInfo = (AdapterContextMenuInfo) menuInfo;
itemselected = aMenuInfo.position;
id_itemselected = (int) aMenuInfo.id;
menu.add(Menu.NONE, M_EDIT2, Menu.NONE, "Изменить2");
menu.add(Menu.NONE, M_DELETE, Menu.NONE, "Удалить2");
menu.add(Menu.NONE, M_ADD, Menu.NONE, Integer.toString(id_itemselected));
}
};
//*****************получаем аккаунт**
SharedPreferences mSettings;
mSettings = getActivity().getSharedPreferences(MainActivity.APP_PREFERENCES, Context.MODE_PRIVATE);
if(mSettings.contains(MainActivity.ACCAUNT_NAME)) {
accauntName=mSettings.getString(MainActivity.ACCAUNT_NAME, "");
Log.d(Tag, "!!!accauntName = _"+accauntName);
}
//пробуем*****
// Log.d(Tag, "ПРОВЕРЯЕМ ЛИСТЫ, ЛИСТ = _"+taskList.getId());
//проверяем если данные в базе
DBHelper dbHelper_AL = new DBHelper(getActivity());
final SQLiteDatabase db1 = dbHelper_AL.getWritableDatabase();
columns = new String[] { COLUMNLIST_GOOGLEID, COLUMNLIST_ID, COLUMNLIST_TITLE ,COLUMNLIST_ACCAUNT };
selection = "tasklistAccaunt = ?";
selectionArgs = new String[] {accauntName};
// orderBy = "time_up";
try {
c_TL = db1.query("listTable", columns, selection, selectionArgs, null, null, null);
Log.d(Tag, "смотрим курсор с параметром"+String.valueOf(pageNumber)+" test= "+test+" pagerPos="+MainActivity.pagerPos +" pagecount = "+MainActivity.PAGE_COUNT);
//тут делаем вилку для листа "все" и остальных
if (pageNumber ==(MainActivity.PAGE_COUNT - 1)) {
if (allTasks()) {
return view;
}
}
String[] arr_date1 = Pager.logCursor(c_TL);
//идем по курсору
if (c_TL.moveToFirst()) {
c_TL.moveToPosition(pageNumber);
Log.d(Tag, "получаем значение из курсора1");
nameGoogleId = c_TL.getColumnIndex(COLUMNLIST_GOOGLEID);
// titleGoogleId = c_TL.getColumnIndex(COLUMNLIST_TITLE);
Log.d(Tag, "получаем значение из курсора2 "+nameGoogleId);
Log.d(Tag, "получаем значение из курсора3");
listGoogleId = c_TL.getString(nameGoogleId);
// listTitle1 = (TextView)getActivity().findViewById(R.id.listTitle1); //это тут не работает...
// listTitle1.setText(c_TL.getString(titleGoogleId));
// Log.d(Tag, "listGoogleId="+listGoogleId);
// do {
// Log.d(Tag, "получаем значение из курсора3");
// listGoogleId = c_TL.getString(nameGoogleId);
// Log.d(Tag, "listGoogleId="+listGoogleId);
// }while (c_TL.moveToNext());
}
} catch (Exception e) {
// TODO: handle exception
}
columns = new String[] { DBHelper.COLUMN_NAME, DBHelper.COLUMN_ID, DBHelper.COLUMN_ACCAUNT, DBHelper.COLUMN_TASK, DBHelper.COLUMNTASKLIST_ID, DBHelper.COLUMN_TIME, DBHelper.COLUMN_DATA, DBHelper.COLUMN_STATUS};
if (listGoogleId != null) {
selection = "tasklist = ? and data_id = ? and accaunt= ?";
if (ListTsk.id_for_listtsk==null) {
selectionArgs = new String[] {listGoogleId, id_for_listtsk_today, accauntName};
} else {
selectionArgs = new String[] {listGoogleId, ListTsk.id_for_listtsk, accauntName};
}
} else {
selection = "data_id = ? and accaunt= ?";
if (ListTsk.id_for_listtsk==null) {
selectionArgs = new String[] {id_for_listtsk_today, accauntName};
} else {
selectionArgs = new String[] {ListTsk.id_for_listtsk, accauntName};
}
}
orderBy = "time_up";
try {
c = db1.query("mytable", columns, selection, selectionArgs, null, null, orderBy);
// String[] arr_date = MainActivity.logCursor(c);
Log.d(Tag, "получаем курсор напрямую..listGoogleTitle = "+listGoogleId+"data_id="+id_for_listtsk_today+"accaunt="+accauntName);
// String[] arr_date = logCursor(c);
//**************************
Log.d(Tag, "onCreateView6");
getActivity().startManagingCursor(c);
int[] listFields = new int[] { R.id.txtTitle, R.id.textData1 };
String[] dbColumns = new String[] { DBHelper.COLUMN_NAME, DBHelper.COLUMN_TASK };
// Log.d(Tag, "трассировка" );
adapter = new MySqlCursorAdapter(
getActivity(), R.layout.my_list_item,
c, dbColumns, listFields,
dbHelper);
Log.d(Tag, "onCreateView7");
lvMain_today.setAdapter(adapter);
Log.d(Tag, "onCreateView8");
registerForContextMenu(lvMain_today);
Log.d(Tag, "onCreateView9");
lvMain_today.setOnCreateContextMenuListener(occm1);
lvMain_today.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
Log.d(Tag, "YYYYYYY");
return false;
}
});
if (c.getCount()==0) {
Log.d(Tag, "c.getCount()==0");
c.close();
db1.close();
// db.close();
}
} catch (Exception e) {
// TODO: handle exception
}
Log.d(Tag, "onCreateView10");
return view;
}
public static String[] logCursor(Cursor c) {
// TODO Auto-generated method stub
final String Tag="States";
String[] arr_date = new String[c.getCount()];//String[] arr_date = new String[] {};
// Log.d(Tag,"мы в курсоре");
if (c!=null) {
Log.d(Tag,"logcursor курсор не нулевой");
if (c.moveToFirst()) {
Log.d(Tag,"мы в курсоре1");
String str;
int i=-1;
do {
Log.d(Tag,"мы в курсоре2");
str="";
i=i+1;
for (String cn: c.getColumnNames()) {
str = str.concat(c.getString(c.getColumnIndex(cn)));
}
Log.d(Tag, "++++"+str);
arr_date[i]=String.valueOf(str);
} while (c.moveToNext());
}
}
else {
Log.d(Tag,"logcursor курсор нулевой");
}
return arr_date;
}
private Boolean allTasks() {
DBHelper dbHelper = new DBHelper(getActivity());
final SQLiteDatabase db1 = dbHelper.getWritableDatabase();
columns = new String[] { DBHelper.COLUMN_NAME, DBHelper.COLUMN_ID,DBHelper.COLUMN_DATA_INTEGER, DBHelper.COLUMN_ACCAUNT, DBHelper.COLUMN_TASK, DBHelper.COLUMNTASKLIST_ID, DBHelper.COLUMN_TIME, DBHelper.COLUMN_DATA, DBHelper.COLUMN_STATUS};
selection = "accaunt= ?";
selectionArgs = new String[] {accauntName};
orderBy = "data_id_integer DESC, time_up";
try {
c = db1.query("mytable", columns, selection, selectionArgs, null, null, orderBy);
//**************************
Log.d(Tag, "onCreateView6");
getActivity().startManagingCursor(c);
int[] listFields = new int[] { R.id.txtTitle, R.id.textData1 };
String[] dbColumns = new String[] { DBHelper.COLUMN_NAME, DBHelper.COLUMN_TASK };
// Log.d(Tag, "трассировка" );
adapter = new MySqlCursorAdapter(
getActivity(), R.layout.my_list_item,
c, dbColumns, listFields,
dbHelper);
Log.d(Tag, "onCreateView7");
lvMain_today.setAdapter(adapter);
Log.d(Tag, "onCreateView8");
registerForContextMenu(lvMain_today);
Log.d(Tag, "onCreateView9");
// lvMain_today.setOnCreateContextMenuListener(occm1);
if (c.getCount()==0) {
Log.d(Tag, "c.getCount()==0");
c.close();
db1.close();
// db.close();
}
Boolean end = true;
return end;
} catch (Exception e) {
Boolean end = false;
return end;
}
}
和MySQLCursorAdapter
public class MySqlCursorAdapter extends SimpleCursorAdapter implements OnClickListener, OnLongClickListener {
public MySqlCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to, DBHelper dbHelper) {
super(context, layout, c, from, to);
Log.d(Tag, "создаем mysqlcursoradapter" );
this.currentCursor = c;
this.context = context;
this.dbHelper = dbHelper;
Log.d(Tag, "MySqlCursorAdapter()");
Integer b = c.getCount();
Log.d(Tag, "b="+b);
mSelectedItemsIds = new SparseBooleanArray();
}
public View getView(int pos, View inView, ViewGroup parent) {
//-------------------------------------------
final int viewType = getItemViewType(pos);
prevDate = null;
if (currentCursor.getPosition() > 0 && currentCursor.moveToPrevious()) {
prevDate = currentCursor.getString(currentCursor.getColumnIndex(DBHelper.COLUMN_DATA));
currentCursor.moveToNext();
}
Log.d(Tag, "getView() + posss=" + pos);
View v = inView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.my_list_item, null);
}
this.currentCursor.moveToPosition(pos);
CheckBox cBox = (CheckBox) v.findViewById(R.id.bcheck);
cBox.setTag(Integer.parseInt(this.currentCursor
.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_ID))));
//Log.d(Tag, "tag="+cBox.getTag().toString());
if (this.currentCursor.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_STATUS)) != null
&& String.valueOf(this.currentCursor
.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_STATUS))).equals(needsAction)) {
cBox.setChecked(true);
} else {
cBox.setChecked(false);
}
cBox.setOnClickListener(this);
DateTitle = (TextView) v.findViewById(R.id.DateTitle);
DateTitle.setText(this.currentCursor.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_DATA)));
//----------------------
if (prevDate == null || !prevDate.equals(thisDate)) {
DateTitle.setVisibility(View.VISIBLE);
} else {
DateTitle.setVisibility(View.GONE);
}
//------------------------
txtTitle = (TextView) v.findViewById(R.id.txtTitle);
txtTitle1 = (TextView) v.findViewById(R.id.textData1);
txtTitle.setText(this.currentCursor.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_TIME))+" , "+this.currentCursor.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_NAME)));
txtTitle1.setText(this.currentCursor.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_TASK)));
llText = (LinearLayout) v.findViewById(R.id.llText);
llText.setTag(Integer.parseInt(this.currentCursor
.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_ID))));
llText.setOnLongClickListener(this);
llText.setOnClickListener(this);
if (cBox.isChecked())
{
Log.d(Tag, " pos444=" + pos);
txtTitle.setPaintFlags(txtTitle.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
txtTitle1.setPaintFlags(txtTitle1.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
else
{
Log.d(Tag, "!pos5555=" + pos);
txtTitle.setPaintFlags(txtTitle.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
txtTitle1.setPaintFlags(txtTitle1.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
// txtTitle1.setSelected(true);
}
return (v);
}
private int getItemViewType(Cursor cursor) {
thisDate = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_DATA));
String thistitle = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_NAME));
Log.d(Tag, "type===="+thisDate+thistitle);
if (thisDate.equals("1")) {
return 0;
} else {
return 1;
}
}
public int getItemViewType(int position) {
Cursor cursor = (Cursor) getItem(position);
return getItemViewType(cursor);
}
public void ClearSelections() {
Log.d(Tag, "ClearSelections()");
this.dbHelper.clearSelections();
this.currentCursor.requery();
}
@Override
public void onClick(View v) {
Log.d(Tag, "onClick(View v) в адаптере"+ v.getId());
switch (v.getId()) {
case R.id.llText:
Log.d(Tag, "переход в ListTsk activity");
LinearLayout llText = (LinearLayout) v;
Integer _idTask = (Integer) llText.getTag();
Intent intent_add = new Intent(context, AddLineBD.class);
Log.d(Tag, "_idTask="+_idTask);
intent_add.putExtra("idTask", _idTask.toString());
// intent_add.putExtra("idTitleList", super);
context.startActivity(intent_add);
break;
case R.id.bcheck:
if(dbHelper.dbSqlite==null) {
Log.d(Tag, "00000000000");
SQLiteDatabase db = dbHelper.getWritableDatabase();
//Log.d(Tag, "onClick");
CheckBox cBox = (CheckBox) v;
Integer _id = (Integer) cBox.getTag();
//Integer _id = 4;
//Log.d(Tag, "Integer _id="+_id.toString());
ContentValues values = new ContentValues();
ContentValues valuesListTable = new ContentValues();
values.put("status", cBox.isChecked() ? "completed" : "needsAction");
Calendar calNow = Calendar.getInstance();
calNow.setTimeZone(TimeZone.getTimeZone("GMT-4:00"));
Long time_for_date1 = calNow.getTimeInMillis();//-(Integer.valueOf(ValueTZ)*3600000);
Log.d(CopyOfAsyncLoadTasks.Tag3, "ValueTZ = "+ValueTZ);
values.put("data_id_update",time_for_date1);
valuesListTable.put("tasklistUpdate",time_for_date1);
try {
db.update("mytable", values, "_id = ?", new String[] { Integer.toString(_id) });
db.update("listtable", valuesListTable, "tasklistTitle = ?", new String[] { MainActivity.titleList});
// String pp = MainActivity.titleList;
Log.d(Tag, "checkbox все получилось");
} catch (SQLException sqle) {
Log.d(Tag, "checkbox неудача");
throw sqle;
}
}
//получаем etag общий листа
try {
SharedPreferences mSettingsList;
mSettingsList = context.getSharedPreferences(MainActivity.LIST_ETAG, Context.MODE_PRIVATE);
Editor editor = mSettingsList.edit();
editor.putString(MainActivity.ETAG, "1");
editor.commit();
} catch (Exception e) {
// TODO: handle exception
// preferences= intent.getStringExtra("preferences");
Log.d(Tag, "ни фига не нашли etag общий");//"preferences in intenrservice = "+preferences);
}
try {
MainActivity.update();
} catch (Exception e) {
// TODO: handle exception
}
try {
ListTsk.update();
} catch (Exception e) {
// TODO: handle exception
}
break;
}
}
@Override
public boolean onLongClick(View v) {
LinearLayout llText = (LinearLayout) v;
Integer ask = (Integer) llText.getTag();
Log.d(Tag, "длинное!"+ask+"__");
toggleSelection(ask);
return true;
}
public void selectView(int position, boolean value) {
if (value)
mSelectedItemsIds.put(position, value);
else
mSelectedItemsIds.delete(position);
notifyDataSetChanged();
}
public void toggleSelection(int tag) {
selectView(tag, !mSelectedItemsIds.get(tag));
}
OnLongClick在MySqlCursorAdapter的功能中运行。但我需要setOnItemLongClickListener。我尝试在MainActivity中执行此功能
ListView lvTareas = (ListView) findViewById (R.id.list);
lvTareas.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
Log.d(Tag,"pos"+" "+pos);
return true;
}
});
但它不起作用。请帮帮我?我做错了什么?
答案 0 :(得分:0)
由于CheckBox
在 my_list_item 布局中的可聚焦性而发生这种情况。
将以下行添加到ListView的项目布局(my_list_item)的根布局。
android:descendantFocusability="blocksDescendants"