Search code examples
androidandroid-switch

Button can't be called from onCheckedChanged until I click Switch and click it agan to return to default state


In my code I have 2 EditBox and a Switch. When I click on Switch to true it sets visible linear layout that contains one more EditText with imagelinearLayout.setVisibility(View.VISIBLE);

On the bottom I have a Button that does calculations of 2 cases:

  1. case when Switch is android:checked="false", where it just calculates values of first 2 EditBox-s
  2. case when Switch is true and I use the third EditBox in caluculation with the first 2 Editbox-s

PROBLEM: When I open the Activity and enter values in the first 2 EditBox the, and Switchs is defaultly false, I click on the Button to calculate and nothing happens.

But, if I just change state of Switch to true and to false again. Then I click to button and it calculates with no problem.

It completely ignores my code until I change state.

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">


        <EditText
            android:maxLines="1"
            android:padding="12dp"
            android:id="@+id/var1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="numberDecimal"
            android:hint="Probing pulse width (s)"/>

    <EditText
        android:maxLines="1"
        android:padding="12dp"
        android:id="@+id/var2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:ems="10"
        android:imeOptions="actionDone"
        android:inputType="numberDecimal"
        android:hint="Pulse Repetition Time (s)"/>


    <Switch
        android:checked="false"
        android:text="Average transmitting power"
        android:paddingLeft="10dp"
        android:id="@+id/switchID"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="#ffffff"/>


<LinearLayout
    android:animateLayoutChanges="true"
    android:id="@+id/hidden"
    android:padding="10dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:paddingTop="3dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/lambda"/>

    <EditText
        android:maxLines="1"
        android:padding="12dp"
        android:id="@+id/var3"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:ems="10"
        android:imeOptions="actionDone"
        android:inputType="numberDecimal"
        android:hint="Pulse Repetition Time (s)"/>


</LinearLayout>

<Button
    android:id="@+id/calculate"
    android:clickable="true"
    android:textColor="@android:color/white"
    style="@style/Widget.AppCompat.Button.Colored"
    android:text="Calculate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"/>

<LinearLayout
    android:background="@color/colorAccent"
    android:layout_margin="15dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <TextView
        android:padding="5dp"
        android:id="@+id/rezultatID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textAlignment="center"
        android:textSize="18sp"
        android:textStyle="bold"/>
</LinearLayout>
</LinearLayout>

MainActivity.java

public class DutyCycle extends AppCompatActivity
{

String naziv;
EditText var1, var2, var3;
Button calculate;
TextView result;
Switch simpleSwitch;
double nResult, nVar1, nVar2, nVar3;
LinearLayout linearLayout;

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

    naziv = getIntent().getStringExtra("formulica");

    simpleSwitch = (Switch) findViewById(R.id.switchID);

    var1 = (EditText) findViewById(R.id.var1);
    var2 = (EditText) findViewById(R.id.var2);
    var3 = (EditText) findViewById(R.id.var3);
    calculate = (Button) findViewById(R.id.calculate);
    result = (TextView) findViewById(R.id.rezultatID);

    linearLayout = (LinearLayout) findViewById(R.id.hidden);
    linearLayout.setVisibility(View.GONE);

    simpleSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
    {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            if(isChecked)
            {

                calculate.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        if(!var1.getText().toString().equals("") & !var2.getText().toString().equals(""))
                        {
                              nVar1 = Double.parseDouble(var1.getText().toString());
                              nVar2 = Double.parseDouble(var2.getText().toString());
                              nVar3 = Double.parseDouble(!var3.getText().toString().equals("") ? var3.getText().toString() : "0");

                            nResult = (nVar1 / nVar2) * nVar3;


                            result.setText(String.valueOf(nResult) + " [W]");
                        }
                        else
                        {
                            Snackbar.make(findViewById(android.R.id.content), "Please fill in all fields", Snackbar.LENGTH_LONG)
                                    .setAction("CLOSE", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {}
                                    })
                                    .setActionTextColor(ContextCompat.getColor(getApplicationContext(), android.R.color.holo_blue_light))
                                    .show();
                        }
                    }
                });
            }
            else
            {
                calculate.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        if(!var1.getText().toString().equals("") & !var2.getText().toString().equals(""))
                        {
                              nVar1 = Double.parseDouble(var1.getText().toString());
                              nVar2 = Double.parseDouble(var2.getText().toString());

                            nResult = (nVar1 / nVar2) * 100;
                            result.setText(String.valueOf(nResult) + " [%]");
                        }
                        else
                        {
                            Snackbar.make(findViewById(android.R.id.content), "Please fill in all fields", Snackbar.LENGTH_LONG)
                                    .setAction("CLOSE", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {}
                                    })
                                    .setActionTextColor(ContextCompat.getColor(getApplicationContext(), android.R.color.holo_blue_light))
                                    .show();
                        }
                    }
                });
            }
        }
    });
}
}

I tried with adding some boolean value in the onCheckedChanged so if it doesn't change state for the first time I could copy the code of calculate.setOnClickListener but it doesn't work.


Solution

  • Thanks to DroidDev i managed to fix this now. I got calculate outside the onCheckedChanged and used if(linearLayout.getVisibility() == View.GONE) to get what formula when to use.

    This is the working code now. Hope it

        simpleSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
        {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
            {
                if(isChecked)
                {
                    linearLayout.setVisibility(View.VISIBLE);
                    linearLayout.setAlpha(0.0f);
                    linearLayout.animate()
                            .setDuration(500)
                            .alpha(1.0f)
                            .setListener(new AnimatorListenerAdapter() {
                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    super.onAnimationEnd(animation);
                                    linearLayout.animate().setListener(null);
                                }
                            });
                }
                else
                {
                    linearLayout.animate()
                                .setDuration(300)
                                .alpha(0.0f)
                                .setListener(new AnimatorListenerAdapter() {
                                    @Override
                                    public void onAnimationEnd(Animator animation) {
                                        super.onAnimationEnd(animation);
                                        linearLayout.setVisibility(View.GONE);
                                        linearLayout.animate().setListener(null);
                                    }
                                });
                }
            }
        });
    
    
        calculate.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if(linearLayout.getVisibility() == View.GONE) {
                    if (!var1.getText().toString().equals("") & !var2.getText().toString().equals("")) {
                        nVar1 = Double.parseDouble(var1.getText().toString());
                        nVar2 = Double.parseDouble(var2.getText().toString());
    
                        nResult = (nVar1 / nVar2) * 100;
                        result.setText(String.valueOf(nResult) + " [%]");
                    } else {
                        Snackbar.make(findViewById(android.R.id.content), "Please fill in all fields", Snackbar.LENGTH_LONG)
                                .setAction("CLOSE", new View.OnClickListener()
                                {
                                    @Override
                                    public void onClick(View view) {
    
                                    }
                                })
                                .setActionTextColor(ContextCompat.getColor(getApplicationContext(), android.R.color.holo_blue_light))
                                .show();
                    }
                }else
                {
                    if(!var1.getText().toString().equals("") & !var2.getText().toString().equals(""))
                    {
                        nVar1 = Double.parseDouble(var1.getText().toString());
                        nVar2 = Double.parseDouble(var2.getText().toString());
                        nVar3 = Double.parseDouble(!var3.getText().toString().equals("") ? var3.getText().toString() : "0");
    
                        nResult = (nVar1 / nVar2) * nVar3;
    
    
                        result.setText(String.valueOf(nResult) + " [W]");
                    }
                    else
                    {
                        Snackbar.make(findViewById(android.R.id.content), "Please fill in all fields", Snackbar.LENGTH_LONG)
                                .setAction("CLOSE", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
    
                                    }
                                })
                                .setActionTextColor(ContextCompat.getColor(getApplicationContext(), android.R.color.holo_blue_light))
                                .show();
                    }
                }
            }
        });