简体   繁体   English

在 android Spinner 中删除间距或填充

[英]Remove Spacing or Padding in android Spinner

I'm using android spinner and edittext from support lib v21.我正在使用 support lib v21 中的 android spinner 和 edittext。 I would like to align text to left the same like edittext as shown in figure.我想将文本对齐到如图所示的 edittext 一样。 But, deafult spinner include spacing or padding.但是,默认的微调器包括间距或填充。 So, I would like to remove it to align text to left.所以,我想删除它以将文本左对齐。 Please help how to remove it.请帮助如何删除它。

在此处输入图片说明

In your SpinnerAdapter:在您的 SpinnerAdapter 中:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        view.setPadding(0, view.getPaddingTop(), view.getPaddingRight(), view.getPaddingBottom());
        return view;
}

This array adapter removes left padding in Android Spinner.此数组适配器删除 Android Spinner 中的左填充。

Kotlin version:科特林版本:

open class NoPaddingArrayAdapter<T>(context: Context, layoutId: Int, items: List<T>?) : ArrayAdapter<T>(context, layoutId, items) {

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? {
        val view = super.getView(position, convertView, parent)
        view.setPadding(0,view.paddingTop,view.paddingRight,view.paddingBottom)
        return view
    }
}

The layout for TextView that is displayed in your Spinner comes from your SpinnerAdapter , which provides 2 methods:显示在Spinner TextView布局来自SpinnerAdapter ,它提供了 2 个方法:

  • getView(position, convertView, parent) : returns View for collapsed state, you can override this to return different layouts for different selected item getView(position, convertView, parent) :返回折叠状态的视图,您可以覆盖它以返回不同选定项的不同布局
  • getDropdownView(position, convertView, parent) : return View for each dropdown item in expanded state (after you click Spinner to open popup/dialog for selection) getDropdownView(position, convertView, parent) : 为每个处于展开状态的下拉项返回 View(点击 Spinner 打开弹出/对话框进行选择后)

In your case you should override your SpinnerAdapter.getView(position, convertView, parent) and inflate the layout with padding/spacing of your choice.在您的情况下,您应该覆盖SpinnerAdapter.getView(position, convertView, parent)并使用您选择的填充/间距来膨胀布局。

For example:例如:

spinner.setAdapter(new MyAdapter());

MyAdapter.java我的适配器

class MyAdapter implements SpinnerAdapter {
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.spinner_item, parent, false);
        }
        // bind your data here
        return convertView;
    }
    // other implementation
}

res/layout/spinner_item.xml res/layout/spinner_item.xml

<!-- set padding margin whatever here -->
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

You can also conveniently use one of the framework provided SpinnerAdapter indirect subclasses ( ArrayAdapter<T>, BaseAdapter, CursorAdapter, ResourceCursorAdapter, SimpleAdapter, SimpleCursorAdapter, ThemedSpinnerAdapter ), just make sure to supply the correct layout that would be used by getView() method.您还可以方便地使用框架提供的SpinnerAdapter间接子类之一ArrayAdapter<T>, BaseAdapter, CursorAdapter, ResourceCursorAdapter, SimpleAdapter, SimpleCursorAdapter, ThemedSpinnerAdapter ),只需确保提供getView()方法将使用的正确布局。

You can also remove the padding of spinner in xml也可以去掉xml中spinner的padding

Only need to set padding to 0dp.只需要将填充设置为 0dp。

    <Spinner
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="left"
        android:padding="0dp"     
        android:id="@+id/my_spinner">

Try below code to do so.尝试下面的代码来做到这一点。 Change style attribute in your spinner list item layout to textViewStyle as below将微调列表项布局中的样式属性更改为 textViewStyle,如下所示

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    style="?android:attr/textViewStyle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:singleLine="false"
    android:textAlignment="inherit"
    android:textAppearance="?android:attr/textAppearanceMedium" />

Try this,尝试这个,

  1. Create custom layout(as you need) for spinner row.为微调行创建自定义布局(根据需要)。

  2. inflate the layout when you set the data adapter to the spinner.将数据适配器设置为微调器时膨胀布局。

If yo don't want to mess in Java Code and have it in styles如果您不想弄乱 Java 代码并使其具有样式

Search for this file (Cmd+Shift+O) abc_spinner_textfield_background_material.xml搜索此文件 (Cmd+Shift+O) abc_spinner_textfield_background_material.xml

and copy to your project.并复制到您的项目中。 Remove all inset values from root element and refer the file as background of your spinner.从根元素中删除所有插入值,并将该文件作为微调器的背景。

In my case it looks like this ( drawable/spinner_background.xml )在我的情况下它看起来像这样( drawable/spinner_background.xml

<inset xmlns:android="http://schemas.android.com/apk/res/android">
    <selector>
        <item
            android:state_checked="false"
            android:state_pressed="false">
            <layer-list>
                <item android:drawable="@drawable/abc_textfield_default_mtrl_alpha" />
                <item android:drawable="@drawable/abc_spinner_mtrl_am_alpha" />
            </layer-list>
        </item>
        <item>
            <layer-list>
                <item android:drawable="@drawable/abc_textfield_activated_mtrl_alpha" />
                <item android:drawable="@drawable/abc_spinner_mtrl_am_alpha" />
            </layer-list>
        </item>
    </selector>
</inset>

and in my styles.xml I use it this way在我的styles.xml中我这样使用它

<style name="DxSpinner" parent="@style/Widget.AppCompat.Spinner.Underlined">
    <item name="android:background">@drawable/spinner_background</item>
</style>

This Kotlin code is a little bit more succinct than the getView override in another answer.这个 Kotlin 代码比另一个答案中的getView覆盖更简洁一些。 It makes it a bit more clear in fewer lines that it is mostly just doing what super does, except that it also overrides setPadding for the left value.它在更少的行中更清楚地表明它主要只是在做 super 所做的事情,除了它还覆盖了左值的setPadding

override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
    return super.getView(position, convertView, parent).apply {
        setPadding(0, paddingTop, paddingRight, paddingBottom)
    }
}

Here is my full fragment code that uses a data binding object for the complete spinner array adapter override, which also does a selected item and an alternating background color in getDropDownView :这是我的完整片段代码,它使用数据绑定对象进行完整的微调数组适配器覆盖,它还在getDropDownView中执行选定项目和交替背景颜色:

binding.editSpinner.apply {
    this.context ?: return@apply
    this.adapter = object : ArrayAdapter<Any>(
        requireContext(),
        android.R.layout.simple_spinner_dropdown_item,
        SpinnerTypeValues.values().map { it.text }
    ) {
        override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
            return super.getDropDownView(position, convertView, parent).also {
                when {
                    position == this@apply.selectedItemPosition -> it.setBackgroundColor( Color.rgb(245, 212, 119) )
                    position % 2 == 0 -> it.setBackgroundColor(Color.rgb(240, 240, 240))
                    else -> it.setBackgroundColor(Color.rgb(214, 235, 189))
                }
            }
        }
        override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
            return super.getView(position, convertView, parent).apply {
                setPadding(0, paddingTop, paddingRight, paddingBottom)
            }
        }
    }
    this.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
        override fun onNothingSelected(parent: AdapterView<*>?) {}
        override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
            viewModel.saveSpinnerSelection(position)
        }
    }
}

I just hit this issue as well.我也刚碰到这个问题。 I was able to solve it with adjusting margin actually instead of padding, so setting android:marginStart="0dp" to the spinner item.我能够通过实际调整边距而不是填充来解决它,因此将 android:marginStart="0dp" 设置为微调项。

在你的 onViewCreated()

spinner.post { spinner.setPadding(0,0,0,0) } 

Maybe this is the simplest way and also it just work.也许这是最简单的方法,而且它也很管用。 To decrease left padding of Spinner , you can use set padding left to minus so it will move to the left.要减少Spinner左填充,您可以使用 set padding left 为减号,以便它向左移动。 For example android:layout_marginLeft="-8dp" This is not a best practice, only a simple hack.例如android:layout_marginLeft="-8dp"这不是最佳实践,只是一个简单的技巧。 Here is a code sample:这是一个代码示例:

<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_marginLeft="-8dp"
android:entries="@array/arr_tipe_kendaraan"
android:gravity="left"
android:paddingTop="14dp"
android:paddingBottom="8dp"
android:prompt="@string/action_sign_in"
android:spinnerMode="dialog" />

Hope this helps.希望这可以帮助。

  1. Create a text-view layout view_spinner_text_view.xml:创建一个文本视图布局 view_spinner_text_view.xml:

     <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" />
  2. Create the adapter by providing the above layout:通过提供上述布局创建适配器:

     ArrayAdapter.createFromResource( context, R.array.my_values, R.layout.view_spinner_text_view // <-- this is for the spinner itself ).also { adapter -> adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item // <-- this is for the dropped-down items (you can customize this one as well) ) spinner.adapter = adapter }

Replace android.R.layout.simple_spinner_item layout from code by new spinner_item layout用新的 spinner_item 布局替换代码中的 android.R.layout.simple_spinner_item 布局

Code for spinner_item: spinner_item 的代码:

<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="@dimen/primaryText"
    android:textColor="@color/black"
    android:textStyle="bold"/>

This will remove an extra margin and you can style it according to your requirement.Thanks.这将删除额外的边距,您可以根据您的要求设置样式。谢谢。

This Work for me这对我有用

Spinner spn = (Spinner) findViewById(R.id.spn);

spn.setPadding(0, spn.getPaddingTop(), spn.getPaddingRight(), spn.getPaddingBottom());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM