Tomblarom
Tomblarom

Reputation: 1458

TextView as attribute?

I'd like to use my TextView as attribute

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);

instead of define it 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);
        <..>
}

The upper methode is producing a force close error on my android device. How to solve this or is that generally possible?

Thanks!

Upvotes: 1

Views: 45

Answers (1)

scubasteve623
scubasteve623

Reputation: 647

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);

}

I'm not sure why your app is crashing, but you will save yourself a lot of headache by declaring/assigning your widgets like this... only one time for the whole activity.

Upvotes: 1

Related Questions