我有一个支持的 fragment Activity ,它将加载差异 fragment 。该 fragment 有一些带有 id = "score"
的 textView
,我想获得它的句柄,但 findViewById
用于 score 的 textView
返回空值。为什么会这样?
textView放在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
}
}
最佳答案
注意:
在fragment外部直接访问fragment的 View 不是一个好主意。您应该使用 fragment 回调接口(interface)来处理此类情况并避免错误。以下方式有效,但不推荐,因为这不是一个好习惯。
如果你想在其父
Activity
中访问 Fragment
的 TextView
那么你应该在你的 Fragment
中定义一个方法像这样的类:
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
中使用它:
myFragment.setTextViewText("foo");
这里 myFragment 的类型是 MyFragment
。
如果你想访问整个 TextView
那么你可以在 MyFragment.java
中定义这样的方法:
public TextView getTextView1(){
return mTextView;
}
通过这个你可以访问 TextView
本身。
希望这会有所帮助。 :)
关于android - 如何在 Fragment 的父 Activity 中访问 Fragment 的 subview ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24188050/