我有LinearLayout,我在其中动态添加视图。我点击它时需要更改每个视图的背景。
我尝试在我的代码中执行此操作:
public class UserDetailActivity extends Activity implements View.OnTouchListener {
...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.l_user_detail);
Intent intent = getIntent();
User user = (User) intent.getSerializableExtra("class");
userWillGo = (LinearLayout) findViewById(R.id.linerLayout_userDetail_willGoTO);
for (int i = 0; i < user.getUserWillGo().size(); i++) {
View myView = (View)LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_event_list, userWillGo, false);
myView.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT));
...
myView.setOnTouchListener(mOnTouchListener());
userWillGo.addView(myView);
}
}
private View.OnTouchListener mOnTouchListener() {
return new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
v.setBackgroundResource(R.color.textBlue);
}
if (event.getAction() == MotionEvent.ACTION_UP) {
v.setBackgroundResource(R.drawable.bg_item);
}
return true;
}
};
}
此代码的结果是:
我需要得到的东西:
答案 0 :(得分:3)
首先,我建议您使用列表视图组件,而不是循环添加布局。
在列表视图中,您可以创建项目选择器,但无论如何,在当前场景中,您可以在 myView布局上使用可绘制选择器 * selector_bg.xml * 作为 。您也可以使用 android:state_focused =“true | false”,如您的方案中所述:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/hover_bg" /> <!-- pressed -->
<item android:drawable="@drawable/normal" /> <!-- default -->
</selector>
<强> myView.setBackgroundResource(R.drawable.selector_bg)强>