以编程方式创建具有某种样式的ImageView

Mac*_*rse 5 android

我想以编程方式执行此操作:

<ImageView style="@style/TitleBarSeparator" />
Run Code Online (Sandbox Code Playgroud)

在哪里TitleBarSeparator:

<style name="TitleBarSeparator">
    <item name="android:layout_width">1px</item>
    <item name="android:layout_height">fill_parent</item>
    <item name="android:background">@color/title_separator</item>
</style>
Run Code Online (Sandbox Code Playgroud)

我试过了:

new ImageView(getContext(), null, R.style.TitleBarSeparator);
Run Code Online (Sandbox Code Playgroud)

但它不起作用.我猜错误来自传递null,AttributeSet但我不完全确定.

Mac*_*rse 0

我找到了解决它的方法。

View v = new ImageView(getContext());
v.setLayoutParams(new LayoutParams(1, LayoutParams.FILL_PARENT));
v.setBackgroundColor(getContext().getResources().getColor(R.color.title_separator));
Run Code Online (Sandbox Code Playgroud)

尽管如此,我还是希望有一种方法来设置样式。