2

如何TextView以编程方式将背景设置为 xml/ripple?

xml/ripple.xml

<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?android:colorFocusedHighlight">
    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <solid android:color="?android:colorAccent" />
        </shape>
    </item>
</ripple>

我试过text.setBackground((Drawable) context.getResources().getXml(R.xml.ripple));但它返回以下异常:

Process: developer.mohab.gymee, PID: 13841
java.lang.ClassCastException: android.content.res.XmlBlock$Parser 
  cannot be cast to android.graphics.drawable.Drawable

    at developer.mohab.gymee.Cardio.HistoryAdapter.<init>(HistoryAdapter.java:36)
    at developer.mohab.gymee.Cardio.HistoryDialogue.onCreateView(HistoryDialogue.java:55)
    at android.app.Fragment.performCreateView(Fragment.java:2053)
    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:894)
    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
    at android.app.BackStackRecord.run(BackStackRecord.java:834)
    at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1452)
    at android.app.FragmentManagerImpl$1.run(FragmentManager.java:447)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:211)
    at android.app.ActivityThread.main(ActivityThread.java:5389)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
4

1 回答 1

1

您的设置稍有错误,但几乎就在那里。

  1. ripple.xmlxml文件夹移动到drawable文件夹
  2. textView.setBackground(context.getDrawable(R.drawable.ripple));
于 2015-10-11T02:33:50.827 回答