0

私の持ってFragmentActivityいる 2Fragmentsと. にはがあります。の とを作成する必要があります。のイベントのメソッドを呼び出しました。メソッドは次のとおりです。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 を定義してから と を作成するTextView必要があるためEditView、これらTextViewと EditText をそれらlayoutsに追加してから、そのレイアウトを に追加する必要がありContentViewます。

これは、次の方法で実現できます。

  1. を定義しlayouts、xml でその xml を次のようにコンテンツ ビューに追加します。TextViewEditText

    setContentView(R.layout.fragment_layout_b);
    
  2. または、定義済みのレイアウトを既に取得していて、メソッドを使用してプログラムでレイアウトを取得したい場合はfindViewById()、新しく作成TextViewEditTextたオブジェクトをこのレイアウトに追加します。

TextViewまたはオブジェクトを単に作成EditTextして に表示するためにそのままにしておくことはできません。Fragment Bで使用されるレイアウトにそれらを追加する必要がありますFragment B

さらにヘルプが必要な場合は、メソッドFragment Bのコードを共有してくださいonCreateView()

onCreateView メソッドが表示されたので、tv = new EditText(getActivity().getApplicationContext()); が表示されます。

「tv」は EditText 参照変数であり、テレビがレイアウトに追加されていることがわかりません。したがって、テレビを適切なレイアウトに追加する必要があります。

または、TextView を追加したように、EditText を xml のレイアウトに追加できます。

わかりましたので、レイアウト xml を表示できます。

1. LinearLayout に Android ID を追加します。

  1. コードで LinearLayout lLayout = myFragmentView.findViewById(R.id.lLayout); を使用します。LinearLayout オブジェクトを取得します。

  2. EditText ビュー オブジェクトを LinearLayout オブジェクトに追加します。

    lLayout.addView(テレビ); //tv が EditText オブジェクトの場合

于 2013-03-10T12:48:55.757 に答える