Activity innerhalb eines Fragmentes in NavigationsDrawer starten

  • Antworten:3
  • OffenNicht stickyNicht beantwortet
  • Forum-Beiträge: 2

11.03.2015, 21:06:45 via Website

Hallo liebe Community,

Ich habe eine Frage bzw. der Entwicklung einer App.

Ich bastel gerade an einer eigenen App für mich, mit dieser ich für die Prüfung üben kann, nur habe ich ein kleines Problem das Activity der Aufgaben zu starten und zwar:

DIe App hat als MainActivity einen NavigationsDrawer, in diesen die verschiedenen Fächer enthalten sind, den NavigationsDrawer habe ich aber in eine extra Klasse ausgelagert, damit es übersichtlicher bleibt.

In den Navigationsdrawer werden die verschiedenen Fragmente eingetragen, die den Inhalt dann repräsentieren, dieser eine Liste (ListView) ist, mit den Unterkategorien. Wenn der onItemClick-Listener aufgerufen wird, soll die entsprechende neue Activity für die Aufgaben starten, nur genau das klappt nicht, die App stützt ab mit keiner Fehlermeldung, nur

"home/jtschoch/Android/Sdk/tools/emulator -avd Nexus_S_API_18 -netspeed full -netdelay none
emulator: emulator window was out of view and was recentered
setWindowSurfaceColorBuffer: bad color buffer handle 0
setWindowSurfaceColorBuffer: bad color buffer handle 0"


Hier alle Sources:

MainActivity:

package de.jonas.prfungsvorbereitung;

import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;

import de.jonas.prfungsvorbereitung.fragments.overview_math;
import de.jonas.prfungsvorbereitung.fragments.overview_physics;

public class MainActivity extends ActionBarActivity {
/**
* Used to store the last screen title. For use in {@link #restoreActionBar()}.
*/
private CharSequence mTitle;
private NavigationDrawer mNavigationsDrawer;

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

    mNavigationsDrawer = new NavigationDrawer(this);
    mNavigationsDrawer.addEntry(getString(R.string.math), overview_math.class);
    mNavigationsDrawer.addEntry(getString(R.string.physics), overview_physics.class);
    mNavigationsDrawer.createNavigationsView();

    mTitle = getTitle();
}

public void restoreActionBar() {
    ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.setTitle(mTitle);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    if (!this.mNavigationsDrawer.isOpen()) {
        // Only show items in the action bar relevant to this screen
        // if the drawer is not showing. Otherwise, let the drawer
        // decide what to show in the action bar.
        getMenuInflater().inflate(R.menu.main, menu);
        restoreActionBar();
        return true;
    }
    return super.onCreateOptionsMenu(menu);
}

@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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

NavigationDrawer:

package de.jonas.prfungsvorbereitung;

import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class NavigationDrawerFragment extends Fragment {

private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private NavigationDrawerCallbacks mCallbacks;
private ActionBarDrawerToggle mDrawerToggle;

private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;

private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;

public NavigationDrawerFragment() {
}

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

    // Read in the flag indicating whether or not the user has demonstrated awareness of the
    // drawer. See PREF_USER_LEARNED_DRAWER for details.
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
    mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);

    if (savedInstanceState != null) {
        mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
        mFromSavedInstanceState = true;
    }

    // Select either the default item (0) or the last selected item.
    selectItem(mCurrentSelectedPosition);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    // Indicate that this fragment would like to influence the set of actions in the action bar.
    setHasOptionsMenu(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    mDrawerListView = (ListView) inflater.inflate(
            R.layout.fragment_navigation_drawer, container, false);
    mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }
    });

    mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
    return mDrawerListView;
}

public void setArrayList(String[] strings) {
    mDrawerListView.setAdapter(new ArrayAdapter<String>(
            getActionBar().getThemedContext(),
            android.R.layout.simple_list_item_activated_1,
            android.R.id.text1,
            strings
            ));
}
public boolean isDrawerOpen() {
    return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}

/**
 * Users of this fragment must call this method to set up the navigation drawer interactions.
 *
 * @param fragmentId   The android:id of this fragment in its activity's layout.
 * @param drawerLayout The DrawerLayout containing this fragment's UI.
 */
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
    mFragmentContainerView = getActivity().findViewById(fragmentId);
    mDrawerLayout = drawerLayout;

    // set a custom shadow that overlays the main content when the drawer opens
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    // set up the drawer's list view with items and click listener

    ActionBar actionBar = getActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setHomeButtonEnabled(true);

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the navigation drawer and the action bar app icon.
    mDrawerToggle = new ActionBarDrawerToggle(
            getActivity(),                    /* host Activity */
            mDrawerLayout,                    /* DrawerLayout object */
            R.drawable.ic_drawer,             /* nav drawer image to replace 'Up' caret */
            R.string.navigation_drawer_open,  /* "open drawer" description for accessibility */
            R.string.navigation_drawer_close  /* "close drawer" description for accessibility */
    ) {
        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            if (!isAdded()) {
                return;
            }

            getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            if (!isAdded()) {
                return;
            }

            if (!mUserLearnedDrawer) {
                // The user manually opened the drawer; store this flag to prevent auto-showing
                // the navigation drawer automatically in the future.
                mUserLearnedDrawer = true;
                SharedPreferences sp = PreferenceManager
                        .getDefaultSharedPreferences(getActivity());
                sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
            }

            getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
        }
    };

    // If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
    // per the navigation drawer design guidelines.
    if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
        mDrawerLayout.openDrawer(mFragmentContainerView);
    }

    // Defer code dependent on restoration of previous instance state.
    mDrawerLayout.post(new Runnable() {
        @Override
        public void run() {
            mDrawerToggle.syncState();
        }
    });

    mDrawerLayout.setDrawerListener(mDrawerToggle);
}

private void selectItem(int position) {
    mCurrentSelectedPosition = position;
    if (mDrawerListView != null) {
        mDrawerListView.setItemChecked(position, true);
    }
    if (mDrawerLayout != null) {
        mDrawerLayout.closeDrawer(mFragmentContainerView);
    }
    if (mCallbacks != null) {
        mCallbacks.onNavigationDrawerItemSelected(position);
    }
}

public void onAttach(NavigationDrawer navigationDrawer) {
    try {
        mCallbacks = (NavigationDrawerCallbacks) navigationDrawer;
    } catch (ClassCastException e) {
        throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mCallbacks = null;
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Forward the new configuration the drawer toggle component.
    mDrawerToggle.onConfigurationChanged(newConfig);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    // If the drawer is open, show the global app actions in the action bar. See also
    // showGlobalContextActionBar, which controls the top-left area of the action bar.
    if (mDrawerLayout != null && isDrawerOpen()) {
        inflater.inflate(R.menu.global, menu);
        showGlobalContextActionBar();
    }
    super.onCreateOptionsMenu(menu, inflater);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }

    if (item.getItemId() == R.id.action_example) {
        Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
        return true;
    }

    return super.onOptionsItemSelected(item);
}

private void showGlobalContextActionBar() {
    ActionBar actionBar = getActionBar();
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setTitle(R.string.app_name);
}

private ActionBar getActionBar() {
    return ((ActionBarActivity) getActivity()).getSupportActionBar();
}

/**
 * Callbacks interface that all activities using this fragment must implement.
 */
public static interface NavigationDrawerCallbacks {
    /**
     * Called when an item in the navigation drawer is selected.
     */
    void onNavigationDrawerItemSelected(int position);
}

}

Fragment (math)

package de.jonas.prfungsvorbereitung.fragments;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import de.jonas.prfungsvorbereitung.ExercisesList;
import de.jonas.prfungsvorbereitung.MainActivity;
import de.jonas.prfungsvorbereitung.OwnFragment;
import de.jonas.prfungsvorbereitung.R;
import de.jonas.prfungsvorbereitung.exerciese.*;

/**
* Created by jtschoch on 03.01.15.
*/

public class overview_math extends OwnFragment {
private MainActivity mainActivity;

/** UI **/
private ProgressBar mProgress;
private TextView mTextView;

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
}

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    getFragmentManager().beginTransaction();
    this.rootView = inflater.inflate(R.layout.math, container, false);
    this.mainActivity = (MainActivity) getActivity();

    update();
    loadUI((ViewGroup) this.rootView);
    return this.rootView;
}


public void loadUI(ViewGroup rootView) {
    ExercisesList list = new ExercisesList(this.mainActivity, this.getThisFragment(), (ListView) rootView.findViewById(R.id.math_exerciseslist));


    list.addItem(getString(R.string.quadrat), math_quadratnumbers.class);
    list.setup();
}

@Override
public void update() {
    if (this.isResumed()) {
        this.mainActivity = (MainActivity) getActivity();

    }
}

}

ExerciesesList

package de.jonas.prfungsvorbereitung;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class ExercisesList extends Activity implements AdapterView.OnItemClickListener
{
public MainActivity mainActivity;
public Fragment parentFragment = null;
final ArrayList list;
final Map> items = new HashMap>();
final ListView listview;
final Intent exercisesIntent = null;

public ExercisesList(MainActivity mainActivity, Fragment parent, ListView listview) {
    this.mainActivity = mainActivity;
    this.parentFragment = parent;
    this.list = new ArrayList<String>();
    this.listview = listview;
}

public void addItem(String key, Class<?> value) {
    this.items.put(key, value);
    this.list.add(key);
}

public void setup() {
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.mainActivity.getApplicationContext(), R.layout.list_item, this.list);
    this.listview.setAdapter(adapter);

    this.listview.setOnItemClickListener(this);
}

@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id)
{
    Class exerciseActivity = items.get(list.get(position));
    Log.d("CLASS", String.valueOf(list.get(position)));

/*
try {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, (Fragment) exerciseActivity.newInstance()).commit();
}
catch (InstantiationException | IllegalAccessException e1) {

    }

    Intent intent = new Intent(this.getBaseContext(), exerciseActivity);
    Log.d("CLASS", String.valueOf(exerciseActivity));
    //startActivityFromFragment(this.parentFragment, intent, 0);

    startActivity(intent);

    Toast.makeText(mainActivity.getApplicationContext(), "Starting de.jonas.prfungsvorbereitung.IExerciese.Exerciese ...", Toast.LENGTH_SHORT).show();
}

}

Activity (math_quadratnumbers)

package de.jonas.prfungsvorbereitung.exerciese;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;

import de.jonas.prfungsvorbereitung.IExerciese;
import de.jonas.prfungsvorbereitung.R;

/**
* Created by jtschoch on 07.03.15.
*/
public class math_quadratnumbers extends ActionBarActivity implements IExerciese{

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

public void runExerviese() {

}

}

— geändert am 11.03.2015, 21:09:03

Antworten
Pascal P.
  • Mod
  • Blogger
  • Forum-Beiträge: 10.182

11.03.2015, 21:17:58 via App

Hallo,
hast du dafür irgend ein Tutorial benutzt?
Denn dein NavigationDrawer besitzt keine Superklasse von der du onCreateView überschreiben kannst. Somit wird das was da drin steht nie ausgeführt und somit auch nicht angezeigt.
Diese Methode dürfte garnicht existieren. Du brauchst einfach nur Zugiff auf die ListView auf dem Layout und den Drawer selber.

Edit: Vielleicht liest du dich nochmal in das Thema Drawer und Fragments ein. Habe das gefühl dass du das noch nicht recht verstsnden hast.

— geändert am 11.03.2015, 21:19:29

LG Pascal //It's not a bug, it's a feature. :) ;)

Antworten
  • Forum-Beiträge: 1.904

12.03.2015, 07:18:15 via App

Eine Lib, die den ganzen scheiß für dich macht: https://github.com/neokree/MaterialNavigationDrawer Ist super! Benutze ich schon sehr lange. Die Eigenheiten der lib musst du beachten (zb. nur onint und nicht OnCreate in der Main Activity überschreiben)

Wenn dir mein Beitrag gefällt, kannst dich einfach mit dem 👍 "Danke"-Button auf der Website dieses Forums bedanken. 😀

Why Java? - Because I can't C#

Antworten
  • Forum-Beiträge: 2

12.03.2015, 17:32:15 via Website

Doch hat diese, ich habe nur die Datei nicht mit gepostet und nein, ich habe kein Tutorial benutzt.

@Sven R. Danke, ich werde mir das mal anschauen :)

Übrigends Fragment besitzt onCreate, außerdem ging es ja nicht um den NavigationsDrawer, denn dieser funktioniert, mir geht es eher um das Listview, welches in dem SelectionFragment ist, ich meine mit dem Drawer wechselt man nur die einzelnen Fragmente, wie overview_math und in diesen einzelnen Fragmenten befindet sich die Liste (ExerciesesList), in dieser man die Übung auswählen kann und dort soll halt die neue Activity (math_quadratnumbers) gestartet werden, und genau das funktioniert nicht.

Nur als Info: die Activity ist in der Manifest eingetragen, also daran liegt der Fehler nicht.

— geändert am 12.03.2015, 17:52:19

Antworten

Empfohlene Artikel