2014-01-29 47 views
0

此問題已被問及很多次,我在閱讀大約20篇文章並在我的代碼中嘗試各種解決方案後發佈了此問題。無法在ListView中高亮顯示選定的行

我已經使用了一個選擇器,並且我還將ListView的選擇模式定義爲ListView.CHOICE_MODE_SINGLE。但沒有任何工作。這是我的xml文件。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="horizontal" 
    android:weightSum="3" 
    tools:context=".MainActivity" > 

<ListView 
    android:id="@+id/listView" 
    android:layout_width="0dp" 
    android:layout_height="match_parent" 
    android:layout_weight="1" 
    android:background="@drawable/bg_key" /> 

<TextView 
    android:id="@+id/textView" 
    android:layout_width="0dp" 
    android:layout_height="match_parent" 
    android:layout_weight="2" /> 

</LinearLayout> 

這是上述文件的java代碼。

public class MainActivity extends Activity { 

    ListView listView; 
    TextView textView; 

    String array[] = new String[] { "abc", "def", "ghi", "jkl", 
      "mno", "pqr" }; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     listView = (ListView) findViewById(R.id.listView); 
     textView = (TextView) findViewById(R.id.textView); 
     listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 

     ArrayAdapter<String> adapter = new ArrayAdapter<String>(
       getApplicationContext(), 
       android.R.layout.simple_dropdown_item_1line, array); 
     listView.setAdapter(adapter); 

     listView.setOnItemClickListener(new OnItemClickListener() { 

      @Override 
      public void onItemClick(AdapterView<?> arg0, View view, 
        int position, long arg3) { 
       // TODO Auto-generated method stub 
       view.setSelected(true); 
       String clicked = array[position]; 
       textView.setText("You clicked " + clicked); 

      } 
     }); 

    } 

這裏是bg_key.xml文件存儲在可繪製文件夾中。

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

    <item android:drawable="@color/pressed_color" android:state_selected="true"/> 
    <item android:drawable="@color/default_color"/> 

</selector> 

選中的行在點擊後仍然不會突出顯示。它瞬間突出顯示,但隨後又回到原來的顏色。

請幫忙。

謝謝

回答

2

如何使用listselector?!

<listView 
android:listSelector="@drawable/listview_selector"/>