2016-07-30 4 views
0

정적 함수에서 findViewById에 오류가 있습니다.findViewById가 정적 함수에서 작동하지 않습니다.

내 기능이 오류를 해결하기 위해 어떤 방법이

public static void onYearSelect() { 

    Spinner yearSelector; 
    String yearName; 
    yearSelector = (Spinner) findViewById(R.id.year_submit); 
    yearName = yearSelector.getSelectedItem().toString(); 

} 

데로!

내가 당신은 매개 변수로 함수 내에서보기를 추가 할 필요가 문자열

답변

3

로 yearName에서 스피너의 값을 저장할 수 있습니다.

public static void onYearSelect(View view) { 

    Spinner yearSelector; 
    yearSelector = (Spinner) view.findViewById(R.id.year_submit); 
    yearName = yearSelector.getSelectedItem().toString(); 

} 

The view which contains your layout data.

이 함수를 호출하면 여기에 onYearSelect(rootView)이 추가됩니다. rootView에는 레이아웃보기가 있습니다.

편집 1 :

보기는 여기에 무엇입니까?

A View in Android is a widget that displays something. Buttons, listviews, imageviews, etc. are all subclasses of View. When you say "change view" I assume you mean change the layout by using setContentView(). This usually only needs to be done once per activity. An Activity is basically what you are referring to as a screen.

당신은 here 자세한 내용을보실 수 있습니다.

+0

나는 안드로이드 스튜디오에서 초보자입니다. 당신은 저에게 무엇을 말해 줄 수 있습니까? –

0

spinner 개체에 setOnItemSelectedListener를 설정하고 onItemSelected() 내부에 yearName 값을 설정할 수 있습니다. 아래처럼,

yearSelector.setOnItemSelectedListener(new OnItemSelectedListener() { 
@Override 
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { 
String yearName = parentView.getItemAtPosition(position).toString() 
} 

@Override 
public void onNothingSelected(AdapterView<?> parentView) { 
    // your code here 
}}); 
관련 문제