Enable Night mode using RadioButton in Android - java

I have an app which has Dialogbox with 3 Radios and RadioGroup,
So if the Light Radio is checked, after clicking Okay, the theme of the app will be changed to light theme.
If Dark is checked, after clicking Okay, the theme will be changed to night themeand if system it will be changed to system.
Toolbar:
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFF"
style="#style/TextAppearance.AppCompat.Widget.Button.Borderless.Colored"
android:elevation="0dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
</androidx.appcompat.widget.Toolbar>
Menu:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/chooseTheme"
android:onClick="chooseTheme"
android:title="Choose Theme"
app:showAsAction="never"
tools:ignore="HardcodedText" />
</menu>
DialogBox:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<RadioGroup
android:id="#+id/themeGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:elevation="5dp"
android:gravity="center"
android:paddingStart="20dp"
android:paddingTop="20dp"
android:paddingEnd="20dp"
android:paddingBottom="5dp"
tools:ignore="UselessParent">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_marginBottom="20dp"
android:text="Choose Theme"
android:textColor="#color/black"
android:textColorHint="#FFFFFF"
android:textSize="20sp"
tools:ignore="HardcodedText" />
<RadioButton
android:id="#+id/radioLight"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginBottom="10dp"
android:buttonTint="#color/colorPrimary"
android:checked="true"
android:text="Light"
android:textSize="18sp"
tools:ignore="HardcodedText" />
<RadioButton
android:id="#+id/radioDark"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginBottom="10dp"
android:buttonTint="#color/colorPrimary"
android:text="Dark"
android:textSize="18sp"
tools:ignore="HardcodedText" />
<RadioButton
android:id="#+id/radioSystem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginBottom="10dp"
android:buttonTint="#color/colorPrimary"
android:text="System"
android:textSize="18sp"
tools:ignore="HardcodedText" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:layout_marginStart="80dp"
android:orientation="horizontal"
tools:ignore="RtlHardcoded">
<Button
android:id="#+id/btn_cancel"
style="?android:attr/borderlessButtonStyle"
android:layout_width="100dp"
android:layout_height="60dp"
android:gravity="center|center_vertical|fill_vertical"
android:scaleY="0.9"
android:text="Cancel"
android:textAlignment="center"
android:textAllCaps="false"
android:textColor="#color/colorPrimary"
android:textSize="14sp"
tools:ignore="ButtonStyle,HardcodedText" />
<Button
android:id="#+id/btn_okay"
style="?android:attr/borderlessButtonStyle"
android:layout_width="100dp"
android:layout_height="60dp"
android:layout_marginStart="10dp"
android:gravity="center|center_vertical|fill_vertical"
android:scaleY="0.9"
android:text="Okay"
android:textAlignment="center"
android:textAllCaps="false"
android:textColor="#color/colorPrimary"
android:textSize="14sp"
tools:ignore="ButtonStyle,HardcodedText" />
</LinearLayout>
</RadioGroup>
</LinearLayout>
MainActivity:
public void chooseTheme(MenuItem item) {
final AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_theme,null);
Button btn_cancel = mView.findViewById(R.id.btn_cancel);
Button btn_okay = mView.findViewById(R.id.btn_okay);
alert.setView(mView);
final AlertDialog alertDialog = alert.create();
alertDialog.setCanceledOnTouchOutside(false);
RadioButton radioLight = findViewById(R.id.radioLight);
final RadioButton radioDark =findViewById(R.id.radioDark);
RadioButton radioSystem =findViewById(R.id.radioSystem);
btn_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
btn_okay.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
alertDialog.show();
}
I tried everything I knew, not I have no idea how to do it.
Thank you for attention!

The following will check which radio button is checked inside RadioGroup:
RadioGroup radioGroup = mView.findViewById(R.id.themeGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch(i) {
case R.id.radioLight:
setLightTheme();
Toast.makeText(getApplicationContext(),"Light mode",Toast.LENGTH_LONG).show();
break;
case R.id.radioDark:
setDarkTheme();
Toast.makeText(getApplicationContext(),"Dark mode",Toast.LENGTH_LONG).show();
break;
}
}
});

I found some points in your code.
for first, I think you have to find your radio buttons from your view too.
like this:
RadioButton radioLight = mView.findViewById(R.id.radioLight);
final RadioButton radioDark = mView.findViewById(R.id.radioDark);
RadioButton radioSystem = mView.findViewById(R.id.radioSystem);
And for the second I think you can use SharedPreferences to find what the user has checked, before calling dialog.dimiss.

That's what was I trying to achieve
Boolean night = false;
public void chooseTheme(MenuItem item) {
final AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
final View mView = getLayoutInflater().inflate(R.layout.dialog_theme,null);
Button btn_okay = mView.findViewById(R.id.btn_okay);
Button btn_cancel = mView.findViewById(R.id.btn_cancel);
alert.setView(mView);
final AlertDialog alertDialog = alert.create();
alertDialog.setCanceledOnTouchOutside(false);
final RadioGroup themeGroup = mView.findViewById(R.id.themeGroup);
themeGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#SuppressLint("NonConstantResourceId")
#Override
public void onCheckedChanged(RadioGroup themeGroup, int i) {
switch(i) {
case R.id.radioLight:
night = false;
break;
case R.id.radioDark:
night = true;
break;
}
}
});
btn_okay.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View v) {
if(night){
sharedpref.setNightModeState(true);
Toast.makeText(getApplicationContext(),"Dark mode", Toast.LENGTH_LONG).show();
}
else if (!night){
sharedpref.setNightModeState(false);
Toast.makeText(getApplicationContext(),"Light mode",Toast.LENGTH_LONG).show();
}
alertDialog.dismiss();
restartApp();
}
});
btn_cancel.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
alertDialog.show();
}
SharedPref:
public class SharedPref {
SharedPreferences mySharedPref ;
public SharedPref(Context context) {
mySharedPref = context.getSharedPreferences("filename",Context.MODE_PRIVATE);
}
// this method will save the nightMode State : True or False
public void setNightModeState(Boolean state) {
SharedPreferences.Editor editor = mySharedPref.edit();
editor.putBoolean("NightMode",state);
editor.apply();
}
// this method will load the Night Mode State
public Boolean loadNightModeState (){
Boolean state = mySharedPref.getBoolean("NightMode",false);
return state;
}
}

Related

ListItem not responding to clickEvents in ArrayAdapter in Android?

"I was trying to create Toast message when user clicks on Description TextView and Like ImageButton. But the list_item is not responding to touch Events "
"I went through many other people answering about changing focus.But none of them are working"
EventsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final EventsObject mEventsObject = mEventsAdapter.getItem(position);
final String mEventUrl = mEventsObject.geteLink();
Log.e(TAG, "Inside ListVIew");
final boolean status = mEventsObject.hasLiked();
//LikeButton likeButton = view.findViewById(R.id.heart_button);
TextView description = view.findViewById(R.id.eventDesc);
//final TextView likesCountTextView = view.findViewById(R.id.likesCount);
Toast.makeText(MainActivity.this, "Liked", Toast.LENGTH_SHORT).show();
description.setFocusable(false);
description.setFocusableInTouchMode(false);
description.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!TextUtils.isEmpty(mEventUrl)) {
Intent openLinkInBrowser = new Intent(Intent.ACTION_VIEW);
openLinkInBrowser.setData(Uri.parse(mEventUrl));
startActivity(openLinkInBrowser);
} else {
Toast.makeText(MainActivity.this, "Links are not provided", Toast.LENGTH_SHORT).show();
}
}
});
Button loveBtn = view.findViewById(R.id.loveButton);
loveBtn.setFocusable(false);
loveBtn.setFocusableInTouchMode(false);
loveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (status) {
Toast.makeText(MainActivity.this, "Liked", Toast.LENGTH_SHORT).show();
mEventsObject.setHeartLiked(true);
} else {
Toast.makeText(MainActivity.this, "Disliked", Toast.LENGTH_SHORT).show();
mEventsObject.setHeartLiked(false);
}
}
});
}
XML for list_item is
?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="8dp"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:orientation="horizontal">
<TextView
android:id="#+id/organiser"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:paddingLeft="16dp"
android:textAllCaps="true"
android:textColor="#ffffff"
android:textSize="16sp"
android:textStyle="bold"
tools:text="Organiser" />
<TextView
android:id="#+id/dateOfEvent"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="right"
android:textColor="#ffffff"
android:textStyle="bold"
tools:text="12/03/20" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/organiserImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/events_circle"
android:padding="16dp"
android:src="#mipmap/ic_launcher"
android:textColor="#ffffff" />
<TextView
android:id="#+id/eventDesc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="4dp"
android:gravity="fill"
android:textColor="#ffffff"
android:textSize="16sp"
tools:text="#string/test_event_desc" />
</LinearLayout>
<ImageButton
android:id="#+id/loveButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="8dp"
android:background="#drawable/events_love"
android:scaleType="center"
android:src="#drawable/love" />
<!--
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="0dp">
<com.like.LikeButton
app:icon_type="heart"
app:icon_size="18dp"
android:id="#+id/heart_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
app:circle_start_color="#ff2134"
app:circle_end_color="#000000"
/>
-->
<!--<TextView
android:id="#+id/likesCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
tools:text="10"
android:textColor="#ffffff"/>
</LinearLayout>-->
</LinearLayout>
"I would like to have list_item's responding to click events and showing toast message..
Please Help..
THanks in Advance !!"
It may be because you are trying to perform click inside item click listener of ListView.
You can fix it by creating a custom adapter for listview. Customer ListView Adapter
After creating this custom adapter you can get the reference of description and loveBtn and perform click operation on this.
Your adapter's getView() code will be like this-
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
convertView=layoutInflater.inflate(R.layout.list_row, null);
TextView description=convertView.findViewById(R.id.eventDesc);
Button loveBtn=convertView.findViewById(R.id.loveButton);
}
description.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!TextUtils.isEmpty(mEventUrl)) {
Intent openLinkInBrowser = new Intent(Intent.ACTION_VIEW);
openLinkInBrowser.setData(Uri.parse(mEventUrl));
startActivity(openLinkInBrowser);
} else {
Toast.makeText(MainActivity.this, "Links are not provided", Toast.LENGTH_SHORT).show();
}
}
});
loveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (status) {
Toast.makeText(MainActivity.this, "Liked", Toast.LENGTH_SHORT).show();
mEventsObject.setHeartLiked(true);
} else {
Toast.makeText(MainActivity.this, "Disliked", Toast.LENGTH_SHORT).show();
mEventsObject.setHeartLiked(false);
}
}
});
return convertView;
}

Android Popup Menu fill parent

I try set my popup menu in way to fill hole item on grid. Currently it look like on attached first picture and the next one is effect which I would like to have.
My code:
private void showPopupMenu(View view) {
// inflate menu
ContextThemeWrapper ctw = new ContextThemeWrapper(context, R.style.PopupMenu);
PopupMenu popup = new PopupMenu(ctw, view);
Menu menu = popup.getMenu();
menu.add(Menu.NONE, 1, Menu.NONE, "Remove");
menu.add(Menu.NONE, 2, Menu.NONE, "Block");
popup.setOnMenuItemClickListener(new MyMenuItemClickListener());
popup.show();
}
Could you please point me to right direction to achieve effect from project?
Demo App for your requirment by using PopupWindow. Preview
You can add list in it or customize it according to your needs.
MainActivity
public class MainActivity extends Activity {
boolean isClicked = true;
PopupWindow popUpWindow;
RelativeLayout relative;
ImageView btnClickHere;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
relative = (RelativeLayout) findViewById(R.id.relative);
popUpWindow = new PopupWindow(this);
popUpWindow.setContentView(getLayoutInflater().inflate(R.layout.popup_design, null));
popUpWindow.getContentView().findViewById(R.id.textViewa).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "PopItemClicked", Toast.LENGTH_LONG).show();
}
});
btnClickHere = (ImageView) findViewById(R.id.imageView);
btnClickHere.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (isClicked) {
isClicked = false;
popUpWindow.setHeight(relative.getHeight());
popUpWindow.setWidth(relative.getWidth());
popUpWindow.showAsDropDown(relative, 0, -relative.getHeight());
} else {
isClicked = true;
popUpWindow.dismiss();
}
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.sohailzahid.testapp.MainActivity">
<RelativeLayout
android:id="#+id/relative"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="#color/colorAccent"
tools:layout_editor_absoluteX="150dp"
tools:layout_editor_absoluteY="150dp">
<ImageView
android:id="#+id/imageView"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:src="#android:drawable/arrow_down_float" />
</RelativeLayout>
</RelativeLayout>
popup_design.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F93567">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/textViewa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="Block"
android:textColor="#ffffff"
android:textSize="20dp" />
<TextView
android:id="#+id/textVsiewa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="Add to friends"
android:textColor="#ffffff"
android:textSize="20dp" />
<TextView
android:id="#+id/textViesw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="Remove"
android:textColor="#ffffff"
android:textSize="20dp" />
</LinearLayout>
<ImageView
android:id="#+id/imageView"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_margin="10dp"
android:src="#android:drawable/arrow_down_float" />
</RelativeLayout>
Try this
popup.getWindow().getAttributes().height = ViewGroup.LayoutParams.MATCH_PARENT;
popup.getWindow().getAttributes().width = ViewGroup.LayoutParams.MATCH_PARENT;

Checkbuttons crashes app when checked

I created a list of checkboxes, and I was trying to increase an int value proportionally to the number of the selected ones. Instead, every time I try to check them (through .isChecked()) the app crashes. I've tried to search everywhere for some solutions, but nothing worked. I really can't understand where is the problem.
Here's the code
XML file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.deadlybanana.myfirstapp.DisplayPicture">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginLeft="0dp"
android:layout_marginTop="0dp"
android:layout_marginRight="0dp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="0dp">
<LinearLayout
android:id="#+id/first"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:src="#drawable/unicorn" />
<TextView
android:id="#+id/frasenome"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="" />
<CheckBox
android:id="#+id/checkbox1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Are you Beatiful?" />
<CheckBox
android:id="#+id/checkbox2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Are you Fabolous?" />
<CheckBox
android:id="#+id/checkbox3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Are you Unique?" />
<CheckBox
android:id="#+id/checkbox4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Are you a horse?" />
<CheckBox
android:id="#+id/checkbox5"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Do you eat grass?" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="checkbutton"
android:text="Check if you are a unicorn" />
</LinearLayout>
</ScrollView>
</android.support.constraint.ConstraintLayout>
Java file
package com.example.deadlybanana.myfirstapp;
public class DisplayPicture extends AppCompatActivity {
List<Boolean> checkboxes = new ArrayList<Boolean>();
CheckBox press1;
CheckBox press2;
CheckBox press3;
CheckBox press4;
CheckBox press5;
int points = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_picture);
Intent intent = getIntent();
String name = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
CheckBox press1 = (CheckBox)findViewById(R.id.checkbox1);
CheckBox press2 = (CheckBox)findViewById(R.id.checkbox2);
CheckBox press3 = (CheckBox)findViewById(R.id.checkbox3);
CheckBox press4 = (CheckBox)findViewById(R.id.checkbox4);
CheckBox press5 = (CheckBox)findViewById(R.id.checkbox5);
TextView NameString = (TextView) findViewById(R.id.frasenome);
String phrase = name + ", are you some of these things?";
NameString.setText(phrase);
}
public void checkbutton(View view){
if (press1.isChecked()){
points += 4;
}
if (points > 3){
Toast.makeText(this, "You are a unicorn", Toast.LENGTH_LONG).show();
} else{
Toast.makeText(this, "You are not a unicorn", Toast.LENGTH_LONG).show();
}
}
}
(right now it is being examined just the first checkbox to simplify the code)
Try this: in onCreate()
press1 = (CheckBox)findViewById(R.id.checkbox1);
press2 = (CheckBox)findViewById(R.id.checkbox2);
press3 = (CheckBox)findViewById(R.id.checkbox3);
press4 = (CheckBox)findViewById(R.id.checkbox4);
press5 = (CheckBox)findViewById(R.id.checkbox5);
error occurs as press1.isChecked() is refers to the global CheckBox press1;
which is not yet initialized..
AS you are initializing the checkbox like:
CheckBox press1 = (CheckBox)findViewById(R.id.checkbox1); inside onCreate() which only gives it a local instance which is not accessable in your checkbutton(View view) function
Solution
remove the local initialization just use: press1 = (CheckBox)findViewById(R.id.checkbox1);
Set id for your button lets assume it be button and add the following code
Button btn = (Button)findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkbutton();
}
});
Note:remove the view parameter
Implementing Listeners is the best way to handle the events
I never use the method isChecked() because it never works for me. Do you want to increase the points when you select a checkbutton and maybe show the points when you press a button?
Here is the class code:
public class ButtonActivity extends AppCompatActivity
{
int points=0;
boolean check1=false;
boolean check2=false;
boolean check3=false;
boolean check4=false;
boolean check5=false;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_button);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(),points+"",Toast.LENGTH_SHORT).show();
}
});
}
public void onClick(View view)
{
switch(view.getId())
{
case R.id.checkBox:
if(check1)
{
check1=false;
points--;
}
else
{
check1=true;
points++;
}
break;
case R.id.checkBox2:
if(check2)
{
check2=false;
points--;
}
else
{
check2=true;
points++;
}
break;
case R.id.checkBox3:
if(check3)
{
check3=false;
points--;
}
else
{
check3=true;
points++;
}
break;
case R.id.checkBox4:
if(check4)
{
check4=false;
points--;
}
else
{
check4=true;
points++;
}
break;
case R.id.checkBox5:
if(check5)
{
check5=false;
points--;
}
else
{
check5=true;
points++;
}
break;
}
}
}
Here is the layout code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_button"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.example.utente.stackoverflow.ButtonActivity">
<CheckBox
android:text="CheckBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/checkBox"
android:onClick="onClick"/>
<CheckBox
android:text="CheckBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/checkBox2"
android:onClick="onClick"/>
<CheckBox
android:text="CheckBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/checkBox3"
android:onClick="onClick"/>
<CheckBox
android:text="CheckBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/checkBox4"
android:onClick="onClick"/>
<CheckBox
android:text="CheckBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/checkBox5"
android:onClick="onClick"/>
<Button
android:text="Points"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button" />
I tested it and it works. I hope this helps you.

null pointer exception on radio group

I am trying to make a popup window in an activity. The popup window shows up when we click a button in the activity. The layout for popup window is to show a radio group containing 4 radio buttons, a button and a seek bar and has to return a value to the main activity based on the selected radio button when the button in the pop up window is pressed.
When i run the app and open the pop up window it is giving we this error:
"java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RadioGroup.setOnCheckedChangeListener(android.widget.RadioGroup$OnCheckedChangeListener)' on a null object reference "
The code for my main activity is:
public class CustomMenuActivity extends Activity
{
String ingredientName;
String ingredientQuantity;
private PopupWindow pw;
Button setQuantity;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_menu);
setQuantity = (Button) findViewById(R.id.btnSetQty);
setQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
initiatePopupWindow();
}
});
}
private void initiatePopupWindow()
{
try {
//We need to get the instance of the LayoutInflater, use the context of this activity
LayoutInflater inflater = (LayoutInflater) CustomMenuActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Inflate the view from a predefined XML layout
View layout = inflater.inflate(R.layout.set_quantity_popup,
(ViewGroup) findViewById(R.id.popupElementid));
// create a 600px width and 570px height PopupWindow
pw = new PopupWindow(layout, 600, 570, true);
// display the popup in the center
pw.showAtLocation(layout, Gravity.CENTER, 0, 0);
RadioGroup radioGroup;
radioGroup = (RadioGroup) findViewById(R.id.radioGroupid);
final String[] tempQtyVar = new String[1];
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId){
case R.id.rbqty30id:
tempQtyVar[0] = "30";
break;
case R.id.rbqty60id:
tempQtyVar[0] = "60";
break;
case R.id.rbqty90id:
tempQtyVar[0] = "90";
break;
case R.id.rbqtycutomid:
tempQtyVar[0] = "120";
break;
}
}
});
Button setQtyBtn = (Button) layout.findViewById(R.id.buttonOkSetQtyid);
setQtyBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ingredientQuantity = tempQtyVar[0];
Toast.makeText(getApplicationContext(),ingredientQuantity,Toast.LENGTH_LONG).show();
pw.dismiss();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
The layout.xml for my pop up window is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:background="#fd050505"
android:padding="30dp"
android:id="#+id/popupElementid">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:id="#+id/relativeLayout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SET QUANTITY"
android:textColor="#84e9e6"
android:textSize="20sp"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:textStyle="bold"
android:id="#+id/popupTitleid"/>
<LinearLayout
android:layout_width="600dp"
android:layout_height="wrap_content"
android:layout_below="#+id/popupTitleid"
android:orientation="horizontal"
android:background="#drawable/btn_rounded_boarder"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp">
<RadioGroup
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/radioGroupid"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:orientation="horizontal"
>
<RadioButton
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text=" 30ml "
android:textColor="#84e9e6"
android:id="#+id/rbqty30id"
android:checked="true" />
<RadioButton
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#84e9e6"
android:text=" 60ml "
android:id="#+id/rbqty60id" />
<RadioButton
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#84e9e6"
android:text=" 90ml "
android:id="#+id/rbqty90id" />
<RadioButton
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#84e9e6"
android:text=" Custom Value "
android:id="#+id/rbqtycutomid"
/>
</RadioGroup>
</LinearLayout>
<LinearLayout
android:layout_width="600dp"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:layout_centerHorizontal="true">
<SeekBar
android:id="#+id/customqtySBid"
android:layout_height="fill_parent"
android:layout_width="600dp"
android:textColor="#84e9e6"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginTop="150dp"
android:paddingBottom="10dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/buttonOkSetQtyid"
android:textColor="#84e9e6"
android:text="OK"
android:background="#drawable/btn_rounded_boarder"
android:layout_marginTop="275dp"/>
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
I tried looking for answer online but didn't really find solution specific to my problem. Please suggest any solutions.
Thanks in advance.
You seem to be inflating the wrong layout. Change the correct layout.xml in
setContentView(R.layout.activity_custom_menu);

hide layout checkbox is checked android

I am trying to simply hide a linear layout if a checkbox is clicked. I have defined function and onClick attribute calls it which is also tested with toast but when I try hiding the layout, it doesn't do anything.
The layout.xml:
<CheckBox
android:id="#+id/cbguest"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.9"
android:onClick="itemClicked"
/>
In MainActivity.java
int[] i = {0};
public void itemClicked(View v) {
LinearLayout layoutguest1 = (LinearLayout) findViewById(R.id.guestlayout);
if (lns[0]%2 == 0) {
Toast.makeText(getApplicationContext(),"Visible", Toast.LENGTH_SHORT).show();
layoutguest1.setVisibility(View.VISIBLE);
lns[0]+=1;
}
if (lns[0]%2 != 0) {
layoutguest1.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(),"Gone", Toast.LENGTH_SHORT).show();
lns[0]+=1;
}
}
**activity_main.xml
put this code in activity_main.xml file**
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.demo.MainActivity" >
<LinearLayout
android:id="#+id/layoutLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="UserName" />
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password" />
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
<CheckBox
android:id="#+id/chkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Hide" />
</RelativeLayout>
**MainActivity.java
put this code in MainActivity.java file**
public class MainActivity extends Activity {
private LinearLayout layoutLogin;
private CheckBox chkBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chkBox = (CheckBox) findViewById(R.id.chkBox);
layoutLogin = (LinearLayout) findViewById(R.id.layoutLogin);
chkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked)
{
// TODO Auto-generated method stub
if(isChecked)
{
layoutLogin.setVisibility(View.GONE);
chkBox.setText("UnHide");
}
else
{
layoutLogin.setVisibility(View.VISIBLE);
chkBox.setText("Hide");
}
}
});
}
}
You should be using onCheckedChangeListener as I don't think it registers as an onClick- but an onCheck.
Android: checkbox listener

Categories

Resources