Pregunta

I have a xml file with several buttons, and I want to use one onclickListener for all, so that I can use switch-case statement and depending on each button's R.getId I perform certain action.

Java_Code:

public class LayoutAndViewsProgrammatically extends ActionBarActivity {

OnLongClickListener mOnClickListener = new OnLongClickListener() {

    @Override
    public boolean onLongClick(View v) {
        // TODO Auto-generated method stub
        return false;
    }
}; 
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    View mAddButton = findViewById(R.id.addBtn00);
    mAddButton.setOnClickListener(mOnClickListener);

    View mRemoveButton = findViewById(R.id.removeBtn00);
    mRemoveButtonButton.setOnClickListener(mOnClickListener);
}
¿Fue útil?

Solución

try below code:-

public class LayoutAndViewsProgrammatically extends ActionBarActivity implements OnClickListener

implement below method into you activity

@Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.click_first:
                // click first
                break;
            case R.id.click_sec:
                // click second             
                break;

            case R.id.click_third:
                // click third
                break;
            case R.id.click_fouth:
                // click fourth             
                break;
            default:
                break;
        }
    }

Otros consejos

Try this

@Override
protected void onCreate(Bundle savedInstanceState) 
{
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  View mAddButton = findViewById(R.id.addBtn00);
  mAddButton.setOnClickListener(mOnClickListener);

  View mRemoveButton = findViewById(R.id.removeBtn00);
  mRemoveButtonButton.setOnClickListener(mOnClickListener);
}

private OnClickListener mOnClickListener = new OnClickListener()
{

    @Override
    public void onClick(View v)
    {
        try
        {
            if (v.getId() == R.id.button1)
            {

            }
            else if (v.getId() == R.id.button2)
            {

            }
            else if (v.getId() == R.id.button3)
            {

            }

        }
        catch (Exception e)
        {
            Logger.LogException(e);
        }
    }
};

You were creating an object of OnLongClickListener but you need to create an object of OnClickListener and assign to the Button

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top