15
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Android】ActionBar内に置いたスイッチを使う(Fragment使用)

Last updated at Posted at 2014-07-11

タイトルどおりです。
#未確認の事項もありますので、あくまで参考としてご覧ください。

PutSwitch.png

・ActionBar内にスイッチを置く
・スイッチのリスナを実装

#1.レイアウト編集
レイアウトに以下の item タグを追加。

menu/main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.putswitch.MainActivity" >

    <item android:id="@+id/action_switch"
          android:title="@string/action_switch"
          android:actionViewClass="android.widget.Switch"
          android:showAsAction="always|withText" />
</menu>

#2.ソース編集
変更点は以下のとおりです。
(必要なパッケージは、適宜importしてください。

MainActivity.java
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//
//        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.main, menu);
//        return true;
//    }
//
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        // Handle action bar item clicks here. The action bar will
//        // automatically handle clicks on the Home/Up button, so long
//        // as you specify a parent activity in AndroidManifest.xml.
//        int id = item.getItemId();
//        if (id == R.id.action_settings) {
//            return true;
//        }
//        return super.onOptionsItemSelected(item);
//    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment implements OnCheckedChangeListener {

        private Switch switchAction;

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container,
                    false);

            setHasOptionsMenu(true);
            return rootView;
        }

        @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            //初めてメニューボタンを押した時に呼ばれる
            inflater.inflate(R.menu.main, menu);

            switchAction = (Switch)menu.findItem(R.id.action_switch).getActionView();
            switchAction.setOnCheckedChangeListener(this);

            super.onCreateOptionsMenu(menu, inflater);
        }

        @Override
        public void onPrepareOptionsMenu(Menu menu){
            //メニューが押されるたびに呼ばれる
            super.onPrepareOptionsMenu(menu);
        }        

        @Override
        public void onResume() {
            super.onResume();
            this.getActivity().invalidateOptionsMenu();
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            //メニューのアイテムが押された時に呼ばれる
            Toast.makeText(getActivity(), "Selected Item: " + item.getTitle(), Toast.LENGTH_SHORT).show();
            return super.onOptionsItemSelected(item);
        }

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            //スイッチが押された時に呼ばれる
            if( isChecked )
            {
                Toast.makeText(getActivity(), "Switch is checked", Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(getActivity(), "Switch is unchecked", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

##1. Activity : onCreateOptionsMenu() と onOptionsItemSelected() をコメントアウト

//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//
//		// Inflate the menu; this adds items to the action bar if it is present.
//		getMenuInflater().inflate(R.menu.main, menu);
//		return true;
//	}
//
//	@Override
//	public boolean onOptionsItemSelected(MenuItem item) {
//		// Handle action bar item clicks here. The action bar will
//		// automatically handle clicks on the Home/Up button, so long
//		// as you specify a parent activity in AndroidManifest.xml.
//		int id = item.getItemId();
//		if (id == R.id.action_settings) {
//			return true;
//		}
//		return super.onOptionsItemSelected(item);
//	}

##2.Fragment : Switchクラスの変数を作成


public static class PlaceholderFragment extends Fragment implements OnCheckedChangeListener {

    Private Switch switchAction;

##3.Fragment : onCreateView() に setHasOptionMenu() を追加

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

    setHasOptionsMenu(true);

##4.Fragment : onCreateOptionsMenu() を追加

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    inflater.inflate(R.menu.main, menu);

    switchAction = (Switch)menu.findItem(R.id.action_switch).getActionView();
    switchAction.setOnCheckedChangeListener(this);

    super.onCreateOptionsMenu(menu, inflater);
}

##5.Fragment : onCheckedChanged() を追加
スイッチがタップされると、ここが呼ばれます。

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

    if( isChecked )
    {
        ...
    }
    else
    {
        ...
    }
}
15
15
0

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
15
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?