ANDROID: clicking multiple checkboxes - java

I want to show the name of those multiple checkboxes that was checked. The problem is that when I check on any of them, only the last one checked is written on the textview. How can I resolve this?
I don't really understand how I will concatenate the names of those checkboxes.
public void ChkCommand(View v)
{
txtans = (EditText)findViewById(R.id.txtcon1);
if(v.getId() == R.id.chk1 && ((CheckBox)v).isChecked()){
chkClick = (CheckBox) findViewById(R.id.chk1);
}
else if(v.getId() == R.id.chk2 && ((CheckBox)v).isChecked()){
chkClick = (CheckBox) findViewById(R.id.chk2);
}
else if(v.getId() == R.id.chk3 && ((CheckBox)v).isChecked()){
chkClick = (CheckBox) findViewById(R.id.chk3);
}
String value = chkClick.getText().toString();
txtans.setText(value);
}
public void CloseConF(View v)
{
Intent intent = new Intent(this, SampComponents.class);
startActivity(intent);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.con_chk_samp, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_con_chk_samp,
container, false);
return rootView;
}
}
}

Each time you want to display the state of all your three checkboxes, you have to check all three:
String value = "";
if (((CheckBox) findViewById(R.id.chk1)).isChecked()) {
value += (CheckBox) findViewById(R.id.chk1).getText().toString();
}
if (((CheckBox) findViewById(R.id.chk2)).isChecked()) {
value += (CheckBox) findViewById(R.id.chk2).getText().toString();
}
if (((CheckBox) findViewById(R.id.chk3)).isChecked()) {
value += (CheckBox) findViewById(R.id.chk3).getText().toString();
}
txtans = (EditText)findViewById(R.id.txtcon1);
txtans.setText(value);
Then of course there would be some refactoring to do to get something cleaner, but that should get you started.

Try getting the checkbox text in every if else and append to a string value like this. chkBox1, chkBox2 and chkBox3 will be CheckBoxes in your java class.
public void ChkCommand(View v)
{
String value="";
txtans = (EditText)findViewById(R.id.txtcon1);
if(chkBox1.isChecked())
{
/*((CheckBox) findViewById(R.id.chk3)).setChecked(false);
((CheckBox) findViewById(R.id.chk2)).setChecked(false);*/
chkClick = (CheckBox) findViewById(R.id.chk1);
value += chkClick.getText().toString()+", ";
}
if(chkBox2.isChecked())
{
/*((CheckBox) findViewById(R.id.chk1)).setChecked(false);
((CheckBox) findViewById(R.id.chk3)).setChecked(false);*/
chkClick = (CheckBox) findViewById(R.id.chk2);
value += chkClick.getText().toString()+", ";
}
if(chkBox3.isChecked())
{/*
((CheckBox) findViewById(R.id.chk1)).setChecked(false);
((CheckBox) findViewById(R.id.chk2)).setChecked(false);*/
chkClick = (CheckBox) findViewById(R.id.chk3);
value += chkClick.getText().toString();
}
txtans.setText(value);
}
So you will get the result with all checked checkboxes' text. Hope this helps.
P.S: I just realized from #njzk2 's comment that you will need to changed else if to if in order to get all checkboxes's state.

Make value a field
private String value = "";
then change
String value = chkClick.getText().toString();
to something as:
value = value + " / " + chkClick.getText().toString();
But it's also necessary to tweak a bit the logic for reading the status from the checkboxes, otherwise they will add text also while un-checking.

Declare StringBuffer or StringBuilder member variables
StringBuffer buff = new StringBuffer();
Try this
buff.append(chkClick.getText().toString()+" ");
txtans.setText(buff.toString());
in place of
String value = chkClick.getText().toString();
txtans.setText(value);
It should work if your checkbox checking action is working correctly

Related

Best solution for Checkbox in LinearLayout

In my LinearLayout, there's a variable number of CheckBoxes. In a question I had a month ago someone said it´s better to add checkboxes dynamicly instead of make them not visible.
Integer[] count = new Integer[]{1,2,3,4,5,6,7,8,9,10};
size = mFrageList.get(position).getAuswahlList().size();
for (int i = 0; i < size; i++) {
cBox = new CheckBox(this);
cBox.setText(mFrageList.get(position).getAuswahlList().get(i));
cBox.setId(count[i]);
cBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
antwortencode[position] += "" + buttonView.getId();
frageBeantworten.setText("Antwort :"+antwortencode[position]+" abgeben");
} else {
String id = Integer.toString(buttonView.getId());
antwortencode[position] = antwortencode[position].replaceAll(id,"");
if(!antwortencode[position].isEmpty() || antwortencode[position]!= "") {
frageBeantworten.setText("Antwort :" + antwortencode[position] + " abgeben");
} else {
frageBeantworten.setText("Keine Checkbox(en) gewählt");
}
}
}
});
antworten.addView(cBox);
Currently, I'm able to save a string with the checked checkboxes, if I un-check a checkbox, it deletes it's value out of the string.
If I update the activity, the string is saved, and the checkboxes get a new List from the mFrageList.get(position)getAuswahlList(); and fill a new string in the "antwortencode" List with their values.
If I go back to the last position, I have the string which was generated but the checkboxes aren't checked anymore. But they have the Strings from the old position. that means everything is saved except the state of the checkboxes. I cant set a cBox.setChecked(isChecked) or buttonView.setChecked(isChecked) or buttonView.setChecked(buttonView.isChecked()) or something which is nearly the same in syntax.
I don't know what I can do besides declaring 10 Checkboxes in a xml file to talk to them one by one and set the VISIBLE.false if the auswahlList.get(position).isEmpty().
IMPORTANT: My XML is a Scrollable Activity because the size of the content overextended the screen. Thats why i didn´t and can´t use a Listview. So i need a solution that uses a LinearLayout
The truth is, you should actually use a ListView. As long as you reuse a layout multiple times - do it.
There are 2 options:
ListView as root - add other contents of your layout as different types of view
ListView inside a scrollable layout - there are many lightweight implementations of ListView that allow it to wrap content, e.g. https://github.com/paolorotolo/ExpandableHeightListView
The other thing is how to maintain the state of Checkboxes - use model classes. It's extremely easy with a ListView as it forces you to use an Adapter which provides methods to iterate over all positions.
Example of an adapter:
public class CheckableItemAdapter extends BaseAdapter {
private List<Pair<Integer, Boolean>> items = new ArrayList<>();
public void setItems(List<Pair<Integer, Boolean>> items) {
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
ViewHolder holder;
if (convertView == null) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_checkable, parent, false);
holder = new ViewHolder(view);
view.setTag(holder);
} else {
view = convertView;
holder = (ViewHolder) view.getTag();
}
Pair<Integer, Boolean> item = items.get(position);
holder.itemCheck.setChecked(item.second);
return view;
}
static class ViewHolder {
CheckBox itemCheck;
public ViewHolder(View itemView) {
itemCheck = (CheckBox) itemView.findViewById(R.id.check);
}
}
}
I´ve managed to solve my problem alone, and now i want to share it, even if it isn´t the best example of programming.
Integer[] count = new Integer[]{1,2,3,4,5,6,7,8,9,10}; //maximum of 10 Checkboxes
size = mFrageList.get(position).getAuswahlList().size();
for (int i = 0; i < size; i++) {
cBox = new CheckBox(this);
cBox.setText(mFrageList.get(position).getAuswahlList().get(i));
cBox.setId(count[i]);
try{ //this is where the magic happens
if(antwortencode[position] != ""){ //cause i won´t want null in my db i´ve set "" as standard string in my activity for the List<String>
String code = antwortencode[position];
char[] c = code.toCharArray();
for(int j=0;j<=c.length;j++){
int x = c[j] -'0'; // 'char 1' - 'char 0' = Integer 1 , lol
if(cBox.getId()== x){ //compare them
cBox.toggle(); //if it fits, toggle
}
}
}
} catch (Exception e){
e.printStackTrace();
} //and here it ends
cBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
antwortencode[position] += "" + buttonView.getId();
frageBeantworten.setText("Antwort :"+antwortencode[position]+" abgeben");
} else {
String id = Integer.toString(buttonView.getId());
antwortencode[position] = antwortencode[position].replaceAll(id,"");
if(!antwortencode[position].isEmpty() || antwortencode[position]!= "") {
frageBeantworten.setText("Antwort :" + antwortencode[position] + " abgeben");
} else {
frageBeantworten.setText("Keine Checkbox(en) gewählt");
}
}
}
});
antworten.addView(cBox);
Ty for the answers and for the correction of my question.
Nostramärus

hide button if text length is < 1 in android studio

I'm new to Android and Java and I'm busy editing an existing app. I am trying to hide a button if no text is getting pulled in from a webservice. I have made it work with another button when the text is being populated
if (textEvent.length() > 1) {
buttonEventSetup.setVisibility(View.INVISIBLE);
}
but when I used:
if (textEvent.length() < 1) {
buttonAccessControl.setVisibility(View.INVISIBLE);
}
nothing seems to happen.
I don't know if the code snippet is in the wrong place or something else is overwriting the code. Here is my activity code:
package com.example.dsouchon.myapplication;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonEventSetup = (Button)findViewById(R.id.buttonEventSetup);
if(Local.isSet(getApplicationContext(), "LoggedIn"))
{
String loggedInUser = Local.Get(getApplicationContext(), "LoggedIn");
if(loggedInUser.length()>0)
{
buttonEventSetup.setVisibility(View.VISIBLE);
}
else
{
buttonEventSetup.setVisibility(View.GONE);
}
}
else
{
buttonEventSetup.setVisibility(View.GONE);
}
if(Local.isSet(getApplicationContext(), "EventName"))
{
String event = Local.Get(getApplicationContext(), "EventName");
TextView textEvent = (TextView) findViewById(R.id.textEventName);
textEvent.setText( event);
Button buttonAccessControl = (Button)findViewById(R.id.buttonAccessControl);
buttonAccessControl.setEnabled(true);
//HIDES SET EVENT BUTTON WHEN EVENT IS SET
if (textEvent.length() > 1) {
buttonEventSetup.setVisibility(View.INVISIBLE);
}
if (textEvent.length() < 1) {
buttonAccessControl.setVisibility(View.INVISIBLE);
}
}
else
{
Button buttonAccessControl = (Button)findViewById(R.id.buttonAccessControl);
buttonAccessControl.setEnabled(false);
}
if(Local.isSet(getApplicationContext(), "EventImage"))
{
TextView textEvent = (TextView) findViewById(R.id.textEventName);
String result = Local.Get(getApplicationContext(), "EventImage");
ImageView imageViewEventImage = (ImageView)findViewById(R.id.imageViewEventImage);
byte[] decodedString = Base64.decode(result, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
imageViewEventImage.setImageBitmap(decodedByte);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void setupEvent(View view) {
Intent intent = new Intent(MainActivity.this, SetupEvent.class );
finish();
startActivity(intent);
}
public void accessControl(View view) {
Button buttonEventSetup = (Button)findViewById(R.id.buttonEventSetup);
buttonEventSetup.setVisibility(View.GONE);
Intent intent = new Intent(MainActivity.this, MainActivity21.class );
finish();
startActivity(intent);
}
public void Logoff(View view) {
Local.Set(getApplicationContext(), "LoggedIn", "");
}
public void Login(View view) {
final AlertDialog ad=new AlertDialog.Builder(this).create();
MySOAPCallActivity cs = new MySOAPCallActivity();
try {
EditText userName = (EditText) findViewById(R.id.editUserName);
EditText password = (EditText) findViewById(R.id.editPassword);
String user = userName.getText().toString();
String pwd = password.getText().toString();
LoginParams params = new LoginParams(cs, user, pwd);
Local.Set(getApplicationContext(), "UserName", user);
Local.Set(getApplicationContext(), "Password", pwd);
new CallSoapLogin().execute(params);
// new CallSoapGetCurrentEvents().execute(params);
} catch (Exception ex) {
ad.setTitle("Error!");
ad.setMessage(ex.toString());
}
ad.show();
}
public class CallSoapLogin extends AsyncTask<LoginParams, Void, String> {
private Exception exception;
#Override
protected String doInBackground(LoginParams... params) {
return params[0].foo.Login(params[0].username, params[0].password);
}
protected void onPostExecute(String result) {
// TODO: check this.exception
// TODO: do something with the feed
try {
TextView loginResult =(TextView)findViewById(R.id.labelLoginResult);
loginResult.setVisibility(View.VISIBLE);
loginResult.setText(result);
// Button buttonUnsetEvent = (Button)findViewById(R.id.buttonUnsetEvent);
// buttonUnsetEvent.setEnabled(true);
//Spinner spinner2 = (Spinner)findViewById(R.id.spinner2);
//spinner2.setEnabled(true);
boolean LoginSuccessful = false;
if(result.toLowerCase().contains("success"))
{
LoginSuccessful = true;
}
if (LoginSuccessful)
{
String user = Local.Get(getApplicationContext(), "UserName");
Local.Set(getApplicationContext(), "LoggedIn", user);
LinearLayout layoutLoggedIn = (LinearLayout)findViewById(R.id.layoutLoggedIn);
layoutLoggedIn.setVisibility(View.VISIBLE);
Button buttonEventSetup = (Button)findViewById(R.id.buttonEventSetup);
buttonEventSetup.setVisibility(View.VISIBLE);
LinearLayout layoutLogIn = (LinearLayout)findViewById(R.id.layoutLogIn);
layoutLogIn.setVisibility(View.VISIBLE);
}
} catch (Exception ex) {
String e3 = ex.toString();
}
}
}
private static class LoginParams {
MySOAPCallActivity foo;
String username;
String password;
LoginParams(MySOAPCallActivity foo, String username, String password) {
this.foo = foo;
this.username = username;
this.password = password;
}
}
}
You are getting the length of Textview that will not work.Use the text length.This should work
String event = Local.Get(getApplicationContext(), "EventName");
//HIDES SET EVENT BUTTON WHEN EVENT IS SET
if (event.length() > 1) {
buttonEventSetup.setVisibility(View.VISIBLE);
}
if (event.length() < 1) {
buttonAccessControl.setVisibility(View.INVISIBLE);
}
In your code above textEvent is not a string value. It is an Object of type TextView. length() in this case will not return the length of the text contained within that element. You will need to explicitly get the text string before you can get the length of it. This is acquired using the getText() method on the TextView.
Your code should look like the following:
//HIDES SET EVENT BUTTON WHEN EVENT IS SET
if (textEvent.getText().length() >= 1) {
buttonEventSetup.setVisibility(View.VISIBLE);
}
if (textEvent.getText().length() < 1) {
buttonAccessControl.setVisibility(View.INVISIBLE);
}
You also have INVISIBLE on both cases in your posted code example.
Note that your code also does not handle cases where the text length == 1. You could simplify the whole block with the following.
Note: any value != 0 is classed as true
buttonEventSetup.setVisibility(textEvent.getText().length() ? View.VISIBLE : View.INVISIBLE);

how to know the check box value of a particular row of a listview

hey how can i know that the below checkbox when clicked is from which row of the list.
is there any way of knowing that. Every time yo is returning false which is its default value.
checkBox.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v ;
callBlockOptions callBlockOptions = (callBlockOptions) cb.getTag();
callBlockOptions.setChecked( cb.isChecked() );
String yo;
if(callBlockOptions.getPosition()=="0")
{
callBlockOptions.setAllCalls();
}
if(callBlockOptions.getAllCalls() ==true)
yo="true";
else
yo="false";
Toast.makeText(getContext(), callBlockOptions.getPosition(), Toast.LENGTH_LONG).show();
}
});
}
After seeing your code, one thing you might want to try is setting listeners for the individual children within the ListView. You could do something like this:
ListView listView = (ListView)findViewById(R.id.listView);
int count = listView.getChildCount();
for (int x = 0; x < count; x++)
{
Class<? extends View> c = listView.getChildAt(x).getClass();
if (c == CheckBox.class)
{
CheckBox checkBox = (CheckBox)(listView.getChildAt(x));
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton compoutButton, boolean isChecked) {
// TODO Auto-generated method stub
callBlockOptions.isChecked = isChecked;
}
});
}
else if (c == TextView.class)
{
TextView textView = (TextView)(listView.getChildAt(x));
textView.setOnEditorActionListener(new OnEditorActionListener(){
#Override
public boolean onEditorAction(TextView tView, int arg1, KeyEvent arg2) {
// TODO Auto-generated method stub
callBlockOptions.name = tView.getText().toString();
return true;
}
});
}
You probably want your other class to be like this:
public class callBlockOptions {
public static String name;
public static Boolean isChecked;
}
Then you can get and set name and isChecked like this:
callBlockOptions.isChecked = false;
Boolean boolVal = callBlockOptions.isChecked;

How to validate to rating bar on Button click in Android?

I want to validation on RatingBar in Android. I have 5 rating Bar and 1 Button. I don't want to submit the data without pressed the rating bar. I want to take validation on Rating bar.
Can someone help me. How to take validation on Rating bar?
Here is my Activity code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rating_baar);
databaseHelper = new DatabaseHelper(this);
databaseHelper.onOpen(db);
addListenerOnRatingBar_one();
addListenerOnRatingBar_two();
addListenerOnRatingBar_three();
addListenerOnRatingBar_four();
addListenerOnRatingBar_five();
addListenerOnButton();
}
#SuppressLint("SimpleDateFormat")
public void addListenerOnButton() {
buttonSubmitRate = (Button) findViewById(R.id.button_SubmitRate);
buttonSubmitRate.setOnClickListener(new OnClickListener() {
#SuppressLint("SimpleDateFormat")
#Override
public void onClick(View v) {
if((etTaskName.getText().toString().isEmpty()))
etTaskName.setError("Field Can Not Be Empty !");
else if (!etTaskName.getText().toString().trim().matches("[a-zA-Z{ }]+"))
etTaskName.setError("Accept Alphabets Only.");
else {
strEmpName = textViewNAme.getText().toString().trim();
strTaskName = etTaskName.getText().toString().trim();
String strCurrentDate = new SimpleDateFormat("dd/MM/yyyy").format(new Date());
System.out.println("strCurrentDate = " + strCurrentDate);
String strCurrentMonth = new SimpleDateFormat("MMM").format(new Date());
System.out.println("strCurrentDate = " + strCurrentMonth);
String strCurrenYear = new SimpleDateFormat("yyyy").format(new Date());
System.out.println("strCurrenYear = " + strCurrenYear);
System.out.println("__________________________________________________________________________________");
databaseHelper.insertPerformance_Details(intentStr1, strEmpName,
strTaskName, rateVal_one,
rateVal_two, rateVal_three,
rateVal_four,rateVal_five,
strCurrentDate,strCurrentMonth,
strCurrenYear);
System.out.println("Data Add SuccesFully !!!!");
etTaskName.setText("");
Intent i = new Intent(RatingBaar_Class.this, Rating_Msg.class);
startActivity(i);
finish();
overridePendingTransition(R.anim.anim_in,R.anim.anim_out);
}
}
});
}
public void addListenerOnRatingBar_one() {
ratingBar_one = (RatingBar) findViewById(R.id.ratingBar1);
ratingBar_one.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
rateVal_one = String.valueOf(rating);
System.out.println(" rateVal_one = " + rateVal_one);
}
});
}
/* Exactly the same methods for four other rating bars, except for variable names */
public void addListenerOnRatingBar_two() { ... }
public void addListenerOnRatingBar_three() { ... }
public void addListenerOnRatingBar_four() { ... }
public void addListenerOnRatingBar_five() { ... }
At first set all rating bar to 0 value. Then on click to button, check if the value has altered in all of them. If so, only valid else invalid.
Also you can use listener to each rating bar and change value of some boolean variable to true
Example:
boolean flag1 = false;
boolean flag2 = false;
.... //similarly upto 5
Then in rating bar listener1
{
flag1 = true;
}
Similarly for all set flag to be true
And in button onClickListener do the following:
if(flag1 && flag2 && flag3 && flag4 && flag5){
//do your work
}else{
//display message that one of the rating bar hasn't been touched
}

How can I capture a long press on a Menu Item?

I have a typical menu and I'm wanting to set a onLongClickListener for one of the items. In other words, I want this item to perform it's normal onOptionsItemSelected function, as well as, a long press function.
MenuItem item;
item = menu.findItem(android.R.id.home);
item.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View v) {
Context context = getApplicationContext();
CharSequence text = "Long Press";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
return true;
}
});
I was able to do this by simply using setActionView on menuItem. You can follow this procedure if it helps.
for(int i = 0; i < menu.size(); i++){
View v = new View(this);
v.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
//Your longclick listener callback logic goes here
return false;
}
});
menu.getItem(i).setActionView(v);
}
Use the findItem method on Menu to get your views, and set your long click listener on each view.
This approach is not right, it disturbs entire flow, but here you go:
private interface OnMenuItemLongClickListener{
boolean onMenuItemLongClik(MenuItem m);
}
private void getMenuItemsView(Activity a, final Menu m, final OnMenuItemLongClickListener listener) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException{
View homeButton = a.findViewById(android.R.id.home);
ViewParent parentOfHome = homeButton.getParent().getParent(); //ActionBarView is parent of home ImageView, see layout file in sources
if (!parentOfHome.getClass().getName().contains("ActionBarView")) {
parentOfHome = parentOfHome.getParent();
Class absAbv = parentOfHome.getClass().getSuperclass(); //ActionBarView -> AbsActionBarView class
Field actionMenuPresenterField = absAbv.getDeclaredField("mActionMenuPresenter");
actionMenuPresenterField.setAccessible(true);
Object actionMenuPresenter = actionMenuPresenterField.get(parentOfHome);
Field actionMenuViewField = actionMenuPresenter.getClass().getSuperclass().getDeclaredField("mMenuView");
actionMenuViewField.setAccessible(true);
Object actionMenuView = actionMenuViewField.get(actionMenuPresenter);
Field childrenField= actionMenuView.getClass().getSuperclass().getSuperclass().getDeclaredField("mChildren");
childrenField.setAccessible(true);
Field menuField =actionMenuPresenter.getClass().getSuperclass().getDeclaredField("mMenu");
menuField.setAccessible(true);
Object menu = menuField.get(actionMenuPresenter);
Object[] menuItemsAsViews = (Object[])childrenField.get(actionMenuView);
View.OnLongClickListener longListener = new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
return listener.onMenuItemLongClik(m.findItem(v.getId()));
}
};
for(Object menuView:menuItemsAsViews ){
View v = (View)menuView;
v.setOnLongClickListener(longListener);
}
}
}
Usage:
#Override
public boolean onPrepareOptionsMenu(final Menu menu) {
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
getMenuItemsViews(MainActivity.this, menu);
}}, 100); //must be called after the menu views are generated, otherwise NPE.
return super.onPrepareOptionsMenu(menu);
}
MenuItem's in the overflow WILL NOT be considered.

Categories

Resources