1

私は単純なセレクターをやろうとしています。

「butt.xml」と呼ばれる私のセレクターxmlコードは次のとおりです。

<?xml version="1.0" encoding="utf-8"?>

<item android:drawable="@drawable/btn_activate_on" android:state_pressed="true"/>
<item android:drawable="@drawable/btn_activate_off" android:state_pressed="false"/> <!-- default -->

それがレイアウトです:

<RelativeLayout 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" >

<ImageButton
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="42dp"
    android:src="@drawable/butt" />

それがコードです:

ImageButton ib;

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

    ib = (ImageButton) findViewById(R.id.imageView1);
    ib.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    ib.setSelected(true);

}

私の問題は、ボタンを押したままにしても状態が変化しないことです。"selected"押した時の画像に変化しています。でも指を離すと元の状態に戻りつつあり"not sellected"ます。

どうしてこんなことに?「選択済み」モードのままにするにはどうすればよいですか?

4

3 に答える 3

1

そのようなトグルにはボタンを使用しないでください。代わりにチェックボックスを使用してください。

ボタンの「選択済み」は、ユーザーが現在ボタン上に指を置いていることを意味するため、ユーザーが指を離すと、ボタンは選択されなくなります。

于 2013-07-31T01:59:29.093 に答える
1

ボタンの状態を選択または非選択として表示する必要がある場合は、セレクターを使用する必要はありません。

代わりに、コードを使用して setBackground() を実行する必要があり、フラグを管理することで、ボタンが現在選択されているかどうかを確認できます。

お気に入り

if(flag)
    btn.setDrawableBackground(R.id.btn_activate_on)
else
    btn.setDrawableBackground(R.id.btn_activate_off)

状態への影響を表示したい場合は、逆の状態を持つ 2 つのセレクターを作成します。

<item android:state_pressed="true"
    android:drawable="@drawable/btn_activate_on"></item>
<item android:drawable="@drawable/btn_activate_off"></item>

そしてもう一つは

<item android:state_pressed="true"
    android:drawable="@drawable/btn_activate_off"></item>
<item android:drawable="@drawable/btn_activate_on"></item>
于 2012-11-05T10:05:18.250 に答える