Problem mit TabHost

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

18.01.2014 20:24:04 via Website

Hallo Leute :) ,

ich bin neu hier - und kenn mich auch noch nicht allzu gut mit Java - Android - Stuff aus...

Aaalso zu meinem Problem:
Ich habe ein Projekt mit NavigationDrawerFragment an der linken Seite und bei einem Item soll ein Fragment geöffnet werden, welches ein TabHost mit TabWidget und ViewPager enthält. Das klappt auch alles wunderbar, wenn ich allerdings dann wieder ein anderes Item aus der Navigation auswähle und wieder zurück zum TabHost wechsele, will das Ganze nicht mehr so funktionieren - die 3 Tabs werden zwar angezeigt, allerdings nicht der Inhalt des Ersten - bei Wechseln auf dritten Tab wird der Inhalt des dritten angezeigt und wenn man wieder zum ersten Tab wechselt auch dessen Inhalt. Der Inhalt des 2. Tabs wird allerdings nicht angezeigt.

Habt ihr irgendeine Idee, woran das liegen könnte?

edit: habe gerade gesehen, dass der Thread in der falschen Kategorie gepostet wurde - kann aber nicht erkennen, wo ich ihn verschieben kann... :(

Hier mal meine Codes:

MainActivity.java:
1package com.example.app;
2
3import android.app.Activity;
4import android.support.v7.app.ActionBarActivity;
5import android.support.v7.app.ActionBar;
6import android.support.v4.app.Fragment;
7import android.support.v4.app.FragmentManager;
8import android.content.Context;
9import android.os.Build;
10import android.os.Bundle;
11import android.view.Gravity;
12import android.view.LayoutInflater;
13import android.view.Menu;
14import android.view.MenuItem;
15import android.view.View;
16import android.view.ViewGroup;
17import android.support.v4.widget.DrawerLayout;
18import android.widget.ArrayAdapter;
19import android.widget.TextView;
20
21public class MainActivity extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks {
22
23 /**
24 * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
25 */
26 private NavigationDrawerFragment mNavigationDrawerFragment;
27
28 /**
29 * Used to store the last screen title. For use in {@link #restoreActionBar()}.
30 */
31 private CharSequence mTitle;
32
33 @Override
34 protected void onCreate(Bundle savedInstanceState) {
35 super.onCreate(savedInstanceState);
36 setContentView(R.layout.activity_main);
37
38 mNavigationDrawerFragment = (NavigationDrawerFragment)
39 getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
40 mTitle = getTitle();
41
42 // Set up the drawer.
43 mNavigationDrawerFragment.setUp(
44 R.id.navigation_drawer,
45 (DrawerLayout) findViewById(R.id.drawer_layout));
46 }
47
48 @Override
49 public void onNavigationDrawerItemSelected(int position) {
50 // update the main content by replacing fragments
51 Fragment fragment = null;
52
53 if(position != 2)
54 fragment = PlaceholderFragment.newInstance(position + 1);
55 else
56 fragment = new TabHostFragment();
57 FragmentManager fragmentManager = getSupportFragmentManager();
58 fragmentManager.beginTransaction()
59 .replace(R.id.container, fragment)
60 .commit();
61 }
62
63 public void onSectionAttached(int number) {
64 switch (number) {
65 case 1:
66 mTitle = getString(R.string.title_section1);
67 break;
68 case 2:
69 mTitle = getString(R.string.title_section2);
70 break;
71 case 3:
72 mTitle = getString(R.string.title_section3);
73 break;
74 }
75 }
76
77 public void restoreActionBar() {
78 ActionBar actionBar = getSupportActionBar();
79 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
80 actionBar.setDisplayShowTitleEnabled(true);
81 actionBar.setTitle(mTitle);
82 }
83
84
85 @Override
86 public boolean onCreateOptionsMenu(Menu menu) {
87 if (!mNavigationDrawerFragment.isDrawerOpen()) {
88 // Only show items in the action bar relevant to this screen
89 // if the drawer is not showing. Otherwise, let the drawer
90 // decide what to show in the action bar.
91 getMenuInflater().inflate(R.menu.main, menu);
92 restoreActionBar();
93 return true;
94 }
95 return super.onCreateOptionsMenu(menu);
96 }
97
98 @Override
99 public boolean onOptionsItemSelected(MenuItem item) {
100 // Handle action bar item clicks here. The action bar will
101 // automatically handle clicks on the Home/Up button, so long
102 // as you specify a parent activity in AndroidManifest.xml.
103 int id = item.getItemId();
104 if (id == R.id.action_settings) {
105 return true;
106 }
107 return super.onOptionsItemSelected(item);
108 }
109
110 /**
111 * A placeholder fragment containing a simple view.
112 */
113 public static class PlaceholderFragment extends Fragment {
114 /**
115 * The fragment argument representing the section number for this
116 * fragment.
117 */
118 private static final String ARG_SECTION_NUMBER = "section_number";
119
120 /**
121 * Returns a new instance of this fragment for the given section
122 * number.
123 */
124 public static PlaceholderFragment newInstance(int sectionNumber) {
125 PlaceholderFragment fragment = new PlaceholderFragment();
126 Bundle args = new Bundle();
127 args.putInt(ARG_SECTION_NUMBER, sectionNumber);
128 fragment.setArguments(args);
129 return fragment;
130 }
131
132 public PlaceholderFragment() {
133 }
134
135 @Override
136 public View onCreateView(LayoutInflater inflater, ViewGroup container,
137 Bundle savedInstanceState) {
138 View rootView = inflater.inflate(R.layout.fragment_main, container, false);
139 TextView textView = (TextView) rootView.findViewById(R.id.section_label);
140 textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
141 return rootView;
142 }
143
144 @Override
145 public void onAttach(Activity activity) {
146 super.onAttach(activity);
147 ((MainActivity) activity).onSectionAttached(
148 getArguments().getInt(ARG_SECTION_NUMBER));
149 }
150 }
151
152}

NavigationDrawerFragment.java:
1package com.example.app;
2
3import android.support.v7.app.ActionBarActivity;;
4import android.app.Activity;
5import android.support.v7.app.ActionBar;
6import android.support.v4.app.Fragment;
7import android.support.v4.app.ActionBarDrawerToggle;
8import android.support.v4.view.GravityCompat;
9import android.support.v4.widget.DrawerLayout;
10import android.content.SharedPreferences;
11import android.content.res.Configuration;
12import android.os.Bundle;
13import android.preference.PreferenceManager;
14import android.view.LayoutInflater;
15import android.view.Menu;
16import android.view.MenuInflater;
17import android.view.MenuItem;
18import android.view.View;
19import android.view.ViewGroup;
20import android.widget.AdapterView;
21import android.widget.ArrayAdapter;
22import android.widget.ListView;
23import android.widget.Toast;
24
25public class NavigationDrawerFragment extends Fragment {
26
27 /**
28 * Remember the position of the selected item.
29 */
30 private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
31
32 /**
33 * Per the design guidelines, you should show the drawer on launch until the user manually
34 * expands it. This shared preference tracks this.
35 */
36 private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
37
38 /**
39 * A pointer to the current callbacks instance (the Activity).
40 */
41 private NavigationDrawerCallbacks mCallbacks;
42
43 /**
44 * Helper component that ties the action bar to the navigation drawer.
45 */
46 private ActionBarDrawerToggle mDrawerToggle;
47
48 private DrawerLayout mDrawerLayout;
49 private ListView mDrawerListView;
50 private View mFragmentContainerView;
51
52 private int mCurrentSelectedPosition = 0;
53 private boolean mFromSavedInstanceState;
54 private boolean mUserLearnedDrawer;
55
56 public NavigationDrawerFragment() {
57 }
58
59 @Override
60 public void onCreate(Bundle savedInstanceState) {
61 super.onCreate(savedInstanceState);
62
63 // Read in the flag indicating whether or not the user has demonstrated awareness of the
64 // drawer. See PREF_USER_LEARNED_DRAWER for details.
65 SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
66 mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
67
68 if (savedInstanceState != null) {
69 mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
70 mFromSavedInstanceState = true;
71 }
72
73 // Select either the default item (0) or the last selected item.
74 selectItem(mCurrentSelectedPosition);
75 }
76
77 @Override
78 public void onActivityCreated (Bundle savedInstanceState) {
79 super.onActivityCreated(savedInstanceState);
80 // Indicate that this fragment would like to influence the set of actions in the action bar.
81 setHasOptionsMenu(true);
82 }
83
84 @Override
85 public View onCreateView(LayoutInflater inflater, ViewGroup container,
86 Bundle savedInstanceState) {
87 mDrawerListView = (ListView) inflater.inflate(
88 R.layout.fragment_navigation_drawer, container, false);
89 mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
90 @Override
91 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
92 selectItem(position);
93 }
94 });
95 mDrawerListView.setAdapter(new ArrayAdapter<String>(
96 getActionBar().getThemedContext(),
97 android.R.layout.simple_list_item_activated_1,
98 android.R.id.text1,
99 new String[]{
100 getString(R.string.title_section1),
101 getString(R.string.title_section2),
102 getString(R.string.title_section3),
103 }));
104 mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
105 return mDrawerListView;
106 }
107
108 public boolean isDrawerOpen() {
109 return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
110 }
111
112 /**
113 * Users of this fragment must call this method to set up the navigation drawer interactions.
114 *
115 * @param fragmentId The android:id of this fragment in its activity's layout.
116 * @param drawerLayout The DrawerLayout containing this fragment's UI.
117 */
118 public void setUp(int fragmentId, DrawerLayout drawerLayout) {
119 mFragmentContainerView = getActivity().findViewById(fragmentId);
120 mDrawerLayout = drawerLayout;
121
122 // set a custom shadow that overlays the main content when the drawer opens
123 mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
124 // set up the drawer's list view with items and click listener
125
126 ActionBar actionBar = getActionBar();
127 actionBar.setDisplayHomeAsUpEnabled(true);
128 actionBar.setHomeButtonEnabled(true);
129
130 // ActionBarDrawerToggle ties together the the proper interactions
131 // between the navigation drawer and the action bar app icon.
132 mDrawerToggle = new ActionBarDrawerToggle(
133 getActivity(), /* host Activity */
134 mDrawerLayout, /* DrawerLayout object */
135 R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
136 R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
137 R.string.navigation_drawer_close /* "close drawer" description for accessibility */
138 ) {
139 @Override
140 public void onDrawerClosed(View drawerView) {
141 super.onDrawerClosed(drawerView);
142 if (!isAdded()) {
143 return;
144 }
145
146 getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
147 }
148
149 @Override
150 public void onDrawerOpened(View drawerView) {
151 super.onDrawerOpened(drawerView);
152 if (!isAdded()) {
153 return;
154 }
155
156 if (!mUserLearnedDrawer) {
157 // The user manually opened the drawer; store this flag to prevent auto-showing
158 // the navigation drawer automatically in the future.
159 mUserLearnedDrawer = true;
160 SharedPreferences sp = PreferenceManager
161 .getDefaultSharedPreferences(getActivity());
162 sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
163 }
164
165 getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
166 }
167 };
168
169 // If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
170 // per the navigation drawer design guidelines.
171 if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
172 mDrawerLayout.openDrawer(mFragmentContainerView);
173 }
174
175 // Defer code dependent on restoration of previous instance state.
176 mDrawerLayout.post(new Runnable() {
177 @Override
178 public void run() {
179 mDrawerToggle.syncState();
180 }
181 });
182
183 mDrawerLayout.setDrawerListener(mDrawerToggle);
184 }
185
186 private void selectItem(int position) {
187 mCurrentSelectedPosition = position;
188 if (mDrawerListView != null) {
189 mDrawerListView.setItemChecked(position, true);
190 }
191 if (mDrawerLayout != null) {
192 mDrawerLayout.closeDrawer(mFragmentContainerView);
193 }
194 if (mCallbacks != null) {
195 mCallbacks.onNavigationDrawerItemSelected(position);
196 }
197 }
198
199 @Override
200 public void onAttach(Activity activity) {
201 super.onAttach(activity);
202 try {
203 mCallbacks = (NavigationDrawerCallbacks) activity;
204 } catch (ClassCastException e) {
205 throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
206 }
207 }
208
209 @Override
210 public void onDetach() {
211 super.onDetach();
212 mCallbacks = null;
213 }
214
215 @Override
216 public void onSaveInstanceState(Bundle outState) {
217 super.onSaveInstanceState(outState);
218 outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
219 }
220
221 @Override
222 public void onConfigurationChanged(Configuration newConfig) {
223 super.onConfigurationChanged(newConfig);
224 // Forward the new configuration the drawer toggle component.
225 mDrawerToggle.onConfigurationChanged(newConfig);
226 }
227
228 @Override
229 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
230 // If the drawer is open, show the global app actions in the action bar. See also
231 // showGlobalContextActionBar, which controls the top-left area of the action bar.
232 if (mDrawerLayout != null && isDrawerOpen()) {
233 inflater.inflate(R.menu.global, menu);
234 showGlobalContextActionBar();
235 }
236 super.onCreateOptionsMenu(menu, inflater);
237 }
238
239 @Override
240 public boolean onOptionsItemSelected(MenuItem item) {
241 if (mDrawerToggle.onOptionsItemSelected(item)) {
242 return true;
243 }
244
245 if (item.getItemId() == R.id.action_example) {
246 Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
247 return true;
248 }
249
250 return super.onOptionsItemSelected(item);
251 }
252
253 /**
254 * Per the navigation drawer design guidelines, updates the action bar to show the global app
255 * 'context', rather than just what's in the current screen.
256 */
257 private void showGlobalContextActionBar() {
258 ActionBar actionBar = getActionBar();
259 actionBar.setDisplayShowTitleEnabled(true);
260 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
261 actionBar.setTitle(R.string.app_name);
262 }
263
264 private ActionBar getActionBar() {
265 return ((ActionBarActivity) getActivity()).getSupportActionBar();
266 }
267
268 /**
269 * Callbacks interface that all activities using this fragment must implement.
270 */
271 public static interface NavigationDrawerCallbacks {
272 /**
273 * Called when an item in the navigation drawer is selected.
274 */
275 void onNavigationDrawerItemSelected(int position);
276 }
277}

TabHostFragment.java
1package com.example.app;
2
3import android.support.v4.app.Fragment;
4import android.os.Bundle;
5import android.support.v4.view.ViewPager;
6import android.view.LayoutInflater;
7import android.view.View;
8import android.view.ViewGroup;
9import android.widget.TabHost;
10
11import java.util.ArrayList;
12import java.util.List;
13
14/**
15 * Created by Michael on 17.01.14.
16 */
17public class TabHostFragment extends Fragment implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
18
19 MyPageAdapter pageAdapter;
20 private ViewPager mViewPager;
21 private TabHost mTabHost;
22
23 @Override
24 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
25 View view = inflater.inflate(R.layout.fragment_tabhost, container, false);
26
27 mViewPager = (ViewPager) view.findViewById(R.id.viewpager);
28
29 // Tab Initialization
30 initialiseTabHost(view);
31
32 // Fragments and ViewPager Initialization
33 List<Fragment> fragments = getFragments();
34 pageAdapter = new MyPageAdapter(getActivity().getSupportFragmentManager(), fragments);
35 mViewPager.setAdapter(pageAdapter);
36 mViewPager.setOnPageChangeListener(this);
37
38 return view;
39 }
40
41 @Override
42 public void onDestroy() {
43 super.onDestroy();
44 }
45
46 // Method to add a TabHost
47 private static void AddTab(MainActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec) {
48 tabSpec.setContent(new MyTabFactory(activity));
49 tabHost.addTab(tabSpec);
50 }
51
52 // Manages the Tab changes, synchronizing it with Pages
53 public void onTabChanged(String tag) {
54 int pos = this.mTabHost.getCurrentTab();
55 this.mViewPager.setCurrentItem(pos);
56 }
57
58 @Override
59 public void onPageScrollStateChanged(int arg0) {
60 }
61
62 // Manages the Page changes, synchronizing it with Tabs
63 @Override
64 public void onPageScrolled(int arg0, float arg1, int arg2) {
65 int pos = this.mViewPager.getCurrentItem();
66 this.mTabHost.setCurrentTab(pos);
67 }
68
69 @Override
70 public void onPageSelected(int arg0) {
71 }
72
73 private List<Fragment> getFragments(){
74 List<Fragment> fList = new ArrayList<Fragment>();
75
76 Fragment f1 = MainActivity.PlaceholderFragment.newInstance(0);
77 Fragment f2 = MainActivity.PlaceholderFragment.newInstance(1);
78 Fragment f3 = MainActivity.PlaceholderFragment.newInstance(2);
79 fList.add(f1);
80 fList.add(f2);
81 fList.add(f3);
82
83 return fList;
84 }
85
86 // Tabs Creation
87 private void initialiseTabHost(View view) {
88 mTabHost = (TabHost) view.findViewById(android.R.id.tabhost);
89 mTabHost.setup();
90
91 // TODO Put here your Tabs
92 AddTab((MainActivity) getActivity(), mTabHost, mTabHost.newTabSpec("Tab1").setIndicator("Tab1"));
93 AddTab((MainActivity) getActivity(), mTabHost, mTabHost.newTabSpec("Tab2").setIndicator("Tab2"));
94 AddTab((MainActivity) getActivity(), mTabHost, mTabHost.newTabSpec("Tab3").setIndicator("Tab3"));
95
96 mTabHost.setOnTabChangedListener(this);
97 }
98}

MyTabFactory.java:
1package com.example.app;
2
3/**
4 * Created by Michael on 17.01.14.
5 */
6import android.content.Context;
7import android.view.View;
8import android.widget.TabHost.TabContentFactory;
9
10public class MyTabFactory implements TabContentFactory {
11
12 private final Context mContext;
13
14 public MyTabFactory(Context context) {
15 mContext = context;
16 }
17
18 public View createTabContent(String tag) {
19 View v = new View(mContext);
20 v.setMinimumWidth(0);
21 v.setMinimumHeight(0);
22 return v;
23 }
24}

MyPageAdapter.java
1package com.example.app;
2
3/**
4 * Created by Michael on 17.01.14.
5 */
6
7import java.util.List;
8import android.support.v4.app.Fragment;
9import android.support.v4.app.FragmentManager;
10import android.support.v4.app.FragmentPagerAdapter;
11
12public class MyPageAdapter extends FragmentPagerAdapter {
13 private List<Fragment> fragments;
14
15 public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
16 super(fm);
17 this.fragments = fragments;
18 }
19
20 @Override
21 public Fragment getItem(int position) {
22 return this.fragments.get(position);
23 }
24
25 @Override
26 public int getCount() {
27 return this.fragments.size();
28 }
29}

fragment_tabhost.xml:
1<LinearLayout xmlns:android="SPAMSCHUTZ://schemas.android.com/apk/res/android"
2 xmlns:tools="SPAMSCHUTZ://schemas.android.com/tools"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent"
5 tools:context=".MainActivity" >
6
7 <TabHost
8 android:id="@android:id/tabhost"
9 android:layout_width="fill_parent"
10 android:layout_height="wrap_content" >
11
12 <LinearLayout
13 android:layout_width="fill_parent"
14 android:layout_height="wrap_content"
15 android:orientation="vertical" >
16
17 <TabWidget
18 android:id="@android:id/tabs"
19 android:orientation="horizontal"
20 android:layout_width="fill_parent"
21 android:layout_height="wrap_content"
22 android:layout_weight="0" />
23
24 <FrameLayout
25 android:id="@android:id/tabcontent"
26 android:layout_width="0dp"
27 android:layout_height="0dp"
28 android:layout_weight="0" />
29
30 <android.support.v4.view.ViewPager
31 android:id="@+id/viewpager"
32 android:layout_width="fill_parent"
33 android:layout_height="wrap_content"
34 android:layout_gravity="bottom" />
35
36 </LinearLayout>
37 </TabHost>
38
39</LinearLayout>

fragment_navigation_drawer.xml, fragment_main.xml und activity_main sind "naturbelassen".

Vielen, vielen Dank für Hilfe!!

— geändert am 18.01.2014 20:28:32

  • Forum-Beiträge: 22.351

10.06.2014 19:09:39 via Website

Hallo Michael,

ich habe deinen Thread mal in unseren Developer-Bereich verschoben...

Bitte sei doch so gut und begrenze deine Infos zuliebe der mobilen Mitleser auf das wesentliche ;)

Viele Grüße,
Andy


OnePlus 3 (Resurrection Remix 5.8.2)
LG G Watch

Regeln | unsere Mods & Admins