我对Android开发很新,所以我遇到了onResume()方法的问题。
当我尝试从onResume()方法中编写Name.setText()时,我的代码崩溃了。 从onPause()方法中编写TextView可以毫无问题地工作。
如何从onResume()方法中访问此TextView?
public class Main extends Activity {
private ViewPager awesomePager;
private static int NUM_AWESOME_VIEWS = 2;
private Context cxt;
private AwesomePagerAdapter awesomeAdapter;
View v;
TextView Name;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cxt = this;
awesomeAdapter = new AwesomePagerAdapter();
awesomePager = (ViewPager) findViewById(R.id.awesomepager);
awesomePager.setAdapter(awesomeAdapter);
}
@Override
protected void onResume() {
super.onResume();
Name.setText("1");
}
@Override
protected void onPause() {
super.onPause();
}
private class AwesomePagerAdapter extends PagerAdapter{
@Override
public int getCount() {
return NUM_AWESOME_VIEWS;
}
@Override
public Object instantiateItem(View collection, int position) {
View v = new View(cxt.getApplicationContext());
final LayoutInflater inflater = (LayoutInflater) cxt
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
switch (position) {
case 0:
v = inflater.inflate(R.layout.subpage1, null, false);
Name = (TextView) v.findViewById(R.id.name);
break;
case 1:
v = inflater.inflate(R.layout.subpage2, null, false);
break;
default:
break;
}
((ViewPager) collection).addView(v, 0);
return v;
}
@Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView(v);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public void finishUpdate(View arg0) {}
@Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {}
@Override
public Parcelable saveState() {
return null;
}
@Override
public void startUpdate(View arg0) {}
}
}
答案 0 :(得分:1)
Name
必须设置为null ...您的应用必须在初始化之前暂停。在尝试使用它之前,请检查以确保它已初始化。你onResume()
应该是这样的:
@Override
protected void onResume() {
super.onResume();
if(Name != null){
Name.setText("1");
}
}
P.S。标准java约定是让所有变量名以小写字母开头。您应该将Name
重命名为name
。
答案 1 :(得分:1)
首先,在您的代码中,您没有获得对Name
文本视图的引用,因此您必须获得NullPointerException。
如果你解决了这个问题,它应该适用于IMO。如果没有,请告诉我们您获得的例外名称。