我正在尝试在我的 Android 项目中创建一些辅助方法 - 设置带有轮廓的背景的方法。我想方法接受不同类型的对象(最小是不同的布局)并在它们上调用 setBackground() 。我的代码:
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
private static <I> void setBackgroundOutlined(Context context,
I item,
String backgroundColor,
String outlineColor, int outlineThickness,
Boolean setStatesPressed) {
GradientDrawable shapeDrawable = new GradientDrawable();
shapeDrawable.setStroke(CF.floatToPixels(context, outlineThickness),
Color.parseColor(outlineColor));
shapeDrawable.setColor(Color.parseColor(backgroundColor));
StateListDrawable states = new StateListDrawable();
states.addState(new int[] {android.R.attr.state_pressed,
android.R.attr.state_enabled},
context.getResources().getDrawable(R.drawable.textview_pressed_color));
states.addState(StateSet.WILD_CARD, shapeDrawable);
if (item instanceof RelativeLayoutWithContextMenuInfo) {
RelativeLayoutWithContextMenuInfo item2= (RelativeLayoutWithContextMenuInfo)item;
if (android.os.Build.VERSION.SDK_INT < 16) {
item2.setBackgroundDrawable(states);
} else {
item2.setBackground(states);
}
} else if (item instanceof LinearLayout) {
LinearLayout item2= (LinearLayout)item;
if (android.os.Build.VERSION.SDK_INT < 16) {
item2.setBackgroundDrawable(states);
} else {
item2.setBackground(states);
}
}
}
我真的不喜欢在条件下重复代码。有什么建议可以让它更清楚吗?谢谢,J。
最佳答案
除了雅各布连字符答案:
您不需要通用方法,因为您只需要传递 ViewGroup
类型或其子类的参数:
private static void setBackgroundOutlined(Context context,
/* you can pass any layout as item -> */ ViewGroup item,
String backgroundColor,
String outlineColor,
int outlineThickness,
Boolean setStatesPressed) {
// apply you logic on a item based on OS runtime API
}
关于Java/Android : generic method - apply same functionality to different objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23156778/