I am trying to insert a Contextual Action Bar when I click on the item of my ListView. What I want to do is select multiple items in the list and then perform actions on them by clicking on the appropriate icons in the action bar. I wrote this code.
applicationListView = (ListView) findViewById(R.id.list);
applicationListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
applicationListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
SparseBooleanArray positions = applicationListView.getCheckedItemPositions();
int counter = 0;
if (positions != null) {
int length = positions.size();
for (int i = 0; i < length; i++) {
if (positions.get(positions.keyAt(i))) {
counter++;
Toast.makeText(getBaseContext(), ""+counter++, Toast.LENGTH_SHORT).show();
}
}
}
startSupportActionMode(mActionModeCallback);
}
});
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback(){
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contextual_action_bar, menu);
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item1:
return true;
case R.id.menu_item2:
//close the action mode
//mode.finish();
return true;
default:
mode.finish();
return false;
}
}
#Override
public boolean onPrepareActionMode(ActionMode arg0, Menu arg1) {
// TODO Auto-generated method stub
arg0.setTitle("Selected item: ");
return false;
}
};
There are various problems.
1- When I click on an item appears in the contextual ActionBar but the selected item is NOT highlighted, for example with the color blue. When you select the items is as if the ActionBar was recreated again, as I see the ActionBar icons disappear and reappear, as if, indeed, it was recreated.
2- When I click on an item in the toast always visualize the number 1. Why? How can I get a number with the selected items and then to put as the title of action bar?
Related
This is how I declare my menu on my action bars:
public void checkUserType() {
if (mPrefs.getUserType().equalsIgnoreCase("mahasiswa")) {
requestData(String.valueOf(mPrefs.getUserID()));
} else if (mPrefs.getUserType().equalsIgnoreCase("dosen")) {
requestData(String.valueOf(mPrefs.getSelectedUserId()));
getSupportActionBar().hide();
myMenu.findItem(R.id.exit).setVisible(false);
}
And I want to hide/remove the menu from the action bar using an if-else (not hiding whole action bar, just the menu). I have tried using "myMenu.findItem(R.id.exit).setVisible(false);" but it occurs error on a null object reference
This is my code:
public void checkUserType() {
if (mPrefs.getUserType().equalsIgnoreCase("mahasiswa")) {
requestData(String.valueOf(mPrefs.getUserID()));
} else if (mPrefs.getUserType().equalsIgnoreCase("dosen")) {
requestData(String.valueOf(mPrefs.getSelectedUserId()));
getSupportActionBar().hide();
myMenu.findItem(R.id.exit).setVisible(false);
}
This will hide a menu item by id:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate( R.menu.main_menu, menu );
// hide menu item
menu.findItem( R.id.menu_item_1 ).setVisible( false );
return true;
}
You can apply the same to:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if( item.getItemId() == R.id.menu_item_1 ) {
item.setVisible( false );
}
}
here just call invalidateOptionsMenu() and move your logic to onCreateOptionsMenu() and change visiblity there.
for example
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.
.
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
invalidateOptionsMenu();
}
});
}
and in onCreateOptionsMenu()
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.activity_main_menu, menu);
menu.findItem(R.id.menu_item).setVisible(condition);
}
I wanted to add three dot menu with each listitem of listview.
**This is my listview adapter getView method **
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = activity.getLayoutInflater();
View inflate = inflater.inflate(R.layout.book_item_new, null, false);
findViews(inflate);
bookTitle.setText(books.get(position).getName());
bookPrice.setText(books.get(position).getPrice() + " ₹");
semBranch.setText(books.get(position).getSemester() + " Sem " + books.get(position).getBranch());
date.setText(books.get(position).getpDate());
senderName.setText(books.get(position).getSender());
return inflate;
}
Add a ImageView with an image of three-dot in your book_item_new layout.
<ImageView
android:id="#+id/imbPopUp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:paddingLeft="18dp"
android:paddingRight="18dp"
android:src="#drawable/icon_menu_dot" />
And set OnclickListener on this imageview inside your getView() like the following.
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPopupMenu(imageView, position);
}
});
/**
* Showing popup menu when tapping on 3 dots
*/
private void showPopupMenu(View view, int position) {
PopupMenu popup = new PopupMenu(context, view, Gravity.END);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.favourite_menu, popup.getMenu());
//set menu item click listener here
popup.setOnMenuItemClickListener(new MyMenuItemClickListener(position));
popup.show();
}
Now create click listener class for your menu item click like below.
/**
* Click listener for popup menu items
*/
class MyMenuItemClickListener implements PopupMenu.OnMenuItemClickListener {
int position;
/**
* #param position
*/
MyMenuItemClickListener(int position) {
this.position = position;
}
/**
* Click listener for popup menu items
*/
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.view:
// ...
return true;
case R.id.edit:
// ...
return true;
case R.id.delete:
// ...
return true;
case R.id.favourite:
// ...
return true;
default:
}
return false;
}
}
you can try this,
In your design xml add following code for dots
<Textview
android:id="#+id/textViewOptions"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="⋮"
android:textAppearance="?android:textAppearanceLarge"
android:gravity="center_horizontal|center_vertical"/>
After this in your on bind method add following code,
holder.textViewOptions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//creating a popup menu
PopupMenu popup = new PopupMenu(context, holder.textViewOptions);
//inflating menu from xml resource
popup.inflate(R.menu.menu_options);
//adding click listener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_delete:
//handle menu1 click
return true;
case R.id.action_edit:
//handle menu2 click
return true;
default:
return false;
}
}
});
popup.show();
}
});
Thank You.
Just add button into your listitem and set onClickListener to the button.
like this
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ContextThemeWrapper wrapper =
new ContextThemeWrapper();
PopupMenu popupMenu = new PopupMenu(wrapper, 'yourItemView');
popupMenu.inflate(R.menu.'your_menu');
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
// implement menu click here
return true
}
});
popupMenu.show();
}
});
I want to hide ImageView when multiple click in Listview.
I did like this:
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
final int checkedCount = listView.getCheckedItemCount();
mode.setTitle(checkedCount + " Selected");
if(checked) {
imageView.setVisibility(View.INVISIBLE);
} else {
imageView.setVisibility(View.VISIBLE);
}
}
#Override
public boolean onActionItemClicked(final ActionMode mode, MenuItem item) {
return false;
default:
return false;
}
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater menuInflater = mode.getMenuInflater();
menuInflater.inflate(R.menu.toolbar_mode, menu);
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
});
But there was only one item invisible and I was getting error.
If anything, I have custom adapter for ListView. Thanks.
So I have a GridView that I want to be able to long-press elements to enable a contextual action bar right? I looked up lots of tutorials, including https://www.bignerdranch.com/blog/recyclerview-part-2-choice-modes/ and https://android.googlesource.com/platform/development/+/master/samples/ApiDemos/src/com/example/android/apis/view/List15.java, as well as others which all state that when using CHOICE_MODE_MULTIPLE_MODAL the MultiChoiceModeListener should automatically be used on a long-press
I see many tutorials using this (and that's it) and it works, but when I long press on elements in my GridView the CAB doesn't start (nor is onCreateActionView called at all) and I absolutely can't figure out why.
Here's my code for the GridView
receiptGridView.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
receiptGridView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
// int count = 0;
ArrayList<Receipt> tmp = new ArrayList();
#Override
public boolean onCreateActionMode(android.view.ActionMode actionMode, Menu menu) {
Log.d("DEBUG","Created action mode!");
MenuInflater inflater = actionMode.getMenuInflater();
inflater.inflate(R.menu.context_delete, menu);
return true;
}
#Override
public void onItemCheckedStateChanged(android.view.ActionMode actionMode, int i, long l, boolean b) {
receiptGridView.setSelection(i);
Receipt r = (Receipt) listAdapter.getItem(i);
if(b) {
tmp.add(r);
}
else {
tmp.remove(r);
}
actionMode.setTitle("Delete Items");
actionMode.setSubtitle(receiptGridView.getCheckedItemCount() + " items selected.");
}
#Override
public boolean onPrepareActionMode(android.view.ActionMode actionMode, Menu menu) {
return true;
}
#Override
public boolean onActionItemClicked(android.view.ActionMode actionMode, MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_delete:
removeReceipts(tmp);
actionMode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(android.view.ActionMode actionMode) {
}
});
Turns out to actually trigger the action menu, you have to call setItemChecked on the gridview, so I just did this to my container view on longpress
holder.container.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
if (ma.mActionMode == null) {
// the line that triggers it
ma.receiptGridView.setItemChecked(position, true);
v.setBackgroundResource(b ? R.color.color_ce5a5a : R.drawable.receipt_item_bg);
view.setBackgroundColor(Color.parseColor("#ce5a5a"));
}
return false;
}
});
I need to use Androids Switch button control but I need to be able to detect changes when the user is dragging the control not on clicking. So if the user drags from off to on and holds it in the on position I need to detect that. I thought I could just set the onTouchListener and then look at when the switches text changes state (on/off off/on) and then trigger my changes then but I can't. The
mySwitch.getText()
Does not work for me. It return blank text even though I have the textOn and textOff attributes set. I need to be able to detect the state change when the user is dragging, not on click. The onCheckedChanged listener will not work for me since that triggers only when the user toggles or slides and lifts there finger off of the button. Any help would be appreciated. Thank you.
Basic Code:
public class MainActivity extends Activity {
private String TAG = MainActivity.class.getSimpleName();
private TextView switchStatus;
private Switch mySwitch;
private TextView mySwitchText;
private String oldState;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchStatus = (TextView) findViewById(R.id.switchStatus);
mySwitch = (Switch) findViewById(R.id.mySwitch);
//set the switch to ON
mySwitch.setChecked(false);
oldState = mySwitch.getText().toString();
//attach a listener to check for changes in state
mySwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(isChecked){
//switchStatus.setText("Switch is currently ON");
}else{
// switchStatus.setText("Switch is currently OFF");
}
}
});
mySwitch.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == event.ACTION_MOVE) {
if(oldState.equals("OFF") && mySwitch.getText().equals("ON")) {
switchStatus.setText("Off to On");
oldState = "ON";
}
if(oldState.equals("ON") && mySwitch.getText().equals("OFF")) {
switchStatus.setText("On to Off");
oldState = "OFF";
}
}
Log.v(TAG, "Old State: " + oldState + " my Switch: " + mySwitch.getText().toString());
return false;
}
});
mySwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mySwitch.isChecked()) {
mySwitch.setChecked(false);
}
}
});
//check the current state before we display the screen
if(mySwitch.isChecked()){
switchStatus.setText("Switch is currently ON");
}
else {
switchStatus.setText("Switch is currently OFF");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Switch is a distant descendant of textview. Therefore you'd have to do this to make it work.
oldState = (TextView)mySwitch.getText().toString();
However, Switch has a textOn and textOff that works for this purpose.