조각의 findViewById
조각에 대한 XML에서 만든 ImageView 요소를 참조하는 조각에 ImageView를 만들려고합니다. 그러나이 findViewById
메서드는 Activity 클래스를 확장하는 경우에만 작동합니다. 어쨌든 Fragment에서도 사용할 수 있습니까?
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);
}
}
findViewById
메소드는 메소드가 정의되는 것을 말한다 그것에 에러를 갖는다.
메소드 구현에서 getView () 또는 View 매개 변수를 사용하십시오 onViewCreated
. 조각에 대한 루트 뷰를 반환합니다 ( 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);
으로 getView()
후에 만 작동 onCreateView()
, 당신은 내부를 사용할 수 없습니다 onCreate()
또는 onCreateView()
방법 조각의.
Fragment의 뷰를 확장하고 반환 findViewById()
되는 호출 을 View
해야합니다.
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.my_image);
return view;
}
Fragment
클래스 내에서 onViewCreated () 오버라이드 메서드를 얻을 수 있습니다.이 메서드에서와 같이 항상 뷰를 초기화해야합니다. 다음과 같이 뷰를 찾을 수있는 뷰 객체를 가져옵니다.
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.yourId).setOnClickListener(this);
// or
getActivity().findViewById(R.id.yourId).setOnClickListener(this);
}
Fragment의 경우 항상 onViewCreated()
null 또는 super.onCreateView()
from onCreateView()
메서드를 반환하는 경우 메서드가 자동으로 호출되지 않음 을 기억하십시오 . 기본적 ListFragment
으로 ListFragment
반환 FrameLayout
되는 경우 기본적으로 호출됩니다 .
참고 : getView()
한 번 onCreateView()
성공적으로 실행 되면 클래스의 모든 위치에서 조각보기를 얻을 수 있습니다 . 즉
getView().findViewById("your view id");
나는 이것이 오래된 질문이라는 것을 알고 있지만 일반적인 대답은 원하는 것을 남깁니다.
질문은 무엇이 필요한지 명확하지 않습니다 imageView
. 뷰로 다시 전달하거나 나중에 참조를 저장하는 것입니까?
어느 쪽이든, ImageView
부풀린 레이아웃에서 오는 경우 올바른 방법은 다음과 같습니다.
public class TestClass extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = (ImageView)v.findViewById(R.id.my_image);
return v;
}
}
먼저 조각보기를 가져온 다음이보기에서 ImageView를 가져옵니다.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.my_image);
return view;
}
onActivityCreated
방법 에서도 할 수 있습니다 .
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
여기 에서처럼 : http://developer.android.com/reference/android/app/Fragment.html (API 레벨 28에서 더 이상 사용되지 않음)
getView().findViewById(R.id.foo);
과
getActivity().findViewById(R.id.foo);
가능합니다.
getView()
루트 뷰를 제공합니다
View v = getView().findViewByID(R.id.x);
모든 뷰가 확장 된 직후에 호출되는 onViewCreated ()를 재정의 할 수 있습니다. Fragment의 멤버 View
변수 를 채우기에 적합한 위치 입니다. 예를 들면 다음과 같습니다.
class GalleryFragment extends Fragment {
private Gallery gallery;
(...)
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
gallery = (Gallery) view.findViewById(R.id.gallery);
gallery.setAdapter(adapter);
super.onViewCreated(view, savedInstanceState);
}
}
getView () 메서드는 OnCreate 및 유사한 메서드 외부의 조각에서 작동하지 않습니다.
두 가지 방법이 있습니다. oncreate의 함수에 뷰를 전달하거나 (즉, 뷰가 생성 될 때만 함수를 실행할 수 있음을 의미합니다) 뷰를 변수로 설정합니다.
private View rootView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_contatos, container, false);
}
public void doSomething () {
ImageView thumbnail = (ImageView) rootView.findViewById(R.id.someId);
}
1) 먼저 Fragment의 레이아웃을 확장 한 다음 findviewbyId를 사용할 수 있습니다.
View view = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.my_image);
return view;
EditText name = (EditText) getView().findViewById(R.id.editText1);
EditText add = (EditText) getView().findViewById(R.id.editText2);
사용하다
imagebutton = (ImageButton) getActivity().findViewById(R.id.imagebutton1);
imageview = (ImageView) getActivity().findViewById(R.id.imageview1);
그것은 작동 할 것이다
findViewById()
View 를 부르는 것에 동의했습니다 .
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = (ImageView) V.findViewById(R.id.my_image);
return V;
}
노트 :
API 레벨 26에서는 반환 유형에 대한 추론을 사용하므로 findViewById의 결과를 구체적으로 캐스팅 할 필요가 없습니다.
이제 간단하게 할 수 있습니다.
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = view.findViewById(R.id.my_image); //without casting the return type
return view;
}
API 레벨 11에 대한 문서에 따르면
참조, 백 스택 http://developer.android.com/reference/android/app/Fragment.html
짧은 코드
/**
* The Fragment's UI is just a simple text view showing its
* instance number.
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.hello_world, container, false);
View tv = v.findViewById(R.id.text);
((TextView)tv).setText("Fragment #" + mNum);
tv.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.gallery_thumb));
return v;
}
Using getView()
returns the view of the fragment, then you can call findViewById()
to access any view element in the fragment view.
Try this it works for me
public class TestClass extends Fragment {
private ImageView imageView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.testclassfragment, container, false);
findViews(view);
return view;
}
private void findViews(View view) {
imageView = (ImageView) view.findViewById(R.id.my_image);
}
}
Inside Fragment
class you will get onViewCreated()
override method where you should always initialize your views as in this method you get view
object using which you can find your views like :
class MyFragment extends Fragment {
private ImageView imageView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.my_fragment_layout, container, false);
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState)
super.onViewCreated(view, savedInstanceState);
//initialize your view here for use view.findViewById("your view id")
imageView = (ImageView) view.findViewById(R.id.my_image);
}
}
The best way to implement this is as follows:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = (ImageView) rootView.findViewById(R.id.my_image);
return rootView
}
In this way, the rootView can be used for each control defined in the xml layout and the code is much cleaner in this way.
Hope this helps :)
1) Declare your layout file.
public View onCreateView(LayoutInflater inflater,ViewGroup container,
Bundle savedInstanceState) {
return inflate(R.layout.myfragment, container, false);
}
2)Then, get the id of your view
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView nameView = (TextView) view.findViewById(R.id.textview1);
}
Use gradle skeleton plugin, it will automatically generate the view holder classes with the reference to your layout.
public class TestClass extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
MyLayout myLayout = new MyLayout(inflater, container, false);
myLayout.myImage.setImageResource(R.drawable.myImage);
return myLayout.view;
}
}
Now assuming you had an ImageView
declared in your my_layout.xml
file, it will automatically generate myLayout class for you.
Try This:
View v = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView img = (ImageView) v.findViewById(R.id.my_image);
return v;
try
private View myFragmentView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
myFragmentView = inflater.inflate(R.layout.myLayoutId, container, false);
myView = myFragmentView.findViewById(R.id.myIdTag)
return myFragmentView;
}
You can call findViewById()
with the Activity Object you get inside your public void onAttach(Activity activity)
method inside your Fragment.
Save the Activity into a variable for example:
In the Fragment class: private Activity mainActivity;
In the onAttach()
method: this.mainActivity=activity;
Finally execute every findViewById through the vairable: mainActivity.findViewById(R.id.TextView);
There is one more method called onViewCreated.
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ImageView imageView = (ImageView) view.findViewById(R.id.imageview1);
}
Inside onCreateView method
1) first you have to inflate the layout/view you want to add eg. LinearLayout
LinearLayout ll = inflater.inflate(R.layout.testclassfragment, container, false);
2) Then you can find your imageView id from layout
ImageView imageView = (ImageView)ll.findViewById(R.id.my_image);
3)return the inflated layout
return ll;
You have to inflate the view
public class TestClass extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = (ImageView)v.findViewById(R.id.my_image);
return v
}}
In fragments we need a view of that window so that we make a onCreateView of this Fragment.
Then get the view and use it to access each and every view id of that view elements..
class Demo extends Fragment
{
@Override
public View onCreateView(final LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState)
{
View view =inflater.inflate(R.layout.demo_fragment, container,false);
ImageView imageview=(ImageView)view.findViewById(R.id.imageview1);
return view;
}
}
Layout inflater comes into picture here. Layout inflater is a class that make us able to use the XML views in java code. So you can inflate the root xml view in variable v with the following code. And then using v, you can find the child views of the root view v.
public class TestClass extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = (ImageView)v.findViewById(R.id.my_image);
return v;
}
}
The easiest way to use such things is to use butterknife By this you can add as many Onclciklisteners just by @OnClick() as described below:
public class TestClass extends Fragment {
@BindView(R.id.my_image) ImageView imageView;
@OnClick(R.id.my_image)
public void my_image_click(){
yourMethod();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.testclassfragment, container, false);
ButterKnife.bind(getActivity,view);
return view;
}
}
참고URL : https://stackoverflow.com/questions/6495898/findviewbyid-in-fragment
'Programing' 카테고리의 다른 글
Access-Control-Allow-Origin 다중 원본 도메인? (0) | 2020.09.28 |
---|---|
docx, pptx 등에 대한 올바른 MIME 유형은 무엇입니까? (0) | 2020.09.28 |
여러 PDF 파일을 하나의 PDF로 병합 / 변환 (0) | 2020.09.28 |
클릭 가능한 라벨이있는 체크 박스를 만드는 방법은 무엇입니까? (0) | 2020.09.28 |
JSON 데이터를 파일에 어떻게 쓰나요? (0) | 2020.09.28 |