2016-03-31 28 views
1

'u ayarlarken Program aracılığıyla bir LayoutParams'ın da ayarlanması gereken bir düğme eklemek istiyorum.NullPointerException LayoutParams

java.lang.NullPointerException: Boş bir nesne başvurusu

I 'int android.view.ViewGroup $ LayoutParams.height' tarla yazmaya çalışılıyor Unfortunaly uygulaması bir istisna verir hiçbir fikrim yok, neden. Bana yardım eder misin? İşte kodum.

Button b = new Button(getApplicationContext()); 
     b.setText(R.string.klick); 
     ViewGroup.LayoutParams params = b.getLayoutParams(); 
     params.height = ViewGroup.LayoutParams.MATCH_PARENT; 
     params.height = ViewGroup.LayoutParams.WRAP_CONTENT; 

cevap

5

programlı b herhangi bir düzen parametreler kümesi olmayacak bir Düğme oluştururken beri. Yani bu gibi manuel olarak ayarlamak gerekir: En az

ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); 
b.setLayoutParams(params); 

Ya onlara

ViewGroup.LayoutParams params = b.getLayoutParams(); 
    if (params != null) { 
     params.width= ViewGroup.LayoutParams.MATCH_PARENT; 
     params.height = ViewGroup.LayoutParams.WRAP_CONTENT; 
    } else 
     params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); 
değiştirmeden önce parametreler boş değil olup olmadığını kontrol
İlgili konular