问题描述
我有一个支持的片段活动,它将加载差异片段.该片段有一些 textView
和 id = "score"
并且我想得到它的句柄但是 findViewById
用于 score 的 textView
> 返回空值.为什么会这样?
I have a supported fragment activity which will load diff fragments. The fragment has some textView
with id = "score"
and I want to get its handle but findViewById
for score's textView
returns null. Why so?
textView放置在fragment中
textView is placed in fragment
public class MyActivity extends extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks{
private TextView scoreBoardTextView = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
scoreBoardTextView = (TextView) findViewById(R.id.score); //this returns null
}
@Override
public void onNavigationDrawerItemSelected(int position) {
//set fragment
}
}
推荐答案
注意:
直接访问片段之外的片段视图不是一个好主意.您应该使用片段回调接口来处理这种情况并避免错误.以下方式有效,但不建议这样做,因为这不是一个好的做法.如果您想访问其父 Activity
内的 Fragment
的 TextView
,那么您应该在您的 Fragment
中定义一个方法这样的类:
Note:
Directly accessing fragment's views outside fragment is not a good idea. You should use fragment callback interfaces to handle such cases and avoid bugs. The following way works but it is not recommended as it is not a good practice.
If you want to access the
TextView
of Fragment
inside its parent Activity
then you should define a method inside your Fragment
class like this:public class MyFragment extends Fragment {
TextView mTextView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
mTextView = (TextView) view.findViewById(R.id.textView1);
return view;
}
public void setTextViewText(String value){
mTextView.setText(value);
}
}
现在你可以像这样在你的 Activity
中使用它:
Now you can use this inside your Activity
like this:
myFragment.setTextViewText("foo");
这里的 myFragment 是 MyFragment
类型.
here myFragment is of type MyFragment
.
如果你想访问整个TextView
,那么你可以在MyFragment.java
中定义一个这样的方法:
If you want to access the whole TextView
then you can define a method like this inside MyFragment.java
:
public TextView getTextView1(){
return mTextView;
}
通过这种方式,您可以访问 TextView
本身.
By this you can access the TextView
itself.
希望这有帮助.:)
这篇关于如何在片段的父活动中访问片段的子视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!