Button.setBackground(Drawable background) throws NoSuchMethodError

前端 未结 5 1701
故里飘歌
故里飘歌 2021-02-04 08:57

I\'m implementing a simple method to add a Button to a LinearLayout programatically.

When I invoke the setBackground(Drawable background) metho

5条回答
  •  一生所求
    2021-02-04 09:35

    To create a homogeneous background for a View, you can create a drawable resource of type shape, and use that with the setBackgroundResource.

    red_background.xml

    
     
            
    
    

    Activity:

    Button b = (Button)findViewById(R.id.myButton);
    b.setBackgroundResource(R.drawable.red_background);
    

    But this will look pretty bad, flat and out of place. If you want a colored button that looks like a button, than you can either design it yourself (rounded corners, stroke, gradient fill...) or a fast and dirty solution is to add a PorterDuff filter to the button's background:

    Button b = (Button)findViewById(R.id.myButton);
    PorterDuffColorFilter redFilter = new PorterDuffColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY);
    b.getBackground().setColorFilter(redFilter);
    

提交回复
热议问题