在视图上设置背景色调模式

时间:2015-12-24 03:36:26

标签: android

我可以使用此功能设置ImageView的bakground颜色:

imgButton.getDrawable().setColorFilter(0x77000000, PorterDuff.Mode.SRC_ATOP);

但是当我在View上尝试相同的功能时它不起作用,它表明我无法解析方法getDrawable。

我必须使用View Type,因为我会扩展布局资源文件

public class game extends AppCompatActivity {
RelativeLayout Rel_main_game;
View pauseButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.game);
    Rel_main_game = (RelativeLayout) findViewById(R.id.rlt2);

    LayoutInflater myInflater = (LayoutInflater) getApplicationContext().getSystemService(getApplicationContext().LAYOUT_INFLATER_SERVICE);
    pauseButton = myInflater.inflate(R.layout.pause, null, false);
    Rel_main_game.addView(pauseButton);

    pauseButton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // Here i want to make the view a little dark to show that it is pressed
            return false;
        }
    });

}

Pause.xml布局



<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:id="@+id/imageView"
        android:src="@drawable/pauseimg"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:contentDescription="@string/pauseimgS"
        android:focusableInTouchMode="false"/>
</RelativeLayout>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

试试这个。

bt_slelector.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@color/white" android:state_pressed="false"/>
<item android:drawable="@color/white_ho"/>

在xml布局中。

  android:background="@drawable/bt_slelector"

或使用

pauseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

答案 1 :(得分:0)

您可以尝试使用method view

上的programmatically这个方便的private static StateListDrawable getStateListDrawable(int normalColor, int pressedColor) { StateListDrawable states = new StateListDrawable(); states.addState(new int[]{android.R.attr.state_pressed}, new ColorDrawable(pressedColor)); states.addState(new int[]{android.R.attr.state_focused}, new ColorDrawable(pressedColor)); states.addState(new int[]{android.R.attr.state_activated}, new ColorDrawable(pressedColor)); states.addState(new int[]{}, new ColorDrawable(normalColor)); return states; }
API >=16

只需致电myView.setBackground(getStateListDrawable(normalColor, pressedColor)); API < 16
myView.setBackgroundDrawable(getStateListDrawable(normalColor, pressedColor));致电.a:hover{ }