TextView作为属性?

时间:2015-04-01 13:52:00

标签: java android

我想将TextView用作属性

private TextView up = (TextView) findViewById(R.id.tv_up);
private TextView mid = (TextView) findViewById(R.id.tv_mid);
private TextView down = (TextView) findViewById(R.id.tv_down);

而不是定义它evertime new:

public void onButtonClickUp(View v) {
        TextView up = (TextView) findViewById(R.id.tv_up);
        TextView mid = (TextView) findViewById(R.id.tv_mid);
        TextView down = (TextView) findViewById(R.id.tv_down);
        <..>
}

public void onButtonClickDown(View v) {
        TextView up = (TextView) findViewById(R.id.tv_up);
        TextView mid = (TextView) findViewById(R.id.tv_mid);
        TextView down = (TextView) findViewById(R.id.tv_down);
        <..>
}

上层方法在我的Android设备上生成force close error。如何解决这个问题还是一般可能的?

谢谢!

1 个答案:

答案 0 :(得分:1)

public class TestActivity extends Activity {

    private TextView up;
    private TextView mid;
    private TextView down;

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

     up = (TextView) findViewById(R.id.tv_up);
     mid = (TextView) findViewById(R.id.tv_mid);
     down = (TextView) findViewById(R.id.tv_down);

}

我不确定你的应用程序崩溃的原因,但是你会通过声明/分配这样的小部件来为自己节省很多麻烦......整个活动只有一次。