2017-03-07 5 views
1

メインアクティビティのレイアウト(sample_content_fragment)にフラグメント(AnotherFragment)を追加してフラグメントを動的にロードしようとしました。しかし、button1をクリックしても動作しません。ボタンではありません。フラグメントが動作しない

public void onClick(View v) { 
    switch (v.getId()) { 
    case R.id.button1: 
     AnotherFragment fragment = new AnotherFragment(); 
     FragmentManager fragmentManager = getFragmentManager(); 
     FragmentTransaction transaction = fragmentManager.beginTransaction(); 
     transaction.add(R.id.sample_content_fragment, fragment); 
     transaction.commit(); 
     break; 
    } 

そして、ここで、あなたはmainactivityのレイアウトを見ることができます:ここで

<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 

    <fragment 
    android:id="@+id/fregment_test" 
    android:name="com.example.henucmapus.TestFragment" 
    android:layout_width="match_parent" 
    android:layout_height="112dp" /> 

    <FrameLayout 
     android:id="@+id/sample_content_fragment" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
    /> 
    </LinearLayout> 

は私がロードする断片です。ここで

import android.app.Fragment; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 

public class AnotherFragment extends Fragment{ 
public View OnCreateView(LayoutInflater inflater,ViewGroup container, 
      Bundle savedInstanceState){ 
    View view =inflater.inflate(R.layout.anotherfragment,container, false); 

    return view; 
} 
} 

は、フラグメントレイアウトです:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 
    <TextView 
     android:id="@+id/t1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="11111111111" 
     /> 

</LinearLayout> 
+0

を行われて何のフラグメントのトランザクションはありませんが見えますフラグメントの代わりにフラグメントを使用します。 – RScottCarson

答えて

1

OnCreateViewは(少なくともJavaでは、Xamarinは、それが大文字ていない)Androidの面で何の意味もありません。

正しい方法はonCreateViewです。 (小文字のon

注釈を使用した場合、そのことが分かります。

たとえば、あなたが最初の内部コンテンツを交換しようとしているよう

public class AnotherFragment extends Fragment{ 
    @Override 
    public View onCreateView(LayoutInflater inflater,ViewGroup container, 
      Bundle savedInstanceState){ 
     View view = inflater.inflate(R.layout.anotherfragment,container, false); 

     return view; 
    } 
} 

そして、それが動作しない場合、あなたはあなたのメインのレイアウトで何R.id.button1を持っていないように見えるので、とにかく

+0

いいキャッチ..... –

関連する問題