如何在Fragment中使用findviewbyid用法

Fragment实例精讲——底部导航栏的实现(方法1)-爱编程
Fragment实例精讲——底部导航栏的实现(方法1)
Android基础入门教程——5.2.1 Fragment实例精讲——底部导航栏的实现(方法1)
标签(空格分隔): Android基础入门教程
本节引言:
在上一节中我们对Fragment进行了一个初步的了解,学习了概念,生命周期,Fragment管理与
Fragment事务,以及动态与静态加载Fragment。从本节开始我们会讲解一些Fragment在实际开发
中的一些实例!而本节给大家讲解的是底部导航栏的实现!而基本的底部导航栏方法有很多种,
比如全用TextView做,或者用RadioButton,又或者使用TabLayout + RadioButton,当然复杂
的情况还是得走外层套布局的方法!本节我们用TextView来做一个底部导航栏的效果,也熟悉
下Fragment的使用!好的,开始本节内容!
1.要实现的效果图以及工程目录结构:
先看看效果图吧:
接着看看我们的工程的目录结构:
2.实现流程:
Step 1:写下底部选项的一些资源文件
我们从图上可以看到,我们底部的每一项点击的时候都有不同的效果是吧!
我们是通过是否selected来判定的!我们要写的资源文件有:首先是图片,然后是文字,接着是背景!
图片Drawable资源:tab_menu_channel.xml
&?xml version="1.0" encoding="utf-8"?&
xmlns:android="/apk/res/android"&
android:drawable="@mipmap/tab_channel_pressed" android:state_selected="true" /&
android:drawable="@mipmap/tab_channel_normal" /& &
其他三个照葫芦画瓢!
文字资源:tab_menu_text.xml
&?xml version="1.0" encoding="utf-8"?&
xmlns:android="/apk/res/android"&
android:color="@color/text_yellow" android:state_selected="true" /&
android:color="@color/text_gray" /& &
背景资源:tab_menu_bg.xml
&?xml version="1.0" encoding="utf-8"?&
xmlns:android="/apk/res/android"&
android:state_selected="true"& &
android:color="#FFC4C4C4" /& & & & &
android:color="@color/transparent" /& & & &
Step 2:编写我们的Activity布局
activity_main.xml:
&RelativeLayout xmlns:android="/apk/res/android" xmlns:tools="/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"&
&RelativeLayout
android:id="@+id/ly_top_bar" android:layout_width="match_parent" android:layout_height="48dp" android:background="@color/bg_topbar"&
android:id="@+id/txt_topbar" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_centerInParent="true" android:gravity="center" android:textSize="18sp" android:textColor="@color/text_topbar" android:text="信息"/&
android:layout_width="match_parent" android:layout_height="2px" android:background="@color/div_white" android:layout_alignParentBottom="true"/&
&/RelativeLayout&
&LinearLayout
android:id="@+id/ly_tab_bar"
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_alignParentBottom="true"
android:background="@color/bg_white"
android:orientation="horizontal"&
android:id="@+id/txt_channel"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/tab_menu_bg"
android:drawablePadding="3dp"
android:drawableTop="@drawable/tab_menu_channel"
android:gravity="center"
android:padding="5dp"
android:text="@string/tab_menu_alert"
android:textColor="@drawable/tab_menu_text"
android:textSize="16sp" /&
android:id="@+id/txt_message"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/tab_menu_bg"
android:drawablePadding="3dp"
android:drawableTop="@drawable/tab_menu_message"
android:gravity="center"
android:padding="5dp"
android:text="@string/tab_menu_profile"
android:textColor="@drawable/tab_menu_text"
android:textSize="16sp" /&
android:id="@+id/txt_better"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/tab_menu_bg"
android:drawablePadding="3dp"
android:drawableTop="@drawable/tab_menu_better"
android:gravity="center"
android:padding="5dp"
android:text="@string/tab_menu_pay"
android:textColor="@drawable/tab_menu_text"
android:textSize="16sp" /&
android:id="@+id/txt_setting"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/tab_menu_bg"
android:drawablePadding="3dp"
android:drawableTop="@drawable/tab_menu_setting"
android:gravity="center"
android:padding="5dp"
android:text="@string/tab_menu_setting"
android:textColor="@drawable/tab_menu_text"
android:textSize="16sp"/&
&/LinearLayout&
android:id="@+id/div_tab_bar"
android:layout_width="match_parent"
android:layout_height="2px"
android:background="@color/div_white"
android:layout_above="@id/ly_tab_bar"/&
&FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/ly_top_bar"
android:layout_above="@id/div_tab_bar"
android:id="@+id/ly_content"&
&/FrameLayout&
&/RelativeLayout&
代码解析:
首先定义顶部标题栏的样式,48dp的LinearLayout中间加上一个TextView作为标题!
接着定义一个大小为56dp的LinerLayout对其底部,在这个里面加入四个TextView,比例1:1:1:1,
并且设置相关属性,接着在这个LinearLayout上加一条线段!
最后以标题栏和底部导航栏为边界,写一个FrameLayout,宽高match_parent,用做Fragment的容器!
PS:这里四个TextView属性是重复的,你也可以自行抽取出来,编写一个style,设置下~
Step 3:隐藏顶部导航栏
意外发现以前的在Activity中调用requestWindowFeature(Window.FEATURE_NO_TITLE);可以隐藏手机
自带顶部导航栏,但是写demo时候发现会报错,即使这句话写在了setContentView()之前!可能是因为
继承的是AppCompatActivity而非Activity类!
当然以前的getSupportActionbar().hide()隐藏掉Actionbar,但是他还是会在界面上!
最后还有一种方法直接在AndroidManifest.xml中为Application设置这个Theme:
接着AndroidManifest.xml设置下theme属性:
android:theme="@style/Theme.AppCompat.NoActionBar"
PS:上述“良心代码”由好程序员曹神赞助~
Step 4:创建一个Fragment的简单布局与类:
fg_content.xml:
&?xml version="1.0" encoding="utf-8"?&
xmlns:android="/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/bg_white"&
android:id="@+id/txt_content" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:text="呵呵" android:textColor="@color/text_yellow" android:textSize="20sp"/& &
MyFragment.java:
* Created by Coder-pig on
*/ public class MyFragment extends Fragment { private S public MyFragment(String content) { this.content =
} @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fg_content,container,false);
TextView txt_content = (TextView) view.findViewById(R.id.txt_content);
txt_content.setText(content); return
代码解析:
就是简单的重写了一个onCreateView()方法,其他方法可以按需重写!
Step 5:编写MainActivity.java
先说说我们要考虑的一些关键问题:
Fragment什么时候初始化和add到容器中?什么时候hide和show?
如何让TextView被选中?选中一个TextView后,要做一些什么操作?
刚进入MainActivity怎么样让一个TextView处于Selected的状态?
嗯,接下来一一解答上面这些问题:
我们选中TextView后对对应的Fragment进行判空,如果为空,初始化,并添加到容器中;
而hide的话,我们定义一个方法hide所有的Fragment,每次触发点击事件就先调用这个hideAll方法,
讲所有Fragment隐藏起来,然后如果TextView对应的Fragment不为空,我们就将这个Fragment显示出来;
这个我们通过点击事件来实现,点击TextView后先重置所有TextView的选中状态为false,然后设置点击的
TextView的选中状态为true;
这个更简单,我们是通过点击事件来设置选中的,那么在onCreate()方法里加个触发点击事件的
方法不就可以了嘛~ txt_channel.performClick();
逻辑都弄懂了,直接上代码咯:
MainActivity.java:
* Created by Coder-pig on
*/ public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private TextView txt_ private TextView txt_ private TextView txt_ private TextView txt_ private TextView txt_ private FrameLayout ly_
private MyFragment fg1,fg2,fg3,fg4; private FragmentManager fM @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
fManager = getFragmentManager();
bindViews();
txt_channel.performClick();
private void bindViews() {
txt_topbar = (TextView) findViewById(R.id.txt_topbar);
txt_channel = (TextView) findViewById(R.id.txt_channel);
txt_message = (TextView) findViewById(R.id.txt_message);
txt_better = (TextView) findViewById(R.id.txt_better);
txt_setting = (TextView) findViewById(R.id.txt_setting);
ly_content = (FrameLayout) findViewById(R.id.ly_content);
txt_channel.setOnClickListener(this);
txt_message.setOnClickListener(this);
txt_better.setOnClickListener(this);
txt_setting.setOnClickListener(this);
private void setSelected(){
txt_channel.setSelected(false);
txt_message.setSelected(false);
txt_better.setSelected(false);
txt_setting.setSelected(false);
private void hideAllFragment(FragmentTransaction fragmentTransaction){ if(fg1 != null)fragmentTransaction.hide(fg1); if(fg2 != null)fragmentTransaction.hide(fg2); if(fg3 != null)fragmentTransaction.hide(fg3); if(fg4 != null)fragmentTransaction.hide(fg4);
} @Override public void onClick(View v) {
FragmentTransaction fTransaction = fManager.beginTransaction();
hideAllFragment(fTransaction); switch (v.getId()){ case R.id.txt_channel:
setSelected();
txt_channel.setSelected(true); if(fg1 == null){
fg1 = new MyFragment("第一个Fragment");
fTransaction.add(R.id.ly_content,fg1);
fTransaction.show(fg1);
} break; case R.id.txt_message:
setSelected();
txt_message.setSelected(true); if(fg2 == null){
fg2 = new MyFragment("第二个Fragment");
fTransaction.add(R.id.ly_content,fg2);
fTransaction.show(fg2);
} break; case R.id.txt_better:
setSelected();
txt_better.setSelected(true); if(fg3 == null){
fg3 = new MyFragment("第三个Fragment");
fTransaction.add(R.id.ly_content,fg3);
fTransaction.show(fg3);
} break; case R.id.txt_setting:
setSelected();
txt_setting.setSelected(true); if(fg4 == null){
fg4 = new MyFragment("第四个Fragment");
fTransaction.add(R.id.ly_content,fg4);
fTransaction.show(fg4);
3.代码下载:
FragmentDemo.zip:
声明:图片素材来自App:better,本代码只做演示,并无用于商业用途!
4.本节小结
本节给大家讲解了如何使用一个LinarLayout + 四个TextView 实现一个底部导航栏以及
Fragment add,hide,show的逻辑~还是蛮简单的,最后要感谢小猪秘密基地的基神,B神,
还有好程序员曹神给我的一些指点!万分感谢,仅以此篇纪念小猪重返装逼界,嗯,重
返应用层,嘿嘿,本节就到这里,谢谢~
版权所有 爱编程 (C) Copyright 2012. . All Rights Reserved.
闽ICP备号-3
微信扫一扫关注爱编程,每天为您推送一篇经典技术文章。今天看啥 热点:
android-The method findViewById(int) is undefined for the type ContactMainFragment报错,androidfragment&
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mTitleNameView = (TextView) findViewById(R.id.ivTitleName);
mTitleNameView.setVisibility(View.VISIBLE);
mTitleNameView.setText(pany_name);
提示:意思应该是提示找不到相应组件而得不到组件ID
解决方法:加上view.即可
mTitleNameView = (TextView) view.findViewById(R.id.ivTitleName);
检查一下你的布局文件里的 myTextView01,这个组件是否正确。从错误信息来看R.id.myTextView01被认为是Object而不是int类型。如果方便可以把你的布局文件贴出来。
主线程可以捕获线程的Message。如果需要在其他线程刷新UI线程,必须要用这种方式通知UI线程去更新。
相关搜索:
相关阅读:
相关频道:
Android教程最近更新android - findViewById in Fragment - Stack Overflow
to customize your list.
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
J it only takes a minute:
Join the Stack Overflow community to:
Ask programming questions
Answer and help your peers
Get recognized for your expertise
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?
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.
23.4k1675110
Use . This will return the root view for the fragment, with this you can call findViewById().
ImageView imageView = (ImageView) getView().findViewById(R.id.foo);
Note: This works only after onCreateView(), So, you can't use this in onCreate().
2,17011125
11.2k32033
You need to inflate the Fragment's view and call findViewById() on the View it returns.
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);
15.8k23103178
8,59432230
Inside Fragment class you will get
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 :
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.yourId).setOnClickListener(this);
getActivity().findViewById(R.id.yourId).setOnClickListener(this);
Always remember in case of Fragment that onViewCreated() method will not called automatically if you are returning null or super.onCreateView() from onCreateView() method.
It will be called by default in case of ListFragment as ListFragment return FrameLayout by default.
Note: you can get the fragment view anywhere in the class by using getView() once onCreateView() has been executed successfully.
getView().findViewById("your view id");
2,87742755
I realise this is an old question, but the prevailing answer leaves something to be desired.
The question is not clear what is required of imageView - are we passing it back as the view, or merely saving a reference for later?
Either way, if the ImageView is coming from the inflated layout, the correct way to do this would be:
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);
Get first the fragment view and then get from this view your 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);
getView() will give the root view
View v = getView().findViewByID(R.id.x);
You can override onViewCreated() which is called right after all views had been inflated. It's the right place to fill in your Fragment's member View variables. Here's an example:
class GalleryFragment extends Fragment {
public void onViewCreated(View view, Bundle savedInstanceState) {
gallery = (Gallery) view.findViewById(R.id.gallery);
gallery.setAdapter(adapter);
super.onViewCreated(view, savedInstanceState);
You could also do it in the onActivityCreated Method.
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Like they do here:
getView().findViewById(R.id.foo);
getActivity().findViewById(R.id.foo);
are possible.
The method getView() wont work on fragments outside OnCreate and similar methods.
You have two ways, pass the view to the function on the oncreate (what means you can only run your functions when the view is being created) or set the view as a variable:
private View rootV
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);
2,87742755
agreed with calling findViewById() on the 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);
2,87742755
EditText name = (EditText) getView().findViewById(R.id.editText1);
EditText add = (EditText) getView().findViewById(R.id.editText2);
2,87742755
Using getView() returns the view of the fragment, then you can call findViewById() to access any view element in the fragment view.
3,059114290
According to the documentation on API level 11
Reference, in Back Stack
short code
* The Fragment's UI is just a simple text view showing its
* instance number.
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));
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
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView nameView = (TextView) view.findViewById(R.id.textview1);
2,87742755
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 :)
imagebutton = (ImageButton) getActivity().findViewById(R.id.imagebutton1);
imageview = (ImageView) getActivity().findViewById(R.id.imageview1);
it will work
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 mainA
In the onAttach() method:
this.mainActivity=
Finally execute every findViewById through the vairable:
mainActivity.findViewById(R.id.TextView);
Use gradle , 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.
Now assuming you had an ImageView declared in your my_layout.xml file, it will automatically generate myLayout class for you.
7,24054095
There is one more method called onViewCreated.
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ImageView imageView = (ImageView) view.findViewById(R.id.imageview1);
2,87742755
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
53.3k10152141
View v = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView img = (ImageView) v.findViewById(R.id.my_image);
2,87742755
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);
private View myFragmentV
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
myFragmentView = inflater.inflate(R.layout.myLayoutId, container, false);
myView = myFragmentView.findViewById(R.id.myIdTag)
return myFragmentV
Timing of transaction after .commit() may also cause this issue
I got the same issue (View in a
Fragment could not be reached). The reason turned out to be, that - immediately after (FragmentTransaction).commit() -, the
View had not been activated in the UI. There is no guarantee when, after .commit(), the tra it's only queued. So I added a (FragmentManager).executePendingTransactions() to force the transaction to be done. After that, referencing the View works as expected !
protected by
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10
on this site (the ).
Would you like to answer one of these
Not the answer you're looking for?
Browse other questions tagged
Stack Overflow works best with JavaScript enabled}

我要回帖

更多关于 findviewbyid报错 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信