【问题标题】:getResources().getColor not working in custom ViewgetResources().getColor 在自定义视图中不起作用
【发布时间】:2013-05-28 14:19:31
【问题描述】:

我创建了一个自定义视图,但似乎无法从那里访问我自定义的颜色。我的整个应用由以下 3 个文件组成

colors.xml 位于 res/values 文件夹中:

<?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 天,不用说我已经尝试了很多都没有奏效。如果有人能帮我解决这个问题,我将不胜感激。

谢谢!

【问题讨论】:

  • 拼写错误应该是 R.colors.black 而不是 R.color.black
  • 嘿还阮。如果我写 R.colors.black,它不会编译,是的,xml 的名称是 colors.xml。这是我已经尝试过的事情之一,但感谢您的建议!
  • gen文件夹中是否包含R.colors.black id?
  • 嘿霍恩。是的,我已经检查过了,它包含一些像 0x04f0000 之类的值。顺便说一句,我只是想通了这一点并发布了答案,但感谢您为我调查。

标签: java android colors custom-view getresource


【解决方案1】:

试试这个:

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

【讨论】:

    【解决方案2】:

    我刚刚想通了。问题是我在构造函数中设置了viewWidthviewHeight。当我直接在onDraw(Canvas canvas) 中调用getWidth()getHeight() 时,它起作用了。我猜这些值直到onDraw 方法才被设置,或者至少在构造函数之后才设置。

    感谢 Hoan Nguyen 的帮助!

    【讨论】:

      猜你喜欢
      • 2015-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      相关资源
      最近更新 更多