0

フラグメント内でボタンなどを操作する必要がありますが、findViewById メソッドが認識されません。さらに、メソッドが認識されないため、警告ダイアログも設定できません。

getActivity() または getActivity().getApplicationContext() を追加すると、フラグメントがバインドされているアクティビティに対して機能します。

オブジェクトを達成し、フラグメント内でそれらを操作する正しい方法は何ですか?

4

3 に答える 3

1

findViewByIdメソッドはActivityクラスから継承されます。Viewフラグメントでは、特定のオブジェクトでこのメソッドを呼び出すことができます。ほとんどの場合、インフレートされたビューで呼び出します。findViewById動作が遅いのでご注意ください!! ビューへの参照をアクティビティ メンバーとして保持することを常にお勧めします。また、最も具体的なViewオブジェクトでこのメソッドを呼び出します。より大きなコンテナーに配置されたコンテナーから View を取得する場合は、より小さなコンテナーでメソッドを呼び出します。より高速です。:)

于 2013-07-05T07:56:31.750 に答える
0

例えば

public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.list_view_fragment, container, false);
    listView = (ListView)v.findViewById(R.id.listView);
    ImageButton imageBtn = (ImageButton)v.findViewById(R.id.imageButton);
    imageBtn.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View arg0) {
            Builder MyAlertDialog = new AlertDialog.Builder(getActivity());
                MyAlertDialog.setTitle("Title");
                MyAlertDialog.setMessage("Message");
                DialogInterface.OnClickListener deleteClick = new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int which) {
                        //your code
                    }
                };
                MyAlertDialog.setPositiveButton("First",deleteClick );
                MyAlertDialog.setNeutralButton("Second",new DialogInterface.OnClickListener()
                     {
                        public void onClick(DialogInterface dialog, int which){ 
                            //second
                        }

                     });
                MyAlertDialog.setNegativeButton("Last",new DialogInterface.OnClickListener()
                     {
                        public void onClick(DialogInterface dialog, int which) {
                            return;
                        }
                     });
                MyAlertDialog.show();

        }
        });
    return v;
}
于 2013-07-05T07:41:34.633 に答える
0

フラグメントの場合、onCreateView メソッドをオーバーライドし、必要なビューをインフレートする必要があります

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.your_fragment_layout, container, false);
        progressBar = (ProgressBar)root.findViewById(R.id.progress_bar);
 }
于 2013-07-05T07:41:46.697 に答える