2016-11-03 3 views
-2

私は、テキストを変更するためにアクティビティにアクセスする必要があるフラグメントの中にボタンを持っています。私は私のメインの活動でこのコードを使用しています:フラグメントからボタンを初期化する方法

CategoryFragment frag = new CategoryFragment(); 

getSupportFragmentManager().beginTransaction().add(R.id.activity_main, frag).commit(); 

frag.setButtonText(i); 

問題はボタンがnullポインタ例外が発生しonCreateView()メソッド(さえ呼ばれることは決してありませんそのメソッド)を使用して初期化されることはありませんです。私は呼び出されるフラグメントにonCreate()メソッドを追加しようとしましたが、私のボタンを初期化するためにビューを取得する必要があります。ビューはまだ初期化されていないので、ビューから別のNULLポインタ例外が発生します。 onCreate()での私の最大の試みは次のとおりです。

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    button = (Button) getView().findViewById(R.id.buttonFrag); 

} 

答えて

1

あなたは完全に互いに道のフラグメントおよびアクティビティ作業を誤解しています。アクティビティには主にフラグメントを表示する義務があり、CategoryFragmentクラスを使用してボタンを初期化する必要があります。

[上書きCategory FragmentonActivityCreated()し、以下を追加します。

Button button = (Button) getView.findViewById(R.id.your_views_id); 
button.setButton("Voila"); 
0

OnCreateView()では、次のように実行します。

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
    View rootView = inflater.inflate(R.layout.yout_layout, container, false); 
    button = (Button) rootView.findViewById(R.id.buttonFrag); 
    return rootView; 
} 
0

あなたは以下のコード

public class CategoryFragment extends Fragment { 

/** 
* Static factory method that takes an int parameter, 
* initializes the fragment's arguments, and returns the 
* new fragment to the client. 
*/ 
public static CategoryFragment newInstance(String i) { 
    CategoryFragment f = new CategoryFragment(); 
    Bundle args = new Bundle(); 
    args.putInt("buttonText", i); 
    f.setArguments(args); 
    return f; 
} 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    if (getArguments() != null) { 
     mParam = getArguments().getString("buttonText"); 
    } 
} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    // Inflate the layout for this fragment 
    View view=inflater.inflate(R.layout.fragment_category, container, false); 
    Button b=(Button) view.findViewById(R.id.button); 
    b.setText(mParam); 

    return view; 
} 
} 

とあなたの活動からを参照してくださいするだけ

getSupportFragmentManager().beginTransaction().add(R.id.activity_main, CategoryFragment.newInstance(i)).commit(); 
を呼び出す 『staticファクトリメソッド』を使用することができます
関連する問題