2013-12-18 5 views
0

조각 안에 서클을 만들려고합니다. 런타임에 그 색상을 변경해야합니다. 이지만 setBackgroundDrawable의 방법을 사용하면 nullPointerException이됩니다.setBackgroundDrawable android에 nullpointerexception을 부여합니다.

저는 웹 개발자로서 알아낼 수 없으며 안드로이드 개발을 처음 접했습니다. 도와주세요.

는 그리고 코드는

public class tester extends Fragment { 
    private View circle_holder; 
    @SuppressWarnings("deprecation") 
    @SuppressLint("NewApi") 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.today, container, false); 
     circle_holder = (View)getActivity().findViewById(R.id.cicle); 
     ShapeDrawable mDrawable = new ShapeDrawable(new OvalShape()); 
     mDrawable.getPaint().setColor(Color.RED); 
     if (Build.VERSION.SDK_INT >= 16){ 
      circle_holder.setBackground(mDrawable); 
     } 
     else{ 
      circle_holder.setBackgroundDrawable(mDrawable); 
     } 
     return rootView; 
    } 
} 

답변

3

변경 다음은이 라인입니다.

circle_holder = (View)rootView .findViewById(R.id.cicle); 
+0

헤이 칼리, 덕분에 많은에

circle_holder = (View)getActivity().findViewById(R.id.cicle); 

. 그것은 효과가 있었다. 디버깅 또는 발견 방법에 대한 간단한 팁을 알려줄 수 있습니까? 그래서 미래에 나를 도울 것입니까? – swati

+0

안녕하세요 @swati 당신이 조각에서 사용했을 때 당신은 당신의 팽창 된 view.findviewById를 사용하여 뷰를 가져와야 만합니다. 또는 여러분의 팽창 된 뷰를 리턴 할 조각에서 getView라는 메소드가 있습니다 만, onCreateView()가 호출 된 후에 사용됩니다. 위의 두 가지 방법을 사용하면 단편에서 뷰를 볼 수 있습니다. –

+0

@swati getActivity.findViewById()는 프래그먼트가 추가 된 상위 Activity 뷰를 가져 오는 데 사용되지만 대부분 필요하지 않습니다. –

관련 문제