OnClick change tablerow background color

倾然丶 夕夏残阳落幕 提交于 2019-12-01 06:59:53

问题


So I'm trying to find an easy way to get the background color or a table row to change when its clicked on. I've been trying to find a way to call what the background color is and check it but I haven't found a way to call the color. Here is what I have right now.

    RowName = (TableRow) findViewById(R.id.RowName); 
    RowName.setBackgroundColor(Color.TRANSPARENT);

    RowName.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            if (RowName.equals(Color.TRANSPARENT))
            RowName.setBackgroundColor(Color.YELLOW);

            else if (RowName.equals(Color.YELLOW))
            RowName.setBackgroundColor(Color.TRANSPARENT);
        }
    });

I know that its wrong. Hopefully you can see what I'm trying to accomplish. If not, what I want to do is have the table row start of transparent. When someone clicks on the table row I want it to change to yellow. Then, if they click it again, I want it to change back to transparent. Thanks.


回答1:


You need to set the background color of your row to a state list drawable (that handles select, pressed, active, non-active).

http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList

The XML should look something like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!--  Active state -->
    <item android:state_selected="true" android:state_focused="false"
        android:state_pressed="false" android:drawable="@android:color/transparent" />
    <!--  Inactive state-->
    <item android:state_selected="false" android:state_focused="false"
        android:state_pressed="false" android:drawable="@android:color/transparent" />
    <!--  Pressed state-->
    <item android:state_pressed="true" android:drawable="@android:color/yellow" />
    <!--  Selected state (using d-pad) -->
    <item android:state_focused="true" android:state_selected="true"
        android:state_pressed="false" android:drawable="@android:color/yellow" />
</selector>



回答2:


So here is what wound up working. Make sure you have your TableRows named. Before my on create I have

private TableRow RowName;

I also have

int state = 0;

. I then add the code

public void RowName(View view) {
  switch (state) {
  case 0:
      RowName.setBackgroundColor(Color.YELLOW);
      state = 1;
      break;
  case 1:
      RowName.setBackgroundColor(Color.TRANSPARENT);
      state = 0;
      break;
  }
}

To get it to work, go into your xml and in the OnClick property add RowName or the name of the public void that you are working with. Enjoy.



来源:https://stackoverflow.com/questions/4410420/onclick-change-tablerow-background-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!