如何通过在非活动类中调用findviewbyid方法来实例化视图?

时间:2018-07-07 11:27:10

标签: android

在下面的这段代码中,我只能实例化一次视图吗?然后,我可以将其用于帮助程序类中的某些方法。

public class Helper {

    private Context context;
    private Activity activity;

    private TextView textView;
    private Button button;

    public Helper(Context context, Activity activity) {
        this.context = context;
        this.activity = activity;
    }

    public void firstMethod() {
        textView = (TextView) activity.findViewById(R.id.text_view);
        button = (Button) activity.findViewById(R.id.button);

        textView.setText(R.string.some_text_1);
        button.setText("Tes1 Button")
    }

    public void secondMethod() {
        textView = (TextView) activity.findViewById(R.id.text_view);
        button = (Button) activity.findViewById(R.id.button);

        textView.setText(R.string.some_text_2);
        button.setText("Tes2 Button")
    }
}

如您所见,textView和button以不同的方法实例化了两次,但是我只想单个实例化。该如何编码?

更新

在活动中,我们可以这样做:

protected void onCreate(Bundle savedInstanceState) {
    //see this code
    textView = (TextView) findViewById(R.id.text_view);
    button = (Button) findViewById(R.id.button);
}

然后在方法中我们就像这样:

public void someMethod() {
        textView.setText(R.string.some_text_2);
        button.setText("Tes2 Button")
}

在非活动状态下,我需要如上所示的代码。有可能吗?

3 个答案:

答案 0 :(得分:0)

使用上下文代替活动:-

请确保在代码初始化时需要将Activity作为构造函数参数传递给Non Activity类。

引用:-{findViewById in non activity class

   public void secondMethod() {
        textView = (TextView) context.findViewById(R.id.text_view);
        button = (Button) context.findViewById(R.id.button);

        textView.setText(R.string.some_text_2);
        button.setText("Tes2 Button")
    }

答案 1 :(得分:0)

如果我正确理解了您的要求,则可以在构造函数中实例化它们,就像这样

public Helper(Context context) {
    // You really don't even need to save context in this case since
    // you only use it in the constructor. If your real problem is more
    // complex you may still need to though
    this.context = context;

    textView = (TextView) context.findViewById(R.id.text_view);
    button = (Button) context.findViewById(R.id.button);
}

那么您不必在firstMethodsecondMethod中这样做,

public void firstMethod() {
    textView.setText(R.string.some_text_1);
    button.setText("Tes1 Button")
}

public void secondMethod() {
    textView.setText(R.string.some_text_2);
    button.setText("Tes2 Button")
}

然后,您可以从活动onCreate之类的内部创建您的帮助程序类

private Helper helper;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_time_till);
    helper = new Helper(this);
}

答案 2 :(得分:0)

在构造函数中进行初始化:

public Helper(Context context, Activity activity) {
    this.context = context;
    this.activity = activity;

    textView = (TextView) activity.findViewById(R.id.text_view);
    button = (Button) activity.findViewById(R.id.button);
}