package
com.gtappdevelopers.kotlingfgproject;
import
android.graphics.Typeface;
import
android.os.Build;
import
android.os.Bundle;
import
android.view.Gravity;
import
android.view.View;
import
android.view.ViewGroup;
import
android.widget.CompoundButton;
import
android.widget.LinearLayout;
import
android.widget.Switch;
import
android.widget.TextView;
import
androidx.annotation.RequiresApi;
import
androidx.appcompat.app.AppCompatActivity;
public
class
MainActivity
extends
AppCompatActivity {
private
LinearLayout containerLL;
@RequiresApi
(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
containerLL = findViewById(R.id.idLLContainer);
LinearLayout.LayoutParams txtLayoutParam =
new
LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);
txtLayoutParam.gravity = Gravity.CENTER;
TextView headingTV =
new
TextView(
this
);
headingTV.setText(
"Dynamic Switch in Android"
);
headingTV.setTextSize(20f);
headingTV.setTextColor(getResources().getColor(R.color.black));
headingTV.setTypeface(Typeface.DEFAULT_BOLD);
headingTV.setPadding(
20
,
20
,
20
,
20
);
headingTV.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
headingTV.setLayoutParams(txtLayoutParam);
TextView statusTV =
new
TextView(
this
);
statusTV.setText(
"Status"
);
statusTV.setTextSize(20f);
statusTV.setTextColor(getResources().getColor(R.color.black));
statusTV.setTypeface(Typeface.DEFAULT_BOLD);
statusTV.setPadding(
20
,
20
,
20
,
20
);
statusTV.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
statusTV.setLayoutParams(txtLayoutParam);
LinearLayout.LayoutParams switchLayoutParam =
new
LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);
switchLayoutParam.gravity = Gravity.CENTER;
switchLayoutParam.setMargins(
10
,
10
,
10
,
10
)
Switch switchView =
new
Switch(
this
);
switchView.setLayoutParams(switchLayoutParam);
if
(switchView.isChecked()) {
statusTV.setText(
"Switch is Checked"
);
}
else
{
statusTV.setText(
"Switch is UnChecked"
);
}
switchView.setOnCheckedChangeListener(
new
CompoundButton.OnCheckedChangeListener() {
@Override
public
void
onCheckedChanged(CompoundButton buttonView,
boolean
isChecked) {
if
(isChecked) {
statusTV.setText(
"Switch is Checked"
);
}
else
{
statusTV.setText(
"Switch is UnChecked"
);
}
}
});
}
}