0

我有一个活动myActivity,其中包含一个 TextViewmyTv和另一个myClass具有单个方法的Class modifyTv

如何修改myTv使用该modifyTv方法的值?

class myActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    myClass myc = new myClass();
    myc.modifyTv();// this line of code must be able to modify myTv value.

}
}
4

3 回答 3

1

You have several options:

1. Pass more info to the constructor. For example, Context or myTv. For example:

public class MyClass {
    Context context;
    public MyClass(Context context) {
        this.context = context;
    }
    public void modifyTv() {
        TextView tv = (TextView) context.findViewById(R.id.myTv);
        tv.setText("Foobar");
    }
}

Then just call:

MyClass m = new MyClass(this);
m.modifyTv();

2. Pass more info to the modifyTv() method.

public class MyClass {

    public void modifyTv(TextView tv) {
        tv.setText("Foobar");
    }
}

Then just call:

MyClass m = new MyClass();
m.modifyTv((TextView) findViewById(R.id.tv));

3. Other, more complicated ways that don't make much sense.

于 2013-08-14T19:01:27.777 回答
1

在“myClass”中,您需要参考您的活动,以便您可以致电

activity.findViewById(R.id.text_id)

您可以在构造函数中传递活动或在其中创建 let saysetCurrentActivity方法myClass

或者,更容易引用TextView自身。

于 2013-08-14T18:59:00.347 回答
1

好吧,你可以这样做:

myc.modifyTv(myTextView);

并且只需将要修改的 TextView 作为参数传递。

于 2013-08-14T18:59:21.913 回答