設置一個不存在的對象我問過,但我會盡量清楚,因爲這個問題被關閉的重複我怎麼能在一個活動中的Android
問題:
當我點擊mbutton2我想在活動中設置一個不存在的textview的大小,(((textview將不會存在,除非我單擊mbutton1))),但是當我點擊mbutton2並且系統顯示:null reference error時,我的應用程序崩潰。
//in Main class
TextView textview;
//creating the text view on button click
Button mbutton1=(Button)findViewById(R.id.button1);
mbutton1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
textview=new TextView(this);
//adding the view to the relativelayout
RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams
(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
textview.setLayoutParams(params);
//making object for Relativelayout and add the view to activity
RelativeLayout relativel=(RelativeLayout)findViewById(R.id.relativelayout);
relative1.addView(textview);
}
});
//now here is the button which must set the size of this text view
Button mbutton2=(Button)findViewById(R.id.button2);
mbutton2.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
textview.setsize(20);
}
});
//And the error is when I click button 2 it says null object reference.
我知道問題的原因,我想要一個清晰的解決方案。
爲什麼不添加空檢查if(textview!= null){textview.setsize(20);}'因爲textview'爲空直到mbutton1沒有按下 –
@ChiragSavsani如果你有一個問題,回答,幫助我。 –
@ρяσѕρєяK如果textview對象仍然不在活動中,我可以設置文本大小,因爲如果用戶想在甚至添加文本之前設置文本的大小。 –