如何访问android中子类中的主要活动内容

时间:2011-09-15 08:53:43

标签: java android xml

我在主要活动上编辑了文本,我需要在子类上访问此编辑文本......

这是我的主要活动

private EditText et1;
    private EditText et2, et;

// int dec = et.getText().toString().length()-1;

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

    et1 = (EditText) findViewById(R.id.editText1);
    et2 = (EditText) findViewById(R.id.editText2);
    et = et1;
    gLib = GestureLibraries.fromRawResource(this, R.raw.gestures);

    // glip1 = GestureLibraries.fromRawResource(this, R.raw.gestures1);

    if (!gLib.load()) {
        Log.w(TAG, "could not load gesture library");
        finish();
    }
    GestureOverlayView gestures = (GestureOverlayView) findViewById(R.id.gestures);
    common myHandler = new common();
    gestures.addOnGesturePerformedListener(myHandler);
}

这是我的班级

public class common implements OnGesturePerformedListener {


    @Override
    public void onGesturePerformed(GestureOverlayView gestureView,
            Gesture gesture) {
        System.out.println("guster");

        ArrayList<Prediction> predictions = gLib.recognize(gesture);//i have to acces glip from main activity
        // ArrayList<Prediction> predictions1 = glip1.recognize(gesture);
        // one prediction needed
        if (predictions.size() > 0 && predictions.get(0).score > 2.0) {
            String prediction = predictions.get(0).name;
            // checking prediction

            if (prediction.equals("A")) {
                // and action
                et.append("A");// i have to access edit text from main activity
                // et.getText().insert(et.getSelectionStart(), "A");
            }
        }
    }
}

3 个答案:

答案 0 :(得分:3)

在构造函数中传递对活动的引用,并添加相关方法以在类之间进行通信(不要直接访问Activity的字段......)

活动:

 common myHandler = new common(this);

在Common中(使用名称约定的大写C):

public class Common implements OnGesturePerformedListener {

    private YourActivityClass activity;

    public Common(YourActivityClass activity) {
        this.activity = activity;
    }
    // Rest of code

}

答案 1 :(得分:0)

最简单的方法是在启动时将主类/对象引用传递给子类,即在构造函数中。并将引用存储在成员变量中以便稍后使用它们。

答案 2 :(得分:0)

忘记尝试从活动外部访问成员。

让您的活动实施GesturePerformedListener

public class MyActivity implements OnGesturePerformedListener
{
  //your activity code here
}

然后,在设置监听器时,不要创建common类,只需使用this

gestures.addOnGesturePerformedListener(this);

这消除了对单独类的需要,并允许您直接访问TextView