Checkbox button center android

CheckBox (Флажок)

Компонент CheckBox является флажком, с помощью которого пользователь может отметить (поставить галочку) определённую опцию. Очень часто флажки используются в настройках, когда нужно выборочно выбрать определённые пункты, необходимые для комфортной работы пользователю.

Компонент находится в группе Buttons.

Для управления состояниями флажка используйте методы setChecked() или togglе(). Чтобы узнать текущее состояние флажка, вызовите свойство isChecked.

Для экспериментов воспользуемся программой «Счетчик ворон», которую писали при изучении щелчка кнопки.

Как вы помните, в программе была кнопка и текстовое поле. Добавим ещё два элемента CheckBox, а также четыре текстовые метки TextView. Нам нужно постараться, чтобы элементы были аккуратно сгруппированы. Для этой цели воспользуемся вложенными компоновками LinearLayout. Заодно применим интересный приём — мы не будем использовать текст у флажков CheckBox, а воспользуемся текстовыми метками с разными размерами шрифтов. Верхняя метка с крупным шрифтом будет указывать на основную функциональность флажка, а нижняя метка с мелким шрифтом будет использоваться в качестве своеобразной подсказки, в которой содержится дополнительная информация для пользователя.

На самом деле вы можете попробовать другие способы разметки, не воспринимайте как догму. А мы идём дальше. Флажки в нашем приложении нужны для того, чтобы пользователь мог менять вывод текста в текстовом поле. По желанию, можно выводить текст красным цветом и жирным стилем по отдельности или в совокупности. Для этого нам нужно добавить дополнительные строчки кода в обработчик щелчка кнопки.

Запустите проект и попробуйте снимать и ставить галочки у флажков в разных комбинациях, чтобы увидеть, как меняется текст после щелчка кнопки. Код очень простой — проверяется свойство isChecked. Если галочка у флажка установлена, то свойство возвращает true и мы меняем цвет (красный) или стиль текста (жирный). Если флажок не отмечен, то свойство возвращает false, и мы используем стандартные настройки текста.

Отслеживаем смену состояния флажка

С помощью слушателя-интерфейса OnCheckedChangeListener с его методом onCheckedChanged() можно отслеживать смену состояния флажка.

Собственные стили

Если вы используете стандартный проект, то флажок будет использовать цвета Material Design, в частности цвет colorAccent для фона флажка.

В файле res/values/styles.xml добавим строки:

Свойство colorControlNormal отвечает за прямоугольник в невыбранном состоянии, а colorControlActivated за закрашенный прямоугольник в выбранном состоянии.

Присваиваем созданный стиль атрибуту android:theme:

Теперь цвета флажков изменились.

Собственный вид

Если вас не устраивает стандартный вид элементов CheckBox, то не составит никакого труда реализовать свои представления о дизайне.

В папке res/drawable создаём файл checkbox_selector.xml:

Также необходимо подготовить два изображения для двух состояний флажков — выбран и не выбран. В нашем случае это две звезды — серая и жёлтая.

Осталось прописать селектор в компоненте CheckBox (атрибут android:button):

Готово! Можете запускать проект и проверять работу флажков. Ниже код для реагирования на смену состояния флажков:

AnimatedStateListDrawable. Анимация между переключением состояния

Когда мы создали собственный вид флажка, то переключение происходит сразу без анимации. В API 21 появилась возможность установить анимацию при помощи нового класса AnimatedStateListDrawable.

Создадим как прежде файл для собственного вида флажка.

res/drawable/toggle.xml

Далее нужные два значка. Они сделаны в векторном виде.

res/drawable/toggle_checked.xml

res/drawable/toggle_unchecked.xml

Присвоим созданный вид атрибуту android:button.

Код будет работать на устройствах, которые поддерживают векторную графику (API 14), но анимации не будет. Для анимации создадим альтернативный вариант файла в папке res/drawable-v21.

AnimatedStateListDrawable похож на обычный StateListDrawable, но позволяет указать анимацию перехода между двумя состояниями. Мы также указываем две картинки, но также добавляем элементы transition.

res/drawable-v21/toggle.xml

res/drawable-v21/toggle_unchecked_checked.xml

res/drawable-v21/toggle_checked_unchecked.xml

Если запустить пример на старом устройстве, то никакой анимации не увидим, но код будет работать без ошибок. На новых устройствах анимация будет работать.

Источник

android — центр checkbox в button

У меня есть приведенный ниже код, это checkbox и button на противоположных концах. Я хочу держать его на противоположных концах, но я хочу, чтобы checkbox (вместе с его текстом) приходился на середину высоты button. Как есть , checkbox находится на вершине высоты button

3 ответа

Я хочу знать, как центр управления drag button get’s it’s color by the lock screen wallpaper. Я публикую здесь фотографию, чтобы понять, что button я имею в виду :

У меня есть несколько checkbox и button. Что я должен сделать, чтобы отключить button, если ни один из checkbox не проверен, и включить button, если он проверен?

Используйте это обновленное XML. Я думаю, что вы получите свой результат.

Вы должны использовать это:

Добавьте android:gravity = «center» в макет, который содержит ваши CheckBox и Button. Так просто. Счастливого кодирования 🙂

Читайте также:  Флеш контакта для андроид

Похожие вопросы:

Я пытаюсь узнать больше о функциях checkbox в android. Я хочу, чтобы отобразить значения отмеченных чекбоксов в TextView. В моем коде он показывает все флажки либо true (если установлен), либо false.

У нас есть требование создать button с встроенным в него CheckBox . Попробовав различные варианты, мы нашли вариант иметь CheckBox с внешним видом Button , но этого недостаточно, так как нам нужно.

Мне нужна помощь с заказом button в Android. Я хочу сделать button, который существует из трех компонентов: левая граница, правая граница и центр. Если button растягивается горизонтально, правая и.

Я хочу знать, как центр управления drag button get’s it’s color by the lock screen wallpaper. Я публикую здесь фотографию, чтобы понять, что button я имею в виду :

У меня есть несколько checkbox и button. Что я должен сделать, чтобы отключить button, если ни один из checkbox не проверен, и включить button, если он проверен?

Я долго работал над этой проблемой. Я хочу показать Button, если установлен флажок CheckBox. У меня есть CheckBoxes по количеству столбцов в моем DataBase. И если Checkbox не установлен, я хочу.

Я хочу поместить изображение в центр и текст чуть ниже него в button, я пытался установить android:gravity, но не смог установить его должным образом,вот прикрепленное изображение: ниже приведен мой.

Я объясню это с помощью картинки: Хорошо. Вот как работает CheckBox, когда я устанавливаю гравитацию на ‘center’. Но я хочу поместить его в центр всего объекта, взяв красную область в качестве.

Есть ли простой способ центрировать checkbox с его текстом? Я попробовал установить Gravity = Center , но получилось как на картинке ниже. Я хочу, чтобы checkbox переместился в центр макета, где.

Я пытаюсь добавить атрибут button к моему checkbox в android. Но checkbox скрывается в android 10 устройствах. При удалении атрибута button отображается checkbox. Какова может быть первопричина этой.

Источник

Using Radio Button and Check Box in Android

By now you must be very much familiar with EditText and TextView and various layouts. Let’s move on and learn more about other views like RadioButton and CheckBox .

In this tutorial we are going to design a form where user will have to select one of the options using radio button. There will be some more suggestions and options that the user will have to select using check boxes. Then we will display all the options selected by the user using a Toast on the display screen.

Let’s start with RadioButton and RadioGroup

So let’s begin. Create a new Android Application Project and copy the below content of the XML layout file.

You will see the following output:

Once the layout is done, we will now work on the background logic(backend) of the user interface which will fetch the user selection and display it on the screen using a toast.

So we will require the views that the user will interact with so that we can get the necessary information. Then we need to implement click listener on the Submit button.

Inside the onClickListener() first we have to get the selected radio button id from the RadioGroup. Once we have the id of the selected Radio Button, we can easily fetch the text value of the selected radio button to display it on screen. Let’s implement this. Below we have the MainActivity.java file with all the code.

To get the selected radio button, we have used radioGroup.getCheckedRadioButtonId() method, which returns the id of the selected radio button.

Then to get the text of the selected radio button, we have used getText() method on that selected radio button. The text we receive from this method is converted to String type using the toString() method. Finally, we have displayed the selected option value to the user using a Toast.

Add the above code in the MainActivity.java file and then run your Android Application Project. The result will be similar to the image shown below. Whenever the user selects any option, it will be displayed to the user as a Toast.

It’s Time for CheckBox

Now, it’s time to play with some check boxes. Extend the UI design by copy-pasting the following code after the Button view (with id as btnSubmit) in the layout XML file.

IMPORTANT: For the SUBMIT button we must set this property: android:layout_below=»@+id/cb4″ , to make it appear at the end, as we have added checkboxes to our existing form now.

Checkboxes are used to display multiple options to the user, and the user is allowed to select one or more out of those options. All check boxes have the checked property set to false initially.

To get user selected check box values from the UI when the user clicks on the SUBMIT button, we will use the isChecked() to check if the check box was selected or not.

Читайте также:  Топ блютуз наушников 2021 для андроид

So we will have to make a few changes in our MainActivity.java class file. First we will have to create instances for the check boxes by using findViewById() method. For this, we also have to declare global variables of CheckBox type.

To declare the global variable,

Then, inside the onCreate() method, store the CheckBox view from the XML into Java using findViewById() method.

Once we have all the instances ready, all we have to do is check which checkboxes are selected by the user when the user clicks on the SUBMIT button. This is done by using isChecked() method of the CheckBox view, as we already mentioned.

isChecked() method returns true if a checkbox is checked otherwise it returns false. Selected checkboxes values are retrieved and added to one string( checkBoxChoices ) using getText() and toString() methods. At last, a Toast is used to display all the selected options.

So update the existing code inside the OnClick() method of the SUBMIT button with the following code:

When you run the app, you will see that out all the radio buttons, you are able to select only one radio button while in case of check boxes, you can select any number of them. That is how radio buttons and checkboxes work. So this is all about implementation of RadioButton and CheckBox in Android Application Development.

Источник

Android CheckBox with Examples

In android, CheckBox is a two-states button that can be either checked (ON) or unchecked (OFF) and it will allow users to toggle between the two states (ON / OFF) based on the requirements.

Generally, we can use multiple CheckBox controls in android application to allow users to select one or more options from the set of values.

Following is the pictorial representation of using CheckBox control in android applications.

By default, the android CheckBox will be in the OFF (Unchecked) state. We can change the default state of CheckBox by using android:checked attribute.

In case, if we want to change the state of CheckBox to ON (Checked), then we need to set android:checked = “true” in our XML layout file.

In android, we can create CheckBox control in two ways either in the XML layout file or create it in the Activity file programmatically.

Create CheckBox in XML Layout File

Following is the sample way to define CheckBox control in XML layout file in android application.

If you observe above code snippet, here we defined CheckBox control and setting CheckBox state ON using android:checked attribute in xml layout file.

Create CheckBox Control in Activity File

In android, we can create CheckBox control programmatically in activity file based on our requirements.

Following is the example of creating a CheckBox control dynamically in an activity file.

LinearLayout layout = (LinearLayout)findViewById(R.id. l_layout );
CheckBox cb = new CheckBox( this );
cb.setText( «Tutlane» );
cb.setChecked( true );
layout.addView(cb);

This is how we can define CheckBox in XML layout file or programmatically in activity file based on our requirements.

Handle Android CheckBox Click Events

Generally, whenever the user clicks on CheckBox to Select or Deselect the CheckBox object will receive an on-click event.

In android, we can define the CheckBox click event in two ways either in the XML layout file or create it in the Activity file programmatically.

Define CheckBox Click Event in XML Layout File

We can define a click event handler for button by adding the android:onClick attribute to the element in our XML layout file.

The value of android:onClick attribute must be the name of method which we need to call in response to a click event and the Activity file which hosting XML layout must implement the corresponding method.

Following is the example of defining a CheckBox click event using android:onClick attribute in XML layout file.

android :onClick= «onCheckBoxClick»/>
LinearLayout >

In Activity that hosts our XML layout file, we need to implement click event method like as shown below.

public void onCheckboxClicked(View view) <
// Is the view now checked?
boolean checked = ((CheckBox) view).isChecked();
// Check which checkbox was clicked
switch (view.getId()) <
case R.id.chk1:
if (checked)
// Do your coding
else
// Do your coding

break ;
// Perform your logic
>
>

Define CheckBox Click Event in Activity File

In android, we can define CheckBox click event programmatically in Activity file rather than XML layout file.

To define checkbox click event programmatically, create View.OnClickListener object and assign it to the button by calling setOnClickListener(View.OnClickListener) like as shown below.

This is how we can handle CheckBox click events in android applications based on our requirements.

Читайте также:  Поисковая система яндекс для андроида

Android CheckBox Control Attributes

The following are some of the commonly used attributes related to CheckBox control in android applications.

Attribute Description
android:id It is used to uniquely identify the control
android:checked It is used to specify the current state of checkbox
android:gravity It is used to specify how to align the text like left, right, center, top, etc.
android:text It is used to set the text for a checkbox.
android:textColor It is used to change the color of text.
android:textSize It is used to specify the size of text.
android:textStyle It is used to change the style (bold, italic, bolditalic) of text.
android:background It is used to set the background color for checkbox control.
android:padding It is used to set the padding from left, right, top and bottom.
android:onClick It’s the name of the method to invoke when the checkbox clicked.
android:visibility It is used to control the visibility of control.

Android CheckBox Control Example

Following is the example of defining multiple CheckBox controls and one Button control in LinearLayout to get the selected values of CheckBox controls when we click on Button in the android application.

Create a new android application using android studio and give names as CheckBoxExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml

xml version= «1.0» encoding= «utf-8» ?>
LinearLayout xmlns: android = «http://schemas.android.com/apk/res/android»
android :orientation= «vertical» android :layout_width= «match_parent»
android :layout_height= «match_parent» >
CheckBox
android :id= «@+id/chkJava»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :padding= «10dp»
android :layout_marginTop= «150dp»
android :layout_marginLeft= «100dp»
android :text= «Java»
android :onClick= «onCheckboxClicked»/>
CheckBox
android :id= «@+id/chkPython»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :padding= «10dp»
android :layout_marginLeft= «100dp»
android :text= «Python»
android :onClick= «onCheckboxClicked»/>
CheckBox
android :id= «@+id/chkAndroid»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :padding= «10dp»
android :layout_marginLeft= «100dp»
android :text= «Android»
android :onClick= «onCheckboxClicked»/>
CheckBox
android :id= «@+id/chkAngular»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :padding= «10dp»
android :layout_marginLeft= «100dp»
android :text= «AngularJS»
android :onClick= «onCheckboxClicked»/>
Button
android :id= «@+id/getBtn»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_marginLeft= «100dp»
android :text= «Get Details»/>
LinearLayout >

If you observe above code we created a multiple CheckBox controls and one Button control in XML Layout file.

Once we are done with the creation of layout with required controls, we need to load the XML layout resource from our activity onCreate() callback method, for that open main activity file MainActivity.java from \java\com.tutlane.checkboxexample path and write the code like as shown below.

MainActivity.java

package com.tutlane.checkboxexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity <
CheckBox android , java , angular , python ;
@Override
protected void onCreate(Bundle savedInstanceState) <
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
android = (CheckBox)findViewById(R.id. chkAndroid );
angular = (CheckBox)findViewById(R.id. chkAngular );
java = (CheckBox)findViewById(R.id. chkJava );
python = (CheckBox)findViewById(R.id. chkPython );
Button btn = (Button)findViewById(R.id. getBtn );
btn.setOnClickListener( new View.OnClickListener() <
@Override
public void onClick(View v) <
String result = «Selected Courses» ;
if ( android .isChecked()) <
result += » \n Android» ;
>
if ( angular .isChecked()) <
result += » \n AngularJS» ;
>
if ( java .isChecked()) <
result += » \n Java» ;
>
if ( python .isChecked()) <
result += » \n Python» ;
>
Toast.makeText(getApplicationContext(), result, Toast. LENGTH_SHORT ).show();
>
>);
>
public void onCheckboxClicked(View view) <
boolean checked = ((CheckBox) view).isChecked();
String str= «» ;
// Check which checkbox was clicked
switch (view.getId()) <
case R.id. chkAndroid :
str = checked? «Android Selected» : «Android Deselected» ;
break ;
case R.id. chkAngular :
str = checked? «AngularJS Selected» : «AngularJS Deselected» ;
break ;
case R.id. chkJava :
str = checked? «Java Selected» : «Java Deselected» ;
break ;
case R.id. chkPython :
str = checked? «Python Selected» : «Python Deselected» ;
break ;
>
Toast.makeText(getApplicationContext(), str, Toast. LENGTH_SHORT ).show();
>
>

If you observe above code we are calling our layout using setContentView method in the form of R.layout.layout_file_name in our activity file. Here our xml file name is activity_main.xml so we used file name activity_main and we are getting the status of CheckBox controls when they Select / Deselect and getting the selected CheckBox control values on Button click.

Generally, during the launch of our activity, onCreate() callback method will be called by android framework to get the required layout for an activity.

Output of Android CheckBox Example

When we execute the above example using the android virtual device (AVD) we will get a result like as shown below.

If you observe above result, we are able to get the status of checkboxes while selecting / deselecting and getting all the selected CheckBox values on button click.

This is how we can use CheckBox control in android applications to allow users to select one or more options based on our requirements.

Источник

Оцените статью