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



我可以使用以下函数设置ImageView的背景颜色:

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

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

我必须使用视图类型,因为我膨胀了布局资源文件

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>

试试这个。

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) {
        }
    });

您可以尝试我在任何view programmatically 上使用的这种方便的method

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));

最新更新