gpt4 book ai didi

用于 SwitchPreferenc 的 android 自定义 Switch 小部件

转载 作者:太空狗 更新时间:2023-10-29 13:30:04 25 4
gpt4 key购买 nike

我搜索 stackoverflow 并找到下一个相关主题:

  1. How can i style an Android Switch?
  2. Custom switch widget in Android 4
  3. Set switchStyle - get error resource not found - why?

我还在谷歌组上找到错误报告:Issue 36636: Unable to override style switchStyle最后发现 Switch 小部件的新问题:

  • 我尝试制作自己的Preference.SwitchPreference 并使用 Switch 小部件定义布局

    android:id="@+android:id/switchWidget"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:thumb="@drawable/switch_thumb"
    android:layout_gravity="center"
    android:padding="16dip"
    android:focusable="false" />

但我收到编译错误:错误:资源不公开。 (在“id”处,值为“@+android:id/switchWidget”)。所以我不能用这种方式。

  • 第二种方法我尝试扩展 Switch 类,从代码中添加集合资源。但我发现那个方法 setThumbResource仅可从 API 16 获得。但我仍然无法应用 @+android:id/switchWidget,因为它不是公开的。

那么,如何获得 SDK API 15 的自定义开关首选项???或者如何在首选项中自定义 Switch?

最佳答案

刚刚找到了一个糟糕的方法来实现这一目标。

首先,src/com/myapp/views/preference/MySwitchPreference.java

public class MySwitchPreference extends SwitchPreference {
public MySwitchPreference(Context context) {
super(context);
}

public MySwitchPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}

public MySwitchPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}

@Override
protected void onBindView(View view) {
super.onBindView(view);

if (view instanceof ViewGroup) {
setLayout((ViewGroup) view);
}
}

@SuppressLint("NewApi")
private void setLayout(ViewGroup viewGroup) {
int count = viewGroup.getChildCount();
for(int n = 0; n < count; ++n) {
View childView = viewGroup.getChildAt(n);
if(childView instanceof Switch) {
final Switch switchView = (Switch) childView;

if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
switchView.setThumbResource(com.myapp.R.drawable.switch_inner);
switchView.setTrackResource(com.myapp.R.drawable.switch_track);
}
return;
}
else if (childView instanceof ViewGroup)
setLayout((ViewGroup) childView);
}
}
}

现在,res/xml/preferences.xml

<com.myapp.views.preference.MySwitchPreference
android:switchTextOff="Off"
android:switchTextOn="On"
android:title="whatever"
android:key="switch" />

有点棘手,只能在 Android > 16 上使用。

关于用于 SwitchPreferenc 的 android 自定义 Switch 小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16696804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com