Android switch track width

Как изменить размер виджета Switch

В Ice Cream Sandwich был представлен виджет Switch, который отображает слайдер On Off.

Я добавил переключатель, как это:

Drawables следа и большого пальца руки 9 изображений заплаты которые должны масштабировать к всем возможным размерам.
Я надеялся, что коммутатор будет масштабироваться до максимального размера внутри заданных границ, но кажется, что drawables просто центрированы внутри поставляемого пространства.

Можно ли увеличить размер переключателя, чтобы он казался больше?

5 ответов

Я занимался похожей проблемой сегодня, и я обнаружил, что, начиная с Jelly Bean, вы можете использовать setSwitchMinWidth(width); , чтобы установить минимальную ширину полного переключателя. Я также понял, однако, что если ваши тексты слишком большие, виджет просто отрезан в левой части. Изменение отступа текста по умолчанию на большом пальце может пригодиться здесь, С setThumbTextPadding(num); вы можете изменить это.

Единственная проблема-и это блокатор на самом деле-я споткнулся до сих пор, что нужно, конечно, расширить переключатель в соответствии с размером родительского контейнера. Для этого я завернул коммутатор в пользовательский линейный макет (который также предоставляет резервный вариант для API :

К сожалению — по какой-то глупой причине-виджет переключателя не реагирует на это. Я пытался сделать это в OnLayoutChangeListener без успеха либо. В идеале, текущий размер коммутатора также должен быть известен в этом состоянии, и я хотел «распределить» свободное пространство для заполнения, как это:

но sw.getWidth() все равно возвращает 0 in onSizeChanged() , вероятно, потому, что он все еще не выложен должным образом. Да, мы почти на месте… если вы наткнетесь на что-то, дайте мне знать 🙂

Я думаю, что я, наконец, понял это:

  1. Размер подписи переключателя проконтролирован мимо
  2. Переключатель thumb размер текста контролируется . Приготовьте свой собственный стиль. Этот стиль важен, потому что он управляет общей шириной большого пальца (подробнее об этом позже).
  3. Общая высота переключателя проконтролирована мимо . Вы использовали девятый патч, и я подозреваю, что именно поэтому у вас возникли проблемы. Я использовал и был успешным.
  4. Высота drawable большого пальца руки отрегулирована для того чтобы соответствовать высоте следа. Высота рисуемого большого пальца важна только для формы большого пальца. Это не влияет на высоту переключателя.

Итак, вот что я нашел:

  1. Используйте . drawables как для большого пальца руки переключателя, так и для следа переключателя.
  2. Ширина обоих drawables безвозвратна. Я установил свой в » 0dp»
  3. Высота дорожки определяет общую высоту переключателя.
  4. Самая длинная строка android:textOff or android:textOn определяет ширину большого пальца. Это определяет ширину всего коммутатора. Ширина переключателя всегда в два раза больше ширины большого пальца.
  5. Если ширина текста большого пальца меньше высоты дорожки,форма большого пальца будет уменьшена. Это может исказить форму большого пальца. Если это происходит, добавьте пробелы, чтобы увеличить ширину текста» off» или «on», пока он не станет по крайней мере таким же широким, как ваш трек.

Этого достаточно, чтобы, по крайней мере, начать проектирование переключателей нужного размера и формы. Дайте мне знать, если выясните что-нибудь еще.

Приведенный выше ответ верен. вот небольшой пример, как изменить ширину переключателя с помощью формы drawable
Надеюсь, это кому-то поможет..

1) Используйте цвет ur для большого пальца (color_thumb.XML)

Читайте также:  Необычные звуки уведомлений для андроид

2) серый цвет для трека (gray_track.XML)

3) селектор для большого пальца (thumb.XML)

4) селектор для трека (track.XML)

и, наконец, в switch

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

Использование свойства scale для изменения размера работало на меня.

Добавьте эти строки в тег в xml-файле.

Вы можете изменить значение масштаба согласно вашей потребности. Здесь значение 2 делает его двойным в размере, аналогично значение 0.5 делает его половиной в размере.

Источник

Android switch track width

September 19, 2017

This post shows how to use android switch button, apply material styles, create custom styles, create custom switch button and how to handle switch button click events.

Android Switch XML Element

Android Switch Properties

Some of the important switch properties are textAppearance, textColor, track, thumb, switchTextAppearance, textOn, testOff, background, and showText.

Property thumb is used to set a drawable that switches back and forth, property track is used for setting a drawable as track for switch thumb, textOn and textOff are used to set text to be displayed when switch is in on or off state, textswitchTextAppearance is used to set style for switch text, and showText is used to indicate whether to show switch text or not.

Android Switch Material Style

Android system provides many material themes. When application level theme is set to one of the material themes, android switch will be displayed applying default switch material theme of the application theme used in the application. Below screen shot shows switch button in both on and off states when application theme is set to Theme.AppCompat.

Android Switch Button Custom Style Application Level

Application level themes can be customized by setting properties to custom values. If you customize properties related to UI controls, the changes will be applied to all UI controls and throughout the application. To change switch text color and switch button color, you need to set textColorPrimaryDisableOnly and colorAccent properties to custom values.

Below theme is an example of custom application theme added to res/values/styles.xml file. You can apply it to an application by setting theme attribute of application element in mainifest xml file.

Below screen shot shows switch button after application theme is set to custom material theme defined above.

Android Switch Custom Style Individual

If you want to change switch style only in a particular section of your application, then define custom switch widget style by inheriting Widget.AppCompat.CompoundButton.Switch as shown below and apply it to switch elements using theme attribute.

Switch attribute colorControlActivated can be used to set track and thumb color when switch is active and colorForeground can be used to set track color when switch is in normal state.

You can use thumbTint and trackTint properties to change color of thumb and track. Applying colors to track and thumb using selector xml allows you to apply different colors for different states, see custom switch section.

Android Switch Event Listener

Switch on and off events or switch drag event can be handled in two ways. One way of handling switch click event is by defining a method in your activity or fragment with View as input parameter and setting it as value for onClick attribute of Switch in layout xml as shown below.

Second way of handling switch on/off event is by defining OnCheckedChangeListener and adding it to switch button by using setOnCheckedChangeListener method.

Custom Switch Button

Android switch with custom track

You can customize android switch track by defining a drawable xml resource as shown below. You need to save it in res/drawable folder, our example file name switch_track_custom.xml, and apply it to switch by using track attribute.

Читайте также:  Как заблокировать смс рассылки андроид

Below xml, used as switch_color in the above drawable, is color selector for track. Color is applied based on the state of switch. This file needs to be saved in res/color folder.

Below xml shows applying the custom track drawable to Switch.

Output of custom track of switch.

Android switch with custom thumb

Android switch thumb can be customized by using material icon and defining drawable xml resource.

To do that, first download one of the android material icons which you want to use in your application or use any other image you may have and save it in res/drawable folder.

Then define drawable xml resource as shown below in res/drawable folder, our example file name is switch_thumb_custom.xml. This xml uses the above downloaded icon, defines shape and sets colors. To apply this to a switch, set its thumb attribute to the drawable xml.

In the above xml switchTrackNormal and switchThumbBgActive are colors defined in res/values/colors.xml

Below color selector xml saved as switch_color.xml is used in the custom thumb drawable xml defined above.

Below switch element in layout xml uses above custom switch thumb and switch track.

With switch button track customization explained from above section and switch button thumb customization explained in this section, the custom switch button will appear as shown below in normal and active states.

About

Android app development tutorials and web app development tutorials with programming examples and code samples.

Источник

How to make Custom Switch in Android?

Hello World, Today we are going to make a custom switch. Why? Because the default one looks so boring and ugly. Why we use a switch? As the name suggests, the switch is used to trigger the value either it is on, or it is off. Let’s see, how our custom switch will look at the end of the tutorial.

In the above gif, there are 3 switches. The First one is the default one and the second and third are our custom switches. To make these custom switches we need to follow certain steps are as follows:

Step 1. Add Switch to Activity Layout

First. we need to add the switch to our layout XML file. We will add SwitchCompat to the layout.

Look at the below code for better understanding.

In the above code, things to be noticed are app:track and android:thumb attributes.

The track is the horizontal container where our thumb or round shape view is placed and the thumb is, as I told you before, is the round shape where we will add an image on top of it.

Step 2. Make Custom Track for Switch

To make our custom track we need to make a drawable file and set the root element as a selector. So click on the drawable folder and make a new file and name it as track.

In our track.xml we write this code for making the custom track.

In the above code, we made two items in the selector where the first item represents the state when the switch is off or not checked and the second item represents the state when the switch is on or checked.

In the first item, we made a shape of a rectangle and fill white color with having corner radius with a grey color stroke or outline and in the second item the only difference is filled color will be our accent color and stroke will be removed but the corner radius will be the same.

Now let’s make our thumb part where we will add images on the thumb.

Step 3. Make Custom Thumb with Image.

To make custom thumb for the switch, create a drawable file in a drawable folder and name it as the thumb.

Читайте также:  При покупке нового смартфона как перенести все данные со старого андроида

In our thumb.xml file, we will write the below code.

as track.xml here we also have the root element as a selector and have the same item tags but this time we set drawable in the attribute. These drawable are our drawable file where we will add images. Let’s add our vector icons to use in thumb drawable.

Add images for thumb

Right-click on drawable then click on new then select vector assets and then choose your icon from clip art. for demo purpose we are selecting notification on and off icon.

After adding the icons, we need to make drawable files for custom thumb off and one for the thumb on which will be add in thumb.xml as drawable.

Let’s make the first file in the drawable for thumb off and set an image to the thumb. Check the below code.

If you noticed, we are using the layer-list as the root element and in the child, we have 2 items.

The first item is our oval (round) shape of the thumb with the size and background color and the second item is our image drawable with 12dp padding from the top, bottom, left, and right.

So this was for when the switch is off our custom thumb will look like this now its turn for thumb true when the switch is on.

Create a new file with the name switch_thumb_true and the code will be like below.

Like thumb false, this code is similar to it but the differences are we added the stroke to the round shape and of course change the image drawable.

Now we have made the all necessary files now its time to run our app and your custom switch is ready. Tada.

This switch is our middle one if you want to make track height small then you need to do some extra work. Keep reading.

How to make track height smaller than the thumb.

To read further article check here: Custom Switch in Android

Источник

How to change Width of Android’s Switch track?

Posted by: admin February 24, 2018 Leave a comment

I’m going crazy with this tiny problem. I have a ‘switch’ Form widget, but no matter how much I try, I cannot make it narrower. Even if I have one character instead of ‘ON’ or ‘OFF’, the size of switch remains the same. The ‘thumb’ becomes small, but it has to be dragged over the same distance as before. Changing the ‘layout_width’ to a smaller value simply cuts off the remaining track. ‘minWidth’ doesnt seem to do anything.

Anybody knows how I can do this? Ideally I want just an empty thumb and I’ll colour code both thumb to know which is which.

I am gettin this:

but I want something like this:

set your desired width of switch in this attribute.

Here is my solution. I removed the texts, set the padding of the track and define the switchMinWidth prop. This is my xml:

Hope it helps somebody.

You should use android:track instead of android:thumb .

android – How do I display a CalendarView in an AlertDialog?

Questions: I’m trying to display the CalendarView in an Alert Dialog, but all that shows up is the month/year and the days of the week. These are the contents of the layout file:

How do I convert a PSD design to Android xml?

Questions: Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers. Want to improve this question? Update the question so it’s on-topic for Stack Over.

Источник

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