S
S
sfilmak2015-06-05 22:18:17
Java
sfilmak, 2015-06-05 22:18:17

How to implement switching between Activities in Navigation Drawer (+ problems after adding it)?

Hello! There are two questions about the Navigation Drawer:
1) How to implement switching between activities in it? I did it according to the instructions from the habr ( instruction ), here is the code of my MainActivity:

public class MainActivity extends ActionBarActivity {
    private final static String FILENAME = "sample.txt"; // имя файла
    private EditText mEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mEditText = (EditText) findViewById(R.id.editText);

   //Сам NaviGation Drawer
        // Handle Toolbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        new Drawer()
                .withActivity(this)
                .withToolbar(toolbar)
                .withActionBarDrawerToggle(true)
                .withHeader(R.layout.drawer_header)
                .addDrawerItems(
                        new PrimaryDrawerItem().withName(R.string.drawer_item_home).withIcon(FontAwesome.Icon.faw_pencil).withIdentifier(1),
                        new PrimaryDrawerItem().withName(R.string.drawer_item_free_play).withIcon(FontAwesome.Icon.faw_book),
                        new PrimaryDrawerItem().withName(R.string.drawer_item_custom).withIcon(FontAwesome.Icon.faw_soundcloud).withIdentifier(2),
                        new SectionDrawerItem().withName(R.string.drawer_item_settings),
                        new SecondaryDrawerItem().withName(R.string.drawer_item_help).withIcon(FontAwesome.Icon.faw_cog),
                        new SecondaryDrawerItem().withName(R.string.drawer_item_open_source).withIcon(FontAwesome.Icon.faw_question).setEnabled(false)

                )
                .build();
   // Конец Navigation Drawer
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {

                case R.id.action_save:
                    saveFile(FILENAME);
                    return true;
                default:
                    return true;
                case R.id.action_settings:
                    Intent intent = new Intent();
                    intent.setClass(this, SettingsActivity.class);
                    startActivity(intent);
                    return true;
            }
        }

    @Override
    public void onResume() {
        super.onResume();
        SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(this);
        // читаем установленное значение из CheckBoxPreference
        if (prefs.getBoolean(getString(R.string.pref_openmode), false)) {
            openFile(FILENAME);
        }
    }

    // Метод для открытия файла
    private void openFile(String fileName) {
        try {
            InputStream inputStream = openFileInput(fileName);

            if (inputStream != null) {
                InputStreamReader isr = new InputStreamReader(inputStream);
                BufferedReader reader = new BufferedReader(isr);
                String line;
                StringBuilder builder = new StringBuilder();

                while ((line = reader.readLine()) != null) {
                    builder.append(line + "\n");
                }

                inputStream.close();
                mEditText.setText(builder.toString());
            }
        } catch (Throwable t) {
            Toast.makeText(getApplicationContext(),
                    "Exception: " + t.toString(), Toast.LENGTH_LONG).show();
        }
    }

    // Метод для сохранения файла
    private void saveFile(String fileName) {
        try {
            OutputStream outputStream = openFileOutput(fileName, 0);
            OutputStreamWriter osw = new OutputStreamWriter(outputStream);
            osw.write(mEditText.getText().toString());
            osw.close();
        } catch (Throwable t) {
            Toast.makeText(getApplicationContext(),
                    "Exception: " + t.toString(), Toast.LENGTH_LONG).show();
        }
    }
}

2) Added Drawer. Before that, there was an EditText with settings. In the end what? Text turned white (only solved with EditText), settings menu too. Plus it went up. How to decide? Screenshot:
9aa9dc68dcfe4307b7fe501d734b6720.png
Code:
Activity_main:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"
    android:textColor="@android:color/black">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        android:minHeight="?attr/actionBarSize"
        android:paddingTop="@dimen/tool_bar_top_padding"
        android:transitionName="actionBar" />


        <EditText
            android:id="@+id/editText"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="top|left"
            android:inputType="textMultiLine"
            android:textColor="@android:color/black"
            android:textStyle="bold"
            android:text="Hello h" />



</LinearLayout>

SettingsActivity:
public class SettingsActivity extends PreferenceActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // загружаем предпочтения из ресурсов
        addPreferencesFromResource(R.xml.preferences);
    }
}

preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <CheckBoxPreference
        android:key="@string/pref_openmode"
        android:summary="Открывать файл при запуске приложения"
        android:title="Открыть"
     />

</PreferenceScreen>

Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Sokolov, 2015-06-11
@retor4i

You need to switch to Fragments. Attach Drawer to the main FragmentActivity and load fragments into it so it will be more correct. Otherwise, when opening a new Activity, you need to somehow pass the Drawer.
If you don't need Drawer in otherActivity then just add OnDrawerItemClickListener;

out.setOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l, IDrawerItem iDrawerItem) {
        Intent intent = new Intent(this, NewActivity.class);
        startActivity(intent);

            }
        });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question