2

たくさんのListItemを含むListViewがあります。ユーザーがアイテムを選択したら、そのListItemの背景を画像に変更したいと思います。どうすればこれを達成できますか?

listView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> a, View v, int position, long id) {
    // how do I change the ListItem background here?
    }
});
4

1 に答える 1

1

のアダプターで設定できますListView。あなたがしなければならないことは、あなたが返すもので使用することですsetBackgroundResource. View簡単な例を挙げましょう。

// lets suppose this is your adapter (which obviously has
//to be a custom one which extends from on of the main
//adapters BaseAdapter, CursorAdapter, ArrayAdapter, etc.)

// every adapter has a getView method that you will have to overwrite
// I guess you know what I'm talking about
public View getView( args blah blah ){
    View theView;
    // do stuff with the view

    // before returning, set the background
    theView.setBackgroundResource(R.drawable.the_custom_background);

    return theView;
}

を使用していることに注意してくださいR.drawable.the_custom_background。つまり、少し XML セレクターを作成する必要があります。ご心配なく。思ったより簡単です。フォルダーthe_custom_background.xml内で呼び出される XML ファイルを作成します。res/drawable

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item 
        android:state_pressed="true" 
        android:state_enabled="true"
        android:drawable="@drawable/the_background_color" />
</selector>

繰り返しますが、私は を使用しているので、最後に というフォルダー@drawable/the_background_colorに別のドローアブルを作成します。res/drawablethe_background_color

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FF0000" />
</shape>

非常に面倒に思えるかもしれませんが、これが Android のやり方です。Viewの内部を変更することもできますがsetOnItemClickListener、それは望ましくなく、実装が難しいと思います。

于 2010-09-27T16:46:24.103 に答える