Question

Question: I am trying to take the index of the selected radio button and use that in the onClick function.

Example:

    btnCalc.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
               if (getIndex(k) == 0) {
                      DO THIS
               }       
               if (getIndex(k) == 1) {
                      DO THAT
               }                
    });

I have the following code in my Android app:

    int POS; //global variable assigned right under MainActivity
    final RadioGroup rgTypeOfTrip = (RadioGroup) findViewById(R.id.rgTripType);
    Button btnCalc = (Button) findViewById(R.id.btnCalculate);

        btnCalc.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                  Toast.makeText(MainActivity.this, Integer.toString(getIndex(POS1)), Toast.LENGTH_SHORT).show(); //DOESN'T WORK
        });

        rgTypeOfTrip.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // TODO Auto-generated method stub

                // Method 1
                int pos=rgTypeOfTrip.indexOfChild(findViewById(checkedId));
                    getIndex(pos);
                Toast.makeText(MainActivity.this, String.valueOf(pos), Toast.LENGTH_SHORT).show();
            }
        });

public int getIndex(int POS1) {
    Toast.makeText(MainActivity.this, Integer.toString(POS1), Toast.LENGTH_SHORT).show(); // WORKS
    return POS1;
}

How can I achieve this line:

Toast.makeText(MainActivity.this, CALL FUNCTION GETINDEX() to get value, Toast.LENGTH_SHORT).show();

To call the function to get the value of k?

Was it helpful?

Solution

Assuming your question is in the Toast such that it is: "CALL FUNCTION GETINDEX() to get value"

Toast.makeText(MainActivity.this, Integer.toString(getIndex(int)), Toast.LENGTH_SHORT).show();

You pass in the integer that is returned though so you could just go with the following (under my assumptions of your code):

Toast.makeText(MainActivity.this, Integer.toString(int), Toast.LENGTH_S
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top