Android mancj.MaterialSearchBar:使用反射来覆盖和更改一些API布局和小部件,字体系列,粗体和填充

时间:2018-10-06 18:45:48

标签: android android-widget android-xml android-library

我正在使用https://github.com/mancj/MaterialSearchBar来设置带有菜单汉堡的搜索栏。 我无法更改API。

这是我获得的:

enter image description here

问题

如何...:

  1. 减少文本的左空白吗?

  2. 更改后者的字体吗?

  3. 最后禁用粗体吗?

注意:这些问题由其他部分在 根据文档 的下一部分中解决。

根据文档

mt_aBCD是XML属性,可让我们自定义搜索栏。但是,以上都不存在。它们相当于Java(setABCD都不是)。

顺便说一下,请注意,该API的Github活动并不多。我不能用另一个替换后者。您会给我什么解决方案?

  1. 我是否应该更改此API中的某些内容(已授权并合法)? (如何?)
  2. 我可以覆盖样式吗?等等(如何?)
  3. 其他?

我的实现

我编辑了构建文件,然后仅在XML布局中添加了搜索栏:

    <com.mancj.materialsearchbar.MaterialSearchBar
    android:id="@+id/material_search_bar"
    style="@style/MaterialSearchBarLight"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_marginEnd="15dp"
    android:layout_marginStart="15dp"
    android:layout_marginTop="15dp"
    app:layout_constraintBottom_toBottomOf="@+id/toolbar"
    app:layout_constraintEnd_toEndOf="@+id/toolbar"
    app:layout_constraintStart_toStartOf="@+id/toolbar"
    app:layout_constraintTop_toTopOf="@+id/toolbar"
    app:mt_maxSuggestionsCount="10"
    app:mt_navIconEnabled="true"
    app:mt_placeholder="@string/search_placeholder" />

2 个答案:

答案 0 :(得分:3)

第一时刻:

此库不支持字体家族。这个问题存在于github块“ 问题

enter image description here


第二时刻:

为您的文本填充不支持“赞”和“禁用粗体”


但是您可以通过反射解决问题

这不是最好的解决方案,但它可行

    searchBar = (MaterialSearchBar) findViewById(R.id.searchBar);
    try {
        final Field placeHolder = searchBar.getClass().getDeclaredField("placeHolder");
        placeHolder.setAccessible(true);
        final TextView textView = (TextView) placeHolder.get(searchBar);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);

        // fix trouble number 1 paddingLeft
        textView.setPadding(0, 0, 0, 0);
        final RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) textView.getLayoutParams();
        layoutParams.setMargins(0,0,0,0);

        //fix trouble number 2 font-family and number 3 Finally, disable boldness?
        Typeface typeface = Typeface.createFromAsset(getAssets(), getString(R.string.roboto_medium));
        //<string name="roboto_medium">fonts/Roboto-Medium.ttf</string>
        textView.setTypeface(typeface);

        textView.setText("Hello World!");
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

enter image description here

汉堡菜单的大小为48dp,不是空白(DeclaredField = navIcon) enter image description here


最后一个变种

在您的项目中复制此库并编辑所有所需的内容。
您可以这样做,因为该库使用了license MIT 最重要的是指定原始作者

答案 1 :(得分:1)

我用这个解决了同样的事情:

Typeface typeface = ResourcesCompat.getFont(Objects.requireNonNull(getContext()), R.font.XXX);
placeHolder = findViewById(R.id.mt_placeholder);
placeHolder.setTypeface(typeface);