2

私の Android アプリには、2 つのフラグメントがあります。1 つのフラグメントには onClickListener があり、本質的に私がやろうとしているのは、ある種のカウンター/ログを作成することです。ボタンがクリックされるたびに、整数を更新してから、 String.valueOf(integer) を別のフラグメントの TextView に渡したいと思います。

onClickListener を使用した最初の Fragment を次に示します。

 public class StartingFragment extends Fragment implements View.OnClickListener {

        public static final String TEA_TYPE_POS = "tea_navdrawer_position";
        public static int COUNT = 0;
        private TeaCounterFragment mTeaCounterFragment;

        // onCreateView method - Returning the layout file
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflating the layout
            View v = inflater.inflate(R.layout.starting_fragment, container, false);


            /* From this point, you do everything in regards to the "v" object */
            Button tea_type1 = (Button) v.findViewById(R.id.tea_type1);
            Button tea_type2 = (Button) v.findViewById(R.id.tea_type2);
            Button tea_type3 = (Button) v.findViewById(R.id.tea_type3);
            Button tea_type4 = (Button) v.findViewById(R.id.tea_type4);
            Button tea_type5 = (Button) v.findViewById(R.id.tea_type5);
            Button tea_type6 = (Button) v.findViewById(R.id.tea_type6);
            Button tea_type7 = (Button) v.findViewById(R.id.tea_type7);
            Button set_timer = (Button) v.findViewById(R.id.set_your_own_timer);




            tea_type1.setText("Oolong");
            tea_type1.setOnClickListener(this);

            tea_type2.setText("White");
            tea_type2.setOnClickListener(this);

            tea_type3.setText("Blooming");
            tea_type3.setOnClickListener(this);

            tea_type4.setText("Black");
            tea_type4.setOnClickListener(this);

            tea_type5.setText("Herbal");
            tea_type5.setOnClickListener(this);

            tea_type6.setText("Green");
            tea_type6.setOnClickListener(this);

            tea_type7.setText("Mate");
            tea_type7.setOnClickListener(this);

            set_timer.setText("Set Your Own Timer");
            set_timer.setOnClickListener(this);

            /* Do your manipulation to your views here, onClick listeners and such */

            // Return the "v" object
            return v;
        }

        @Override
        public void onClick(View view) {
            switch (view.getId()) {
            /*
             * Use the View interface with OnClickListener to get the Button ID's
             * Then you can run a switch on the Buttons (because normally switches
             * cannot be run on buttons
             */

                case R.id.tea_type1:
                    Builder oolongBuilder = new AlertDialog.Builder(StartingFragment.this.getActivity(),
                            AlertDialog.THEME_HOLO_LIGHT);

                    oolongBuilder.setPositiveButton("Hot",
                            //Starts OolongTeaActivity for hot tea when clicked
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface arg0, int arg1) {
                                    Intent i = new Intent(StartingFragment.this.getActivity(),
                                            OolongTeaActivity.class);
                                    StartingFragment.this.getActivity().startActivity(i);
                                }
                            });

                    oolongBuilder.setNeutralButton("Iced",

                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent i = new Intent(StartingFragment.this.getActivity(),
                                            ColdOolongTeaActivity.class);
                                    StartingFragment.this.getActivity().startActivity(i);

                                }
                            });

                    oolongBuilder.setTitle("Oolong Tea");
                    oolongBuilder.setMessage("How Do You Like Your Tea?");

                    AlertDialog oolongDialog = oolongBuilder.create();
                    oolongDialog.show();

                    COUNT++;
                    Fragment fragment = new Fragment();
                    final Bundle bundle = new Bundle();
                    bundle.putString("id_User", String.valueOf(COUNT));
                    Log.i("BUNDLE", bundle.toString());
                    fragment.setArguments(bundle);

                    break;

そして、valueOf(integer) を入れたい Fragment です。

public class TeaCounterFragment extends Fragment {

    public TeaCounterFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_tea_counter, container, false);

        TextView oolongCounterText = (TextView) rootView.findViewById(R.id.counter_tv);

        Bundle args = getArguments();
        if (args  != null && args.containsKey("id_User")){
            String userId = args.getString("id_User");
            oolongCounterText.setText(userId);
        }

        return rootView;
    }

TextView が元の状態に戻ることに気付きましたが、ボタンをクリックした後に少なくとも更新できるようになれば、後で永続的に保存する方法を見つけることができます。

Android 開発者向けドキュメントを確認したところ、2 つの Fragment が直接通信するべきではないと書かれていますが、現在使用している方法が機能しない理由がわかりませ

編集:この問題を解決する別の方法を試みましたが、NullPointerException が発生します。1 つの Fragment でインターフェイスを作成することにし、NavDrawer (MainActivity) クラスを使用して、TextView を更新しようとしました。

pastebin.com/1dx5rEVv (MainActivity) --- pastebin.com/7wKW1zq1 ( StartingFragment)

この時点で、いずれかのアプローチ、またはまだ使用されていないアプローチを使用して、TextView を更新したいだけです (アプリが完全に閉じられた後も保持します)。

4

4 に答える 4

3

フラグメントの親アクティビティで変数を使用して、データを簡単に渡すことができます。その変数を静的にする

public static Bundle myBundle = new Bundle();

最初のフラグメントから次のように更新します

 YourParentActivityName.myBundle.putString("id_User", String.valueOf(COUNT));

2番目のフラグメントでは、この値を次のように取得できます

String myValue = YourParentActivityName.myBundle.get("id_User");
于 2015-01-07T05:19:29.527 に答える
1

「TextView が元の状態に戻る」という問題は、時間の経過とともにボタンがクリックされ、新しいTeaCounterFragment.

最初のフラグメントで、TeaCounterFragment を作成し、onCreate 関数でインスタンス化します。

public class YourFirstFragment extends Fragment {

    private TeaCounterFragment mTeaCounterFragment;

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

        if (savedInstanceState == null) {
            mTeaCounterFragment = new TeaCounterFragment();
            getFragmentManager().beginTransaction()
                    .add(R.id.container, mTeaCounterFragment)
                    .commit();
        }
    }
}

最初のフラグメントの onClick で、これを TeaCounterFragment の目的の更新に追加するだけです。

@Override
public void onClick(View view) {
    ...
    COUNT++;
    mTeaCounterFragment.UpdateCount(COUNT);
    ...
}

TeaCounterFragment で、パブリック関数を作成して UI を更新し、これを使用して onCreateView を変更します。

public class TeaCounterFragment extends Fragment {

    private TextView mTeaCounterText;

    public TeaCounterFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_tea_counter, container, false);
        mTeaCounterText = (TextView) rootView.findViewById(R.id.counter_tv);
        return rootView;
    }

    public void UpdateCount(int count)
    {
        mTeaCounterText.setText(String.valueOf(count));
    }
}

これで問題が解決することを願っています。

于 2015-01-06T06:43:03.037 に答える
0

Fragment Classのオブジェクトを作成しています。TeaCounterFragment クラスを作成する必要があります。

        TeaCounterFragment fragment = new TeaCounterFragment ();
        final Bundle bundle = new Bundle();
        bundle.putString("id_User", String.valueOf(COUNT));
        Log.i("BUNDLE", bundle.toString());
        fragment.setArguments(bundle);

もう 1 つの間違いは、この作成されたフラグメント オブジェクトを使用してビューを表示していないことです。ビューを表示するために同じインスタンスを使用していることを確認してください。

于 2015-01-06T05:30:15.343 に答える
0

onAttachFragment クラスでインターフェイスを定義した後、次のように、フラグメント内のメソッドを使用してアクティビティによってインターフェイスが実装されていることを確認する必要もあります。

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        listener = (updateFragment) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement the interface");
    }
}

次に、アクティビティからフラグメントを更新するには、次のようにします。

@Override
public void onButtonClick(String message) {

TeaCounterFragment fragment = new TeaCounterFragment();
final Bundle bundle = new Bundle();
bundle.putString("id_User", String.valueOf(COUNT));
Log.i("BUNDLE", bundle.toString());
fragment.setArguments(bundle);

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_replace, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
于 2015-01-07T07:35:41.877 に答える