LoginSignup
77
66

More than 5 years have passed since last update.

Fragment上のonClickとかをFragment内で受け取る

Posted at

自分用メモ

Fragment使ってタブUIを実装するのはわかったけどそれだと一つのActivityにいくつもFragmentが貼られるとかで。
Android Tips #38 FragmentTabHost を使って Fragment をタブで切り替える
で、tabcontentのfragment上にあるButtonとかをxmlで

sample_fragment.xml
 <Button
        android:id="@+id/loadButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="loadData"
        android:text="@string/Load" >
</Button>

とか置いてあった場合、loadDataはActivityから呼ばれるらしい。

でもそれって気持ち悪い

だって、画面をうまいこと切り替えて使えるFragmentなのにイベント周り?はすべてActivityって。
なによりタブUIなんか作った日には4画面分のイベント処理をすべてActivityにモリモリ書くとか信じられない。
Fragmentでの処理はすべてそっちに書きたい。

調べたら見つけて色々試した。
How to handle button clicks using the xml onClick within Fragments

結果的にはXML上ではonClickは定義しない。
そしてFragment上でUI要素を取得してそれぞれListenerをセットすればよい感じ(タイミングはonStart()でいいのかな?

SampleFragment.java
public class SampleFragment extends Fragment {

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

        return inflater.inflate(R.layout.sample_fragment, container, false);
    }

@Override
    public void onStart() {
       super.onStart();

       Button button = (Button)getActivity().findViewById(R.id.loadButton);
       button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(), "hoge!", Toast.LENGTH_SHORT).show();


            }
        });

    }
}

多分当たり前の事なんだけど雑魚なので結構ハマってしまった。
Android辛い。

77
66
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
77
66