3

次のように呼び出される Activity のスーパータイプ メソッドを実装する Android アプリを構築してonCheckedChanged(CompoundButton buttonView, boolean isChecked)います。

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if (isChecked){
        LinearLayout view = (LinearLayout) findViewById(R.id.some_view);
        Animation anim = expand(view, true);
        view.startAnimation(anim);
    }
    else {
        LinearLayout view = (LinearLayout) findViewById(R.id.some_view);
        Animation anim = expand(view, false);
        view.startAnimation(anim);
    }
}

そして、このメソッドは、次のように onCreate メソッドで Switch をリッスンするように設定されます。

mySwitch = (Switch) findViewById(R.id.my_switch);
mySwitch.setOnCheckedChangeListener(this);

some_view問題は、このメソッドを だけでなく、他のいくつかのビューにも実装したいということです。このメソッドを数回コピー/貼り付けして some_view を変更したくないので、ビューを渡す何らかの方法が必要です。ただし、このメソッドをオーバーライドしているため、単純にメソッドに引数を追加することはできません。このメソッドにリスナーを設定したため、このメソッドが呼び出される直前に id をグローバル変数に設定することもできません。

したがって、私の質問は次のとおりです。メソッドをコピーして貼り付けて複数のビューで再利用する必要がないように、このメソッドに id を渡すにはどうすればよいですか?

4

3 に答える 3

4

OnCheckedChangeListener独自のものと、ニーズに合った 2 つのオプションのいずれかを実装します。

  1. このリスナーの複数のインスタンスを使用します。の各ペアに 1 つ<Switcher, LinearLayout>
  2. の配列を保持するこのリスナーの 1 つのインスタンスを使用LinearLayoutsして、1 つのインスタンスを切り替えるときにそれらすべてをアニメーション化しSwitcherます。

これは、両方のオプションのコードです。

public class MyOnCheckedChangeListener implements CompoundButton.OnCheckedChangeListener {

    private final View[] mViews;

    public MyOnCheckedChangeListener(View... views) {
        mViews = views
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        for (View v : mViews) {
            LinearLayout layout = (LinearLayout) v;
            if (isChecked) {
                Animation anim = expand(layout, true);
                layout.startAnimation(anim);
            } else {
                Animation anim = expand(layout, false);
                layout.startAnimation(anim);
            }
        }
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // inflate layout

    // option 1
    mySwitch = (Switch) findViewById(R.id.my_switch);
    mySwitch.setOnCheckedChangeListener(
            new MyOnCheckedChangeListener(findViewById(R.id.some_view)));
    myOtherSwitch = (Switch) findViewById(R.id.my_other_switch);
    myOtherSwitch.setOnCheckedChangeListener(
            new MyOnCheckedChangeListener(findViewById(R.id.some_other_view)));

    // option 2
    mySwitch = (Switch) findViewById(R.id.my_switch);
    mySwitch.setOnCheckedChangeListener(
            new MyOnCheckedChangeListener(new View[]{
                    findViewById(R.id.some_view),
                    findViewById(R.id.some_other_view)
            }));
}
于 2013-10-06T22:26:36.177 に答える