android - 如何在 Fragment 的父 Activity 中访问 Fragment 的 subview ?

标签 android android-layout

我有一个支持的 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 中访问 FragmentTextView 那么你应该在你的 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/

相关文章:

android - 始终显示一个按钮

android - Firebase 归因跟踪

android - Eclipse 中是否有 "open declaration in layout"的键盘快捷键?

android genymotion vs 模拟器

android - 将 appcompat 更新到 27.1 后,为什么我的 Android 导入语句 (ActionBarActivity) 会出现 'cannot find symbol class' 错误?

android - 如何解决 "Unable to connect to the editor to retrieve text"错误?

android - 当 AppTheme 为半透明时,软键盘与 EditTextPreferenceDialogFragmentCompat 重叠

java.lang.ClassCastException : org. ksoap2.serialization.SoapPrimitive 无法转换为 org.ksoap2.serialization.SoapObject

android - 带圆角的 TextInputLayout

android - 如何逐项显示 ListView 滚动