2016-12-26 42 views
-2

設置一個不存在的對象我問過,但我會盡量清楚,因爲這個問題被關閉的重複我怎麼能在一個活動中的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. 

我知道問題的原因,我想要一個清晰的解決方案。

+0

爲什麼不添加空檢查if(textview!= null){textview.setsize(20);}'因爲textview'爲空直到mbutton1沒有按下 –

+0

@ChiragSavsani如果你有一個問題,回答,幫助我。 –

+0

@ρяσѕρєяK如果textview對象仍然不在活動中,我可以設置文本大小,因爲如果用戶想在甚至添加文本之前設置文本的大小。 –

回答

0

做到這樣,

int size = 14; // 14 is the default textview text size; 

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.setTextSize(size); //setting up textview size (default or changed) 

    textview.setLayoutParams(params); 

    //making object for Relativelayout and add the view to activity 
    RelativeLayout relativel=(RelativeLayout)findViewById(R.id.relativelayout); 
    relative1.addView(textview); 
    } 
}); 

Button mbutton2=(Button)findViewById(R.id.button2); 
mbutton2.setOnClickListener(new View.OnClickListener(){ 
@Override 
    public void onClick(View view){ 

     size = 20; // textview text size you want to set 
     if(textview != null){ 
      textview.setTextSize(size); 
     } 

    } 
}); 

任何東西,你只申報,並試圖初始化應顯示NullPointerException異常之前使用它。 這裏,

TextView textview; //--- This is the declaration 

,如果你BUTTON1之前BUTTON2點擊,初始化不會發生,因爲,

textview=new TextView(this); //--- this line is inside button1 click listener. So textview remains null. 

在上面的代碼,

size = 20; // textview text size you want to set 
    if(textview != null){ 
     textview.setTextSize(size); 
    } 

這部分節省TextView的大小初始化時使用,如果textview沒有初始化,如果你想要做,如果初始化然後設置值。

+0

你是一個天才,就是我所能說的。 –

+0

非常感謝。 –