以编程方式创建 UI 时出现 appcompat-v7:22.0.0 主题问题

appcompat-v7:22.0.0 theme issue when creating UI programmatically

更新到 appcompat-v7:22 后,我 运行 遇到了严重的主题问题。 appcompat-v7:21

不会出现下述问题

我 activity 有一个静态添加的片段。片段视图仅以编程方式创建(没有布局被放大)。最终 activity 视图包含 2 个按钮:一个直接在 Activity 布局中创建,第二个通过 Fragment 以编程方式添加。 第二个按钮看起来应该与第一个按钮相似,因为没有分配自定义样式或属性值:

应用主题扩展 Theme.AppCompat.NoActionBar

Activity布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:text="Super Button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <fragment
        android:id="@+id/myfragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:name="com.jskierbi.appcompat22test.MainFragment" />

</LinearLayout>

片段class:

public class MainFragment extends Fragment {

    @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        LinearLayout layout = new LinearLayout(getActivity());
        layout.setOrientation(LinearLayout.VERTICAL);
        Button btn = new Button(getActivity());
        btn.setText("Click me!");
        layout.addView(btn);
        return layout;
    }
}

我已将此问题分离到此处的新项目中:https://github.com/jskierbi/appcompat-v7-22-bug

这是一个错误还是我遗漏了什么? 是否可以为此制定解决方法?

编辑

这不是错误。 <Button> 布局中定义的小部件膨胀为视图层次结构中的 TintButton 对象。可能的解决方法是在代码中创建 TintButton 而不是 Button。 警告 TintButton 位于内部包中,因此不应在生产代码中使用。

据我所知,v21 不支持根据 material 准则自动设置按钮样式。我现在假设在运行时创建的按钮没有样式,是的,可能被认为是一个错误。

想到的可能解决方法(现在无法测试)是调用,而不是 new Button()new TintButton(),其中 TintButton 是支持中定义的 class库,假定为 Button.

的 material 样式版本

我觉得应该是android.support.v7.internal.widget.TintButton.

问题已于 4 月 22 日通过 appcompat rev 22.1 修复。现在您可以使用普通按钮或新的 AppCompatButton See here