仅使用来自公共静态方法的调用来调用所有实例的私有方法

时间:2017-06-05 08:31:41

标签: java android static-methods instances non-static

我正在尝试为其他应用创建一个库。

该库包含一个简单的自定义视图(AutoTranslateTextView),用于将当前文本从一种语言翻译成另一种语言。

要求允许单次调用AutoTranslateTextView的public static function translateAllTo(String)开始翻译所有实例,请参阅以下代码:

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;
import java.lang.ref.WeakReference;

public class AutoTranslateTextView extends TextView {

    private static final String TAG = AutoTranslateTextView.class.getSimpleName();

    public AutoTranslateTextView(Context context) { this(context, null); }
    public AutoTranslateTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); }
    public AutoTranslateTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        if(isInEditMode()) { return; }

        mHandler = new IncomingTranslationRequest(this);
    }

    private static IncomingTranslationRequest mHandler;

    private static class IncomingTranslationRequest extends Handler {

        private WeakReference<AutoTranslateTextView> mHAutoTranslateTextView;

        public IncomingTranslationRequest(AutoTranslateTextView hattv) {
            mHAutoTranslateTextView = new WeakReference<AutoTranslateTextView>(hattv);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if(msg.what == 1) {
                if(msg.obj != null) {
                    mHAutoTranslateTextView.get().translateTo((String) msg.obj);
                } else {
                    Log.e(TAG, "handleMessage(Message), msg.obj is null or not LanguageLocaleCode");
                }
            } else {
                Log.e(TAG, "handleMessage(Message), unhandled what: " + msg.what);
            }
        }
    };

    public static void translateAllTo(String languageCode) {
        if(languageCode == null) {
            Log.e(TAG, "translateAllTo(languageCode), parameter is null");
            return;
        }

        if(mHandler == null) {
            Log.e(TAG, "translateAllTo(" + languageCode + "), handler is null");
            return;
        }

        Log.d(TAG, "translateAllTo(" + languageCode + ")");

        mHandler.sendMessage(Message.obtain(mHandler, 1, languageCode));
    }

    private void translateTo(String languageCode) {
        String text = (String) getText();

        Log.d(TAG, "translateTo(" + languageCode + "), current text: " + text);

        // --------- Main logic here ----------
    }
}

我的问题是,当调用translateAllTo(languageCode)时,只有一个(最后一个)实例将执行translateTo(languageCode)

我知道app(不是我的库)可以为每个实例调用translateTo(languageCode),但是客户端要求我只需要调用1个公共静态方法来翻译所有AutoTranslateTextView实例。

这可能吗?

0 个答案:

没有答案