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

Android mancj.MaterialSearchBar: Using reflection to override and change some API layout and widgets, font-family, boldness and padding

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

这是我得到的:

问题

如何...:

  1. 减少文本的左填充?

  2. 更改后者的字体系列?

  3. 最后,禁用加粗?

注意:这些问题在下一节由其他人完成,根据文档

根据文档

mt_aBCD 是允许我们自定义搜索栏的 XML 属性。然而,以上这些并不存在。他们的 Java 等价物(setABCD 两者都不是)。

顺便说一句,请注意 Github activity 并不多 API。我不能用另一个代替后者。你会给我什么解决方案?

  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" />

第一时间:

这个库不支持 font-familly。此问题存在于 github 版块“ISSUE


第二个时刻:

padding for you text 不支持 like 和“disable boldness”


但是你可以用反射来解决你的问题

这不是最好的解决方案,但它有效

    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();
    }

汉堡菜单的大小为 48dp,它不是边距(DeclaredField = navIcon)


最后一个变体

将此库复制到您的项目中,并根据需要进行编辑。
你可以做到,因为这个库使用了 license MIT 最重要的是注明原作者

我用这个解决了同样的问题:

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