问题
I have an example in android that I am trying to run. There were 2 ways to do it..
// Get a drawable
ColorDrawble redDrawable = (ColorDrawable).getResources().getDrawable(R.drawable.red_rectangle);
//Set it as a background to a text view
textView.setBackground(redDrawable);
When I put this in the Eclipse IDE I get an error ColorDrawble cannot be resolved to a type I have the textview in the main XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView android:layout_width="fill_parent"
android:id="@+id/texter"
android:layout_height="wrap_content"
android:text="this string"/>
</LinearLayout>
and the resources in the strings xml file
<resources>
<string name="hello">Hello World, ResourceTesterActivity!</string>
<string name="app_name">ResourceTester</string>
<drawable name="red_rectangle" >#f00</drawable>
<drawable name="blue_rectangle">#0000ff</drawable>
<drawable name="green_rectangle" >#f0f0</drawable>
</resources>
**
回答1:
you can simply use a drawable like this :
// Get a drawable
Drawable redDrawable = YourActivity.this.getResources().getDrawable(R.drawable.red_rectangle);
//Set it as a background to a text view
textView.setBackgroundDrawable(redDrawable);//i've changed setBackground with setBackgroundDrawable.
or you can directly use :
textView.setBackgroundResources(R.drawable.red_rectangle);
NOTE : clean and rebuild your project , and run it to test and for the drawable, you dont need to declare it in strings.xml , just add your drawable on the folder drawables , and it will work
回答2:
It should be:
ColorDrawble redDrawable = (ColorDrawable)
getResources().getDrawable(R.drawable.red_rectangle);
You don't need the dot (perhaps it's a typo).
Then press Ctrl+Shift+O (Organize Imports) to import ColorDrawble class.
来源:https://stackoverflow.com/questions/6621372/android-textview