When I select tab 3 my listview appears, yet when I select tab 1 and reselect tab 3, the listview doesn't appear.
Why is this?
https://github.com/jdavey1996/News-Android-App
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Local"));
tabLayout.addTab(tabLayout.newTab().setText("Top rated"));
tabLayout.addTab(tabLayout.newTab().setText("All"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
package com.josh_davey.news_app;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class FragmentAdapter extends FragmentPagerAdapter {
int count;
public FragmentAdapter(FragmentManager fm, int count) {
super(fm);
this.count = count;
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
Fragment1 temp = new Fragment1();
return temp;
case 1:
Fragment2 temp2 = new Fragment2();
return temp2;
case 2:
Fragment3 temp3 = new Fragment3();
return temp3;
}
return null;
}
#Override
public int getCount() {
return count;
}
}
package com.josh_davey.news_app;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment3 extends Fragment {
public Fragment3() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GetData getData = new GetData(getContext(),getActivity());
getData.execute("lincoln");
}
#Override
public void onResume() {
super.onResume();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment3, container, false);
}
}
If you need link to the full code it's on my github. Thanks in advance for any help
https://github.com/jdavey1996/News-Android-App
Default ViewPager's offscreenPageLimit is 1. So the tab3 is detached when tab1 is re-selected. If fragment is detached, Fragment's views are destroyed.
see: ViewPager.setOffscreenPageLimit
So I recommend you to set offscreenPageLimit to 2.
viewPager.setOffscreenPageLimit(2);
Or you can hold the list of ArticleConstructor in Fragment3 like blew.
GetData.java:
public class GetData extends AsyncTask<String, String,ArrayList<ArticleConstructor>>{
Callback callback;
interface Callback {
void onArticleConstructorLoaded(ArrayList<ArticleConstructor> articleConstructors);
}
public GetData(Callback callback) {
this.callback = callback;
}
...
#Override
protected void onPostExecute(ArrayList<ArticleConstructor> result) {
callback.onArticleConstructorLoaded(result);
}
....
}
Fragment3.java:
public class Fragment3 extends Fragment implements GetData.Callback {
private ListView listView;
private ArrayList<ArticleConstructor> articleConstructors = new ArrayList<>();
private ArticleArrayAdapter adapter;
public Fragment3() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment3, container, false);
listView = (ListView) view.findViewById(R.id.listView);
adapter = new ArticleArrayAdapter(getActivity(), getContext(), articleConstructors);
listView.setAdapter(adapter);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (articleConstructors.size() == 0) {
GetData getData = new GetData(this);
getData.execute("lincoln");
}
}
#Override
public void onArticleConstructorLoaded(ArrayList<ArticleConstructor> articleConstructors) {
this.articleConstructors = articleConstructors;
adapter.setArticleConstructors(articleConstructors);
}
}
Related
I am creating a simple app. I am running into one problem to finalize the app.
I am trying onclick image WebView in tabbed view.
However, only the first button opens the scanner. The second button does not do anything.
This is my current code from MainActivity.java:
package in.radioactiveenterprise.watchout;
import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
private static ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
click();
}
public void click()
{
img = (ImageView)findViewById(R.id.imageViewz);
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
Intent intent = new Intent("in.radioactiveenterprise.watchoutt1.Main2Activity");
startActivity(intent);
}
});
};
#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) {
// 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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1)
{
View rootView = inflater.inflate(R.layout.fragment_sub_page01, container, false);
return rootView;
}
else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2)
{
View rootView = inflater.inflate(R.layout.fragment_sub_page02, container, false);
return rootView;
}
else
{
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 3);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "FASTBOOK";
case 1:
return "TIMELINE";
case 2:
return "FARMBOOK";
}
return null;
}
}
}
In Your MainActivity remove below method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
click(); // add this into your Primary onCreate method.
}
Note: You can not use the same method with same Arguments in one class.
you can use bellow method if your activities created with
the attribute android.R.attr.persistableMode.
Same as onCreate(Bundle) but called for those activities created with
the attribute android.R.attr.persistableMode set to
persistAcrossReboots.
persistentState - if the activity is being re-initialized after
previously being shut down or powered off then this Bundle contains
the data it most recently supplied to outPersistentState in
onSaveInstanceState. Note: Otherwise it is null.
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
}
You have 2 onCreate():
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
click();
}
Remove the click() method and add into main onCreate():
REMOVE ALL:
private static ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
click(); //add this on onCreate
}
i have been working on app (Question Answer based) . I have included view pager to swipe the image but it's only swiping same image .
code of class which call a class (where view pager is included in activity)
package com.example.joshiyogesh.puzzle;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class ExerciseOneQuestionList extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exercise_one_question_list);
}
public void questionOne(View view) {
Intent intent = new Intent(getApplicationContext(),ExerciseOneQuestions.class);
intent.putExtra("question_index",0);
startActivity(intent);
}
}
ExerciseOneQuestion.java
package com.example.joshiyogesh.puzzle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class ExerciseOneQuestions extends AppCompatActivity {
ViewPager viewPager;
public int questionIndexReceive;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exercise_one_questions);
questionIndexReceive = getIntent().getIntExtra("question_index",1);
// questionIndexReceive =Integer.parseInt(getIntent().getStringExtra("question_index"));
viewPager = (ViewPager)findViewById(R.id.pager);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
}
}
pager Adapter class
package com.example.joshiyogesh.puzzle;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class PagerAdapter extends FragmentPagerAdapter {
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
position = new ExerciseOneQuestions().questionIndexReceive;
Fragments fragments = new Fragments();
Bundle bundle = new Bundle();
bundle.putInt("question_no",position);
fragments.setArguments(bundle);
return fragments;
}
#Override
public int getCount() {
return 2;
}
}
fragments class
public class Fragments extends Fragment {
ImageView imageView;
#Override
public View onCreateView(LayoutInflater inflater , ViewGroup container ,
Bundle savedInstanceState){
int [] image_index = {R.drawable.eightypageanswer1,R.drawable.eightypageanswer8};
Bundle bundle = getArguments();
int message = bundle.getInt("question_no");
View rootView = inflater.inflate(R.layout.fragments,container,false);
imageView = (ImageView) rootView.findViewById(R.id.imageQuestions);
imageView.setImageResource(image_index[message]);
return rootView;
}
}
for testing purpose I have considered only two images in integer, But its always swiping same image i.e first image.
instead of changing "question_index" in ExerciseOneQuestionList.java
here ...
public void questionOne(View view) {
Intent intent = new Intent(getApplicationContext(),ExerciseOneQuestions.class);
intent.putExtra("question_index",0);
startActivity(intent);
}
couldn't understand why its always showing same image ?
It seems that problem is in line
position = new ExerciseOneQuestions().questionIndexReceive;
It seems that position is always set on the same number.
I really dont know what you are doing with this " new ExerciseOneQuestions().questionIndexReceive;" line. But in standard way you should have make two fragments then add these fragments to your adapter. Rest of thing will be done by adapter , following rough code may help you :
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position); // Which Fragment should be dislpayed by the viewpager for the given position
}
#Override
public int getCount() {
return mFragments.size();
}
}
Make two fragments object in class add them in adapter by calling addFragment method and then setadapter.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I created some tabs with this tutorial (first answer)
But I don't know where should I put my other codes in Tab1Fragment.java!
I'm programming for Android And these are the codes:
MainActivity.java
package com.example.applicationname;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
public class MainActivity extends FragmentActivity {
// Fragment TabHost as mTabHost
private FragmentTabHost mTabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("Tab1"),
Tab1Fragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Tab2"),
Tab2Fragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("tab3").setIndicator("Tab3"),
Tab3Fragment.class, null);
}
}
Tab1Fragment.java
package com.example.applicationname;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Tab1Fragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View V = inflater.inflate(R.layout.tab1_view, container, false);
return V;
}
}
The easiest way to implement tabs is through TabLayout and ViewPager.
MainActivity
This code will come under onStart/onCreate method.
TabLayout tabLay = (TabLayout) findViewById(R.id.tabLayout);
tabLay.addTab(tabLay.newTab().setText("Collections"));
tabLay.addTab(tabLay.newTab().setText("Loyalty"));
tabLay.addTab(tabLay.newTab().setText("Orders"));
viewPager = (ViewPager) findViewById(R.id.userTabs);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLay.getTabCount());
viewPager.setAdapter(adapter);
tabLay.setupWithViewPager(viewPager);
tabLay.getTabAt(0).setText("Collections");
tabLay.getTabAt(0).setIcon(R.drawable.collage);
tabLay.getTabAt(1).setText("Loyalty");
tabLay.getTabAt(1).setIcon(R.drawable.heart_outline);
tabLay.getTabAt(2).setText("Orders");
tabLay.getTabAt(2).setIcon(R.drawable.cart_outline);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLay));
tabLay.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
Pager Adapter
public class PagerAdapter extends FragmentStatePagerAdapter {
public int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = 3;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
CollectionsFragment tab1 = new CollectionsFragment();
return tab1;
case 1:
LoyaltyFragment tab2 = new LoyaltyFragment();
return tab2;
case 2:
OrdersFragment tab3 = new OrdersFragment();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}}
Fragment
public class CollectionsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.frag_collections, container, false);
}
}
This implementation will be similar for every fragment.
This should do it.
Hey guys I need help I'm making a launcher that needs to have a button that when clicked it opens the AllApps.class activity witch shows a list of all installed apps
The other button needs to open a installed app that is on the device
and the last button needs to open the default web browser and open google.com
Here's my code!
Home.java:
package com.dva.schooltoolshome;
import java.util.Locale;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
public class Home extends FragmentActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayOptions(actionBar.getDisplayOptions()
^ ActionBar.DISPLAY_SHOW_TITLE);
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
if (mSectionsPagerAdapter.getPageTitle(i).toString()
.equalsIgnoreCase("calc")) {
actionBar.addTab(actionBar.newTab()
.setIcon(R.drawable.calendar)
.setTabListener(this));
} else if (mSectionsPagerAdapter.getPageTitle(i).toString()
.equalsIgnoreCase("home")) {
actionBar.addTab(actionBar.newTab().setIcon(R.drawable.home)
.setTabListener(this));
} else if (mSectionsPagerAdapter.getPageTitle(i).toString()
.equalsIgnoreCase("drive")) {
actionBar.addTab(actionBar.newTab().setIcon(R.drawable.folder)
.setTabListener(this));
}
}
mViewPager.setCurrentItem(1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_SETTINGS));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new CalcFragment();
break;
case 1:
fragment = new HomeFragment();
break;
case 2:
fragment = new DriveFragment();
break;
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
public static class HomeFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public HomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_homebar,
container, false);
return rootView;
}
}
public static class CalcFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public CalcFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_calculator,
container, false);
return rootView;
}
}
public static class DriveFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public DriveFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home_dummy,
container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText("DRIVE");
return rootView;
}
}
}
activity_homebar
<RelativeLayout 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"
android:background="#drawable/bg"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".HomeBar" >
<ImageButton
android:id="#+id/apps"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#drawable/appdrawer"
android:src="#drawable/appdrawer" />
<ImageButton
android:id="#+id/wbrowser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignTop="#+id/apps"
android:src="#drawable/browser" />
</RelativeLayout>
AllApps.java:
package com.dva.schooltoolshome;
import android.app.LauncherActivity;
import android.content.Intent;
public class AllApps extends LauncherActivity {
#Override
protected Intent getTargetIntent () {
// just a example, you should replace the method yourself
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
}
I'm am still learning so please don't judge
Thanks in advance
Regards
Rapsong11
You can easily find the answer to your question with a bit of googling. It has been asked many times before. I will point you in the right direction.
To add functionality to a button you have to first make the button (view) aware it can be clicked. This can be done in java programatically (research this yourself) or in the xml like so:
android:onClick="onClickDoStuff"
Then you have to implement the onClickDoStuff method which will look like:
public void onClickDoStuff(View view) {
//Do stuff on click
}
You wanted the button to open a new activity onClick to do that you would require an intent have a look here for futher guidance
I'm completely new to android app development and I'm currently working on a project for school.
From my understanding so far, you can use the navigation drawer to swap out UI fragments.
I made a nav drawer that's working properly so far based on the tutorial given here:
https://developer.android.com/training/implementing-navigation/nav-drawer.html
I'm trying to have it switch views for each item that's selected. I made a view pager fragment activity and I want the program to replace the view with my view pager upon selecting the 4th item in the nav drawer (index 3). I added a switch statement in my fragment class to determine which layout to load.
Here's the activity for the nav drawer:
package com.mkge.mkg;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
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;
public class MainActivity extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mTitle;
private String[] mPageTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = getTitle();
mPageTitles = getResources().getStringArray(R.array.nav_draw_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mPageTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(R.string.drawer_open);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) return true;
return super.onOptionsItemSelected(item);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
Fragment fragment = new PageFragment();
Bundle args = new Bundle();
args.putInt(PageFragment.ARG_PAGE_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
setTitle(mPageTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
public static class PageFragment extends Fragment {
public static final String ARG_PAGE_NUMBER = "page_number";
public PageFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
int i = getArguments().getInt(ARG_PAGE_NUMBER);
View rootView;
switch(i) {
case 0:
rootView = inflater.inflate(R.layout.page_home, container, false);
break;
case 1:
rootView = inflater.inflate(R.layout.page_services, container, false);
break;
case 2:
rootView = inflater.inflate(R.layout.page_packages, container, false);
break;
case 3:
View view = new MeetViewPager().getViewPager();
rootView = view;
break;
case 4:
rootView = inflater.inflate(R.layout.page_about, container, false);
break;
case 5:
rootView = inflater.inflate(R.layout.page_contact, container, false);
break;
case 6:
rootView = inflater.inflate(R.layout.page_extras, container, false);
break;
default:
rootView = null;
}
String page = getResources().getStringArray(R.array.nav_draw_array)[i];
getActivity().setTitle(page);
return rootView;
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
I made this fragment activity here to create the view pager. I tried taking the view pager object I made here and passing it to the switch statement to my nav drawer activity.
package com.mkge.mkg;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
#SuppressLint("ValidFragment")
public class MeetViewPager extends FragmentActivity {
public ViewPager mViewPager;
public FragmentPagerAdapter mViewPagerAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.page_meet);
List<Fragment> fragments = getFragments();
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPagerAdapter = new mPageAdapter(getSupportFragmentManager(), fragments);
mViewPager.setAdapter(mViewPagerAdapter);
}
public View getViewPager() {
return mViewPager;
}
private List<Fragment> getFragments() {
List<Fragment> fList = new ArrayList<Fragment>();
Fragment fragment = new mFragment();
Bundle args = new Bundle();
args.putInt("position", 0);
fragment.setArguments(args);
fList.add(fragment);
fragment = new mFragment();
args = new Bundle();
args.putInt("position", 1);
fragment.setArguments(args);
fList.add(fragment);
return fList;
}
private class mPageAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public mPageAdapter(FragmentManager f, List<Fragment> fragments) {
super(f);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
#SuppressLint("ValidFragment")
public static class mFragment extends Fragment {
public mFragment() {
}
public static final mFragment newInstance(int i) {
mFragment f = new mFragment();
Bundle args = new Bundle(1);
args.putInt("position", i);
f.setArguments(args);
return f;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v;
int i = getArguments().getInt("postion");
switch(i) {
case 0:
v = inflater.inflate(R.layout.page_meet_0, container, false);
break;
case 1:
v = inflater.inflate(R.layout.page_meet_1, container, false);
break;
default:
v = null;
}
return v;
}
}
}
Any help would be appreciated thanks.
mViewPager.setCurrentItem(0);
This should be all you need to make your ViewPager change to the first tab.
This would be called from inside your selectItem() method.