-2

我有LinearLayout,我可以在其中動態添加視圖。當我點擊它時,我需要更改每個視圖的背景。更改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; 
      } 
     }; 
} 

我能得到什麼,因爲這代碼的結果:

enter image description here

我需要得到:

enter image description here

+0

什麼可以用狀態選擇器來繪製? – Zielony 2013-03-20 12:36:40

+0

你在談論.xml嗎? – Val 2013-03-20 12:37:22

+1

不需要。如果你知道,如何爲你的視圖設置背景,你可以用狀態選擇器替換那個可繪製的背景,你可以用代碼或者xml來完成, r更方便。請參閱:http://www.vogella.com/articles/AndroidDrawables/article.html#drawables_state – Zielony 2013-03-20 12:42:09

回答

3

首先我會建議你去哈有一個列表視圖組件,而不是在循環中添加布局。

在列表視圖中,你可以創建一個項目選擇,但不管怎麼說在當前情況下,你可以有一個平局,能夠選擇* selector_bg.xml *在MyView的佈局作爲 。您還可以使用Android的:state_focused =「真|假」在方案中所解釋的:

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

Detailed Reference for the above click here

+0

它的工作原理但只有當我使用這個LinearLayout作爲ListView中的項目,但不適用於我的情況。不知道爲什麼。 – Val 2013-03-20 13:15:32

+0

@ p.Valery它應該在當前情況下工作也可能是由於視圖上的其他焦點 - sable項目,但我仍然建議最好的方式是列表視圖。因爲它回收視圖和沒有內存問題,所以做一個優化的應用程序 – 2013-03-20 13:30:43

+0

我需要一個沒有滾動的列表,我不能用列表視圖幫助來做到這一點。 – Val 2013-03-20 14:01:01