簡體   English   中英

getResources()。getColor在自定義視圖中不起作用

[英]getResources().getColor not working in custom View

我做了一個自定義視圖,似乎無法從那里訪問我的自定義顏色。 我的整個應用包含以下3個文件

位於res / values文件夾中的colors.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="black">#000000</color>
</resources>

TestView.java:

public class TestView extends View {

    Paint background;
    int viewWidth;
    int viewHeight;

    public TestView(Context context){
        super(context);
        background = new Paint();
        background.setColor(getResources().getColor(R.color.black));
        //find view dimensions
        viewWidth = getWidth();
        viewHeight = getHeight();
    }

    @Override 
    protected void onDraw(Canvas canvas){
        super.onDraw(canvas);
        canvas.drawRect(0,0,viewWidth,viewHeight, background);      
    }
}

和MainActivity.java:

public class MainActivity extends Activity {

    private static final String TAG = "MainActivity";
    TestView testView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        testView = new TestView(this);
        setContentView(testView);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

我得到的只是一個空白的白色屏幕,應該是黑色的! 我一直在試圖找出可能造成這種情況的原因,現在已經連續約2天了,不用說我已經做了很多沒有用的嘗試。 如果有人可以幫助我,我將不勝感激。

謝謝!

我只是想通了。 問題是我在構造函數中設置viewWidthviewHeight 當我直接在onDraw(Canvas canvas)直接調用getWidth()getHeight() ,它起作用了。 我猜想直到onDraw方法或至少在構造函數之后才設置這些值。

感謝Hoan Nguyen的幫助!

嘗試這個:

background.setColor(ContextCompat.getColor(context,R.color.black));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM