Onclick和OnlongClick无法正常工作,我正在使用AppCompatActivity来支持KitKat。我不知道为什么它不起作用。它是适配器还是视图?我知道我正在使用已弃用的适配器,但我将其用于某个目的。
以下代码:
public class MainActivity extends AppCompatActivity {
ActionMode mActionMode;
private CartDbAdapter dba;
private Cursor cursor;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
databaseview();
}
else {
setContentView(R.layout.cart);
dba = new CartDbAdapter(this);
dba.open();
}
private void databaseview(){
cursor = dba.fetchAllBooks();
ListView listView = (ListView) findViewById(list);
startManagingCursor(cursor);
String [] from = new String[] {BookContract.TITLE , BookContract.AUTHORS };
int [] to = new int [] {android.R.id.text1 , android.R.id.text2 };
SimpleCursorAdapter databaseAdapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2, cursor, from, to);
listView.setAdapter(databaseAdapter);
listView.setOnLongClickListener(longListener);
listView.setOnClickListener(clickListener);
}
View.OnLongClickListener longListener = new View.OnLongClickListener() {
public boolean onLongClick(View view) {
if (mActionMode != null) {
return false;
}
mActionMode = MainActivity.this.startSupportActionMode(callback);
view.setSelected(true);
return true;
}
};
View.OnClickListener clickListener = new View.OnClickListener(){
public void onClick(View view) {
Intent viewIntent = new Intent(MainActivity.this, BookActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable(BookActivity.KEY, dba.fetchBook(view.getId()));
viewIntent.putExtras(bundle);
startActivity(viewIntent);
}
};
private ActionMode.Callback callback = new ActionMode.Callback() {
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contextbar_menu, menu);
return true;
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.delete:
mode.finish();
return true;
default:
return false;
}
}
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
};
谢谢!
答案 0 :(得分:0)
我刚刚使用setOnItemClickListener和setOnItemLongClickListener与ListView适配器解决了这个问题。
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Toast.makeText(arg0.getContext(), ((TextView)arg1).getText(), Toast.LENGTH_SHORT).show();
return false;
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> listView, View itemView, int index,
long id) {
}
});