티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
findViewById in Fragment
Fragment에서 findViewById 사용하기
문제 내용
I am trying to create an ImageView in a Fragment which will refer to the ImageView element which I have created in the XML for the Fragment. However, the findViewById
method only works if I extend an Activity class. Is there anyway of which I can use it in Fragment as well?
XML에서 Fragment에 대해 생성한 ImageView 요소를 참조할 Fragment에 ImageView를 생성하려고 합니다. 그러나 findViewById 메서드는 Activity 클래스를 확장하는 경우에만 작동합니다. 프래그먼트에서도 사용할 수 있는 방법이 있나요?
public class TestClass extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ImageView imageView = (ImageView)findViewById(R.id.my_image);
return inflater.inflate(R.layout.testclassfragment, container, false);
}
}
The findViewById
method has an error on it which states that the method is undefined.
findViewById 메서드에 정의되지 않은 오류가 있습니다.
높은 점수를 받은 Solution
Use getView() or the View parameter from implementing the onViewCreated
method. It returns the root view for the fragment (the one returned by onCreateView()
method). With this you can call findViewById()
.
onViewCreated 메서드를 구현할 때 getView() 또는 View 매개 변수를 사용합니다. Fragment에 대한 루트 뷰(onCreateView() 메서드에서 반환한 루트 뷰)를 반환합니다. 루트뷰를 이용해 findViewById()를 호출할 수 있습니다.
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
ImageView imageView = (ImageView) getView().findViewById(R.id.foo);
// or (ImageView) view.findViewById(R.id.foo);
As getView()
works only after onCreateView()
, you can't use it inside onCreate()
or onCreateView()
methods of the fragment .
getView()는 onCreateView() 이후에만 작동하므로 프래그먼트의 Create() 또는 onCreateView() 메서드에서 내부에서 사용할 수 없습니다.
가장 최근 달린 Solution
ImageView imageView;
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.testclassfragment, container, false);
imageView = view.findViewById(R.id.my_image);
return view;
출처 : https://stackoverflow.com/questions/6495898/findviewbyid-in-fragment
'개발 > 안드로이드' 카테고리의 다른 글
패키지 이름과 일치하는 클라이언트를 찾을 수 없습니다(Google Analytics) (0) | 2022.12.01 |
---|---|
웹뷰 net::ERR_CACHE_MISS 오류 메시지 (0) | 2022.12.01 |
WebView에서 JavaScript 함수 호출 (0) | 2022.12.01 |
"Unable to add window — token null is not for an application” 오류 수정하기 (0) | 2022.12.01 |
액티비티 상태 저장하기 (0) | 2022.12.01 |