我读到了为在Android 5.0中实现Switch小部件而引入的新SwitchCompat.我尝试使用相同但我无法看到可绘制的拇指图像,如下图所示.
我的XML代码如下,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp">
<android.support.v7.widget.SwitchCompat
android:id="@+id/sampleSwitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:showtext="false"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp"
android:text="@string/action" />
<TextView
android:id="@+id/switchStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/sampleSwitch"
android:layout_marginTop="22dp"
android:text="@string/status"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
我能够在预览设计(eclipse中的图形布局选项卡)中看到上面布局的拇指图像,但是当我运行我的代码时,我看不到图像.
预览设计
这是我得到的例外
java.lang.NullPointerException: Attempt to invoke virtual method ‘
boolean android.graphics.drawable.Drawable.getPadding(android.graphics.Rect)
‘ on a null object reference
有人可以帮忙解决问题吗?
解决方法:
android:thumb="@drawable/thumb"
android:track="@drawable/bg"
要么
SwitchCompat switchCompat = (SwitchCompat)findViewById(R.id.sampleSwitch);
switchCompat.setThumbResource(R.drawable.apptheme_switch_thumb_holo_light);
switchCompat.setTrackResource(R.drawable.apptheme_switch_track_holo_light);
布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp">
<android.support.v7.widget.SwitchCompat
android:id="@+id/sampleSwitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp"
android:textOff="OFF"
android:textOn="ON"
android:text="Toggle Me"
android:clickable="true"
android:checked="true" />
</RelativeLayout>
和代码
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SwitchCompat switchCompat = (SwitchCompat)findViewById(R.id.sampleSwitch);
switchCompat.setThumbResource(R.drawable.apptheme_switch_thumb_holo_light);
switchCompat.setTrackResource(R.drawable.apptheme_switch_track_holo_light);
}
}