findViewById没有重复

我开始学习android,并且我有疑问。如果我从XML获得字段,我会这样做:

import android.widget.RatingBar;

public class TestActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        RatingBar rate = (RatingBar) findViewById(R.id.ratebar1);
        rate.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {

            public void onRatingChanged(RatingBar ratingBar, float rating,
                    boolean fromTouch) {
                ((TextView)findViewById(R.id.rating_text)).setText("Rating: "+ (int)rating);
            }
        });

        final Button test = (Button) findViewById(R.id.Button123);
        test.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                RatingBar rate = (RatingBar) findViewById(R.id.ratebar1);
                rate.setRating(2);
            }
        }
        );
        });
}

这个工作正常,但是为什么我不能做:

import android.widget.RatingBar;

public class TestActivity extends Activity {

    RatingBar rate = (RatingBar) findViewById(R.id.ratebar1); //here!!!

    protected void onCreate(Bundle savedInstanceState) {
        //remove!!
        rate.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {

            public void onRatingChanged(RatingBar ratingBar, float rating,
                    boolean fromTouch) {
                ((TextView)findViewById(R.id.rating_text)).setText("Rating: "+ (int)rating);
            }
        });

        final Button test = (Button) findViewById(R.id.Button123);
        test.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //remove!!
                rate.setRating(2);
            }
        }
        );
        });
}

或只是为init实例运行?我该怎么做?

西马斯

您可能希望RatingBar是最终的,但在onCreate方法中是这样的:

protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity_test); // also this as noted by other answers
    final RatingBar rate = (RatingBar) findViewById(R.id.ratebar1); //here!!!
    rate.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {

        public void onRatingChanged(RatingBar ratingBar, float rating,
                boolean fromTouch) {
            ((TextView)findViewById(R.id.rating_text)).setText("Rating: "+ (int)rating);
        }
    });

    final Button test = (Button) findViewById(R.id.Button123);
    test.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            rate.setRating(2);
        }
    }
    );
    });
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章