如何在Activity中使用回调

时间:2016-02-18 15:15:21

标签: java android

我是Android开发中的新手,我试图了解如何在界面中使用回调。

我在我的应用中使用"Color-pick-preference"库。我需要它来改变不同的设置,例如背景颜色。我想在运行时更改,无需刷新活动。

这就是我现在的表现:

颜色选择器偏好有三个主要类别:

ColorPickerView(据我了解它显示颜色面板并通过回调将用户选择发送到ColorPickerDialog)

ColorPickerDialog(此类显示优先对话窗口包括颜色面板,提交颜色按钮等,并在ColorPickerPreference中进一步发送用户选择数据)

和ColorPicerPreference,用于在共享首选项中保存用户选择。

如果你原谅我,我的描述非常浅薄。

这三个文件的一部分

ColorPickerView

***



***
private OnColorChangedListener mListener;


***
public interface OnColorChangedListener {
    public void onColorChanged(int color);
}

***

@Override
public boolean onTouchEvent(MotionEvent event) {

    boolean update = false;

    switch (event.getAction()) {

        case MotionEvent.ACTION_DOWN:

            mStartTouchPoint = new Point((int) event.getX(), (int) event.getY());

            update = moveTrackersIfNeeded(event);

            break;

        case MotionEvent.ACTION_MOVE:

            update = moveTrackersIfNeeded(event);

            break;

        case MotionEvent.ACTION_UP:

            mStartTouchPoint = null;

            update = moveTrackersIfNeeded(event);

            break;

    }

    if (update) {

        if (mListener != null) {
            mListener.onColorChanged(Color.HSVToColor(mAlpha, new float[]{mHue, mSat, mVal}));
        }

        invalidate();
        return true;
    }


    return super.onTouchEvent(event);
}

***

public void setOnColorChangedListener(OnColorChangedListener listener) {
    mListener = listener;
}

***

public void setColor(int color, boolean callback) {

    int alpha = Color.alpha(color);

    float[] hsv = new float[3];

    Color.colorToHSV(color, hsv);

    mAlpha = alpha;
    mHue = hsv[0];
    mSat = hsv[1];
    mVal = hsv[2];

    if (callback && mListener != null) {
        mListener.onColorChanged(Color.HSVToColor(mAlpha, new float[]{mHue, mSat, mVal}));
    }

    invalidate();
}

ColorPickerDialog

***

public class ColorPickerDialog
    extends
    Dialog
    implements
    ColorPickerView.OnColorChangedListener,
    View.OnClickListener, ViewTreeObserver.OnGlobalLayoutListener ...

***

private OnColorChangedListener mListener;

***

public interface OnColorChangedListener {
    public void onColorChanged(int color);
}

***

 private void setUp(int color) {

    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    mLayout = inflater.inflate(R.layout.dialog_color_picker, null);
    mLayout.getViewTreeObserver().addOnGlobalLayoutListener(this);

    mOrientation = getContext().getResources().getConfiguration().orientation;
    setContentView(mLayout);

    setTitle(R.string.dialog_color_picker);

    mColorPicker = (ColorPickerView) mLayout.findViewById(R.id.color_picker_view);
    mOldColor = (ColorPickerPanelView) mLayout.findViewById(R.id.old_color_panel);
    mNewColor = (ColorPickerPanelView) mLayout.findViewById(R.id.new_color_panel);

    mHexVal = (EditText) mLayout.findViewById(R.id.hex_val);
    mHexVal.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
    mHexDefaultTextColor = mHexVal.getTextColors();

    mHexVal.setOnEditorActionListener(new TextView.OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                String s = mHexVal.getText().toString();
                if (s.length() > 5 || s.length() < 10) {
                    try {
                        int c = ColorPickerPreference.convertToColorInt(s.toString());
                        mColorPicker.setColor(c, true);
                        mHexVal.setTextColor(mHexDefaultTextColor);
                    } catch (IllegalArgumentException e) {
                        mHexVal.setTextColor(Color.RED);
                    }
                } else {
                    mHexVal.setTextColor(Color.RED);
                }
                return true;
            }
            return false;
        }
    });

    ((LinearLayout) mOldColor.getParent()).setPadding(
            Math.round(mColorPicker.getDrawingOffset()),
            0,
            Math.round(mColorPicker.getDrawingOffset()),
            0
    );

    mOldColor.setOnClickListener(this);
    mNewColor.setOnClickListener(this);
    mColorPicker.setOnColorChangedListener(this);
    mOldColor.setColor(color);
    mColorPicker.setColor(color, true);

}

***

@Override
public void onColorChanged(int color) {

    mNewColor.setColor(color);

    if (mHexValueEnabled)
        updateHexValue(color);


}

***

public void setOnColorChangedListener(OnColorChangedListener listener) {
    mListener = listener;
}

ColorPickerPreference

public class ColorPickerPreference
    extends
    Preference
    implements
    Preference.OnPreferenceClickListener,
    ColorPickerDialog.OnColorChangedListener ...

***

@Override
public void onColorChanged(int color) {
    if (isPersistent()) {
        persistInt(color);
    }
    mValue = color;
    setPreviewColor();
    try {
        getOnPreferenceChangeListener().onPreferenceChange(this, color);
    } catch (NullPointerException e) {

    }
    notifyChanged();
}

***

protected void showDialog(Bundle state) {
    mDialog = new ColorPickerDialog(getContext(), mValue);
    mDialog.setOnColorChangedListener(this);
    if (mAlphaSliderEnabled) {
        mDialog.setAlphaSliderVisible(true);
    }
    if (mHexValueEnabled) {
        mDialog.setHexValueEnabled(true);
    }
    if (state != null) {
        mDialog.onRestoreInstanceState(state);
    }
    mDialog.show();
}

我在MainActivity中尝试做什么

public class MainActivity extends AppCompatActivity implements
    ColorPickerDialog.OnColorChangedListener {

public ColorPickerDialog cpd;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    //return super.onOptionsItemSelected(item);
    Integer id = item.getItemId();
    switch (id) {
        case R.id.menu_action_settings:
            Intent i = new Intent(this, SettingActivity.class);
            startActivity(i);
            break;

    }
    return super.onOptionsItemSelected(item);
}

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

    cpd = new ColorPickerDialog(this,Color.BLACK);
    cpd.setOnColorChangedListener(this);

    setContentView(R.layout.activity_main);
}

public void onColorChanged(int color) {
    RelativeLayout main_scroll_view = (RelativeLayout)findViewById(R.id.activity_main_rel_layout);
    System.out.println("AIM ALIVE!");
    main_scroll_view.setBackgroundColor(color);

}


}

但是当我在ColorPickerPreference小部件中更改颜色时 - 没有任何反应。背景颜色不会改变,我的System.out.println不起作用?

对不起混乱的演讲,谢谢你的回答。

我自己更多的是挑战)通过在Mainactivity中添加onResume方法并检查共享首选项然后在结果值中设置背景颜色来解决问题。

3 个答案:

答案 0 :(得分:0)

您在哪里声明操作以便显示/打开对话框?

答案 1 :(得分:0)

SettingActivity

***

 public static class SettingsFragment extends PreferenceFragment {
    PrefernceAnimation pa;
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        String settings = getArguments().getString("settings");
        if ("colors".equals(settings)) {
            addPreferencesFromResource(R.xml.preference_fragment_colors);
        } else if ("sounds".equals(settings)) {
            addPreferencesFromResource(R.xml.preference_fragment_sounds);
        }
          else if ("animation".equals(settings)) {
            addPreferencesFromResource(R.xml.preference_fragment_animation);

        }

    }

}

和preference_headers.xml

<preference-headers xmlns:android="http://schemas.android.com/apk/res/android">
<header
    android:fragment="com.dosomeweb.mika.babypic.SettingActivity$SettingsFragment"
    android:title="@string/pref_main_title_colors"
    android:summary="@string/pref_main_summery_colors">
    <extra
        android:name="settings"
        android:value="colors"/>


</header>

<header
    android:fragment="com.dosomeweb.mika.babypic.SettingActivity$SettingsFragment"
    android:title="@string/pref_main_title_sounds"
    android:summary="@string/pref_main_summery_sounds">
    <extra
        android:name="settings"
        android:value="sounds"/>



</header>

<header
    android:fragment="com.dosomeweb.mika.babypic.SettingActivity$SettingsFragment"
    android:title="@string/pref_main_title_animation"
    android:summary="@string/pref_main_summery_animation">
<extra
    android:name="settings"
    android:value="animation"/>
</header>

以防prference_fragment_colors.xml

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<net.margaritov.preference.colorpicker.ColorPickerPreference
    android:key="pref_bg_color"
    android:title="@string/pref_title_layout_bg_color"
    android:summary="@string/pref_summary_layout_bg_color"
    android:defaultValue="@color/colorAccent"/>
</PreferenceScreen>

答案 2 :(得分:0)

为什么要创建这么多不同的界面?为什么不使用1个接口并将它们全部链接在一起,因为回调具有相同的参数。