0

我有FragmentActivity2Fragments和. 里面有一个。的,我需要创建一个和。我已经调用了事件的方法。方法如下:FragmentAfragmentBFragmentAbuttononClickfragmentA buttonTextViewEditTextFragmentBFragmentB onCickFragmentA button

public void updateFragmentB(String t) {
TextView tv = new TextView(getActivity().getApplicationContext());
            tv.setText(t);
}

但它不起作用。

这是我在 FragmentB 中的 onCreate 方法:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View myFragmentView = inflater.inflate(R.layout.fragment_b, container, false);

    b_received = (TextView)myFragmentView.findViewById(R.id.b_received);
    b_received.setText("Wait For the text");
    tv = new EditText(getActivity().getApplicationContext());
    String myTag = getTag();

    ((AndroidViewPagerActivity)getActivity()).setTabFragmentB(myTag);

    return myFragmentView;
}

我的 fragment_b 布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical" >
   <TextView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="It's Fragment B" />
   <TextView
       android:id="@+id/b_received"
       android:layout_width="match_parent"
       android:layout_height="wrap_content" />
   <ImageView
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:scaleType="center"
       android:src="@drawable/ic_launcher"/>
</LinearLayout>
4

1 回答 1

1

因为Fragment B您必须首先定义一个 Layout 然后创建您的TextViewand EditView,然后您必须将这些TextView和 EditText 添加到那些layouts,然后将该布局添加到ContentView.

您可以通过以下方式完成此操作:

  1. 定义您的layouts,TextViewEditText在 xml 中然后将该 xml 添加到您的内容视图中,如下所示

    setContentView(R.layout.fragment_layout_b);
    
  2. 或者,如果您已经定义了布局,并且您希望通过使用该findViewById()方法以编程方式获取布局,然后将新创建的对象TextViewEditText对象添加到此布局中。

您不能只是简单地创建TextViewEditText对象并让它出现在Fragment B您必须将它们添加到Fragment B.

如果您需要进一步的帮助,请Fragment B分享onCreateView()方法代码

现在我可以看到您的 onCreateView 方法,我可以看到 tv = new EditText(getActivity().getApplicationContext());

我假设 'tv' 是一个 EditText 引用变量,我看不到电视被添加到您的布局中。因此,您必须将 tv 添加到适当的布局中。

或者您可以像添加 TextView 一样将 EditText 添加到 xml 中的布局中。

好的所以现在我可以查看你的布局 xml:

1.将android id添加到您的LinearLayout:

  1. 在您的代码中使用 LinearLayout lLayout = myFragmentView.findViewById(R.id.lLayout); 获取 LinearLayout 对象。

  2. 现在将您的 EditText 视图对象添加到您的 LinearLayout 对象:

    lLayout.addView(tv); //如果 tv 是 EditText 对象

于 2013-03-10T12:48:55.757 回答