Move to a particular tab of bottom navigation from an activity - android

I am working on a project in which I used Bottom Navigation Bar. On Nav Bar, I used 4 menu items(Profile, Home, Reservation, Logout), for them I used fragment.
Moving to Home, a list of restaurant will be appear. When the user tap on any restaurant from the list, an activity( name ReservationInfo ) will be opened. There are 3 edit text fields and a button in ReservationInfo activity. When the user click on the button it will move to the fragment(Reservation) which is placed on third position of bottom nav bar.
The question is how to move from activity to fragmentand the fragment is set to the 3rd menu item of the bottom navigation bar.
Here is the code:
Resrvation.java
package restaurantlocator.application;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
public class Resrvation extends AppCompatActivity {
Button reserve;
ImageButton imageButton;
EditText food, chooseTime, date;
DataBaseHelper db;
// ReservationInfo reservationInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_resrvation);
db = new DataBaseHelper(this);
food = (EditText) findViewById(R.id.etfood);
chooseTime = (EditText) findViewById(R.id.ettime);
date = (EditText) findViewById(R.id.edate);
reserve = (Button) findViewById(R.id.btnreserve);
imageButton = (ImageButton) findViewById(R.id.imgButton);
imageButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
finish();
}
});
//reservationInfo = new ReservationInfo();
reserve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!emptyValidation()) {
db.AddData(new Data(food.getText().toString(),
chooseTime.getText().toString(),
date.getText().toString()));
AlertMessage();
food.setText(null);
chooseTime.setText(null);
date.setText(null);
} else {
Toast.makeText(Resrvation.this, "Empty Fields", Toast.LENGTH_SHORT).show();
}
}
private void AlertMessage() {
AlertDialog.Builder builder = new AlertDialog.Builder(Resrvation.this);
builder.setTitle("Reserved!");
builder.setMessage("A notification will be send on your device regarding your reservation.");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//move to fragment ReservationInfo
}
});
builder.show();
}
});
}
private boolean emptyValidation() {
if (TextUtils.isEmpty(food.getText().toString()) || TextUtils.isEmpty(chooseTime.getText().toString())) {
return true;
} else {
return false;
}
}
}
BottomNavigation.java
package restaurantlocator.application;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.FrameLayout;
public class BottomNavigation extends AppCompatActivity {
private BottomNavigationView mMianNav;
private FrameLayout mMainFrame;
private HomeActivity homeActivity;
private ReservationInfo reservationInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom_navigation);
startService(new Intent(this, NotificationService.class));
mMainFrame = (FrameLayout) findViewById(R.id.main_frame);
mMianNav = (BottomNavigationView) findViewById(R.id.main_nav);
homeActivity = new HomeActivity();
reservationInfo = new ReservationInfo();
setFragment(homeActivity);
//Listener for handling selection events on bottom navigation items
mMianNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.tohome:
setFragment(homeActivity);
return true;
case R.id.toresrvation:
setFragment(reservationInfo);
return true;
case R.id.tologout:
logout();
return true;
default:
return false;
}
}
private void logout() {
Intent intent = new Intent(BottomNavigation.this, Registration.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
});
}
private void setFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame, fragment);
fragmentTransaction.commit();
fragmentTransaction.addToBackStack(null);
}
public void onBackPressed() {
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_HOME);
homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
finish();
}
}

Solution:
Follow the steps below:
Step1: Add the lines as shown in below reserve click listener
reserve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
....
....
Intent intent = new Intent(Resrvation.this, BottomNavigation.class);
intent.putExtra("FromReservation", "1");
startActivity(intent);
....
}
}
Next, Step2: In your write the below code in onCreate() of BottomNavigation class:
Intent i = getIntent();
String data = i.getStringExtra("FromReservation");
if (data != null && data.contentEquals("1")) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame, new ReservationInfo());
fragmentTransaction.commitNow();
mMianNav.setSelectedItemId(R.id.toresrvation);
}
Try it, If any problem, do comment below.

All you need to do is just use startActivityForResults instead of startActivity when user selects a restaurant from your home fragment.
e.g :
startActivityForResult(yourIntent, 1000);
And on the reservationInfo Activity in the onClick function use
Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();
And then in your first activity override onActivityResult() method and set the selected fragment as reservation if request code matches
e.g:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1000) {
mMianNav.setSelectedItemId(R.id.toresrvation);
}
}

Related

How to add Back Button from an Activity to a Fragment

I'm using a fragment because I used a nav drawer menu. After I click "Category" menu it will take me to "Category" fragment and in that fragment, I have added a floating action bar that will take you to "Add category" activity.
Since fragments can't be viewed in AndroidManifest.xml file, I can't make a fragment as a parent. What I want is to add a "Back Button" from "Add category" activity, display a toast message (If sure to leave without saving changes..etc) and will go back to "Category" fragment.
I have tried using "onBackPressed()" and "getSuppoerActionBar()" that will show a toast but when running the app, the toast message will just show up in a few seconds and will go back to "Category" fragment.
Please help. Thanks!
Here is my code.
CategoriesFragment.java
package com.example.devcash;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class CategoriesFragment extends Fragment {
public CategoriesFragment() {
// 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.fragment_categories, container, false);
//add floating action button
FloatingActionButton categories_fab = view.findViewById(R.id.addcategories_fab);
categories_fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// when add fab is pressed, go to add product activity
Intent addprod = new Intent(getActivity(), AddCategoryActivity.class);
startActivity(addprod);
}
});
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Categories");
}
}
AddCategoryActivity.java
package com.example.devcash;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
public class AddCategoryActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_category);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Unsaved changes");
builder.setMessage("Are you sure you want to leave without saving changes?");
builder.setPositiveButton("LEAVE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
AddCategoryActivity.super.onBackPressed();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.show();
super.onBackPressed();
}
}
You need to remove below code from onBackPressed() as it is calling super class method and eventually destroying activity.
super.onBackPressed();
To handle toolbar back add following code
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// todo: goto back activity from here
onBackPressed();
default:
return super.onOptionsItemSelected(item);
}
}
Your AddCategoryActivity should be like this
public class AddCategoryActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_category);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onBackPressed() {
quitActivity();
}
private void quitActivity() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Unsaved changes");
builder.setMessage("Are you sure you want to leave without saving changes?");
builder.setPositiveButton("LEAVE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
quitActivity();
return true;
} else
return super.onOptionsItemSelected(item);
}
}
you can use EventBus.
class Activity{
fun backToFragment(){
EventBus.postEvent(BackToFragmentEvent())
}
}
class HomeActivity{
EventBus.register{
fragmentmanager.replace(CategoriesFragment)
}
}

Android Main Activity is too slow

I have 9 buttons on my main activity which navigates to particular fragment on clicking. but it is to heavy on main thread. how can reduce the code size. can i use switch instead of defining 9 buttons
here is the main activity code
MainActivity
package com.gowarbaam.baluchistannationalparty;
import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.gowarbaam.baluchistannationalparty.Fragments.AboutApp;
import com.gowarbaam.baluchistannationalparty.Fragments.AboutParty;
import com.gowarbaam.baluchistannationalparty.Fragments.Aims;
import com.gowarbaam.baluchistannationalparty.Fragments.CityList;
import com.gowarbaam.baluchistannationalparty.Fragments.Events;
import com.gowarbaam.baluchistannationalparty.Fragments.History;
import com.gowarbaam.baluchistannationalparty.Fragments.Martyrs;
import com.gowarbaam.baluchistannationalparty.Fragments.TwitterMain;
public class MainActivity extends AppCompatActivity {
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
final Button HistoryBtn = (Button) findViewById(R.id.historyBtn);
HistoryBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new History()).commit();
}
});
final Button AimsBtn = (Button) findViewById(R.id.aimsBtn);
AimsBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new Aims()).commit();
}
});
final Button MembersBtn = (Button) findViewById(R.id.membersBtn);
MembersBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new CityList()).commit();
}
});
final Button PhotoBtn = (Button) findViewById(R.id.martyrsBtn);
PhotoBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new Martyrs()).commit();
}
});
final Button TweetBtn = (Button) findViewById(R.id.tweetsBtn);
TweetBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new TwitterMain()).commit();
}
});
final Button AboutParty = (Button) findViewById(R.id.aboutParty);
AboutParty.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new AboutParty()).commit();
}
});
final Button b = (Button) findViewById(R.id.eventsBtn);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new Events()).commit();
}
});
final Button AboutApp = (Button) findViewById(R.id.aboutApp);
AboutApp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new AboutApp()).commit();
}
});
}
#Override
public void onBackPressed() {
Intent myIntent = new Intent(this, MainActivity.class);
this.startActivity(myIntent);
}
}
One reason why your application might be getting slower is the way you treat the onBackPressed() event. Every time you hit the back press button anywhere in the app you are creating a new MainActivity, but you never finish the previous one and since that's your MainActivity you are pretty much recreating your whole application on every back press.
Your problem doesn't seem to be something due to your activity class, but rather your XML files.
If anything, I would recommend creating an activity for each fragment an put them on it, just for tests. You can see how below.
AboutAppActivity
package com.gowarbaam.baluchistannationalparty;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.gowarbaam.baluchistannationalparty.Fragments.AboutApp;
public class AboutAppActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction()
.replace(R.id.containerView, new AboutApp())
.commit();
}
}
And on your MainActivity
public class MainActivity extends AppCompatActivity {
// This is not for performance, just DRY
private View.OnClickListener btnOnClickListener(final Class activityClass) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), activityClass);
startActivity(i);
}
};
}
#Override
protected void onCreate(Bundle savedInstanceState) {
(...)
final Button AboutApp = (Button) findViewById(R.id.aboutApp);
AboutApp.setOnClickListener(this.btnOnClickListener(AboutAppActivity.class));
}
}

Android:Not able to write on textview of main activity when comming from different activity

I created a simple demo program in which there is start button.When i click on start button on main (Home) screen "hi all" appended to Text view.It works fine, But when I change the activity from selecting action bar menu and if again come on the home screen by selecting the action bar home menu then it will not show the "hi all " Message when I click on the Start button.
package com.example.testdemo;
import android.app.ActionBar.LayoutParams;
import android.content.Intent;
import android.os.Bundle;
import android.app.ActionBar;
import android.app.Activity;
import android.text.method.ScrollingMovementMethod;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView logArea;
private TextView log;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
ActionBar actionBar = getActionBar();
log = new TextView(MainActivity.this);
log.append("Heollosdfsjdf" + "\n");
#SuppressWarnings("deprecation")
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);
params.gravity = Gravity.LEFT;
log.setLayoutParams(params);
log.setGravity(Gravity.CENTER);
LinearLayout chat = (LinearLayout) findViewById(R.id.main_linear_view);
log.setMovementMethod(new ScrollingMovementMethod());
chat.addView(log);
setDefault();
}
public void setDefault(){
Button btn = (Button) findViewById(R.id.start_recording_button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startWriting(v);
}
});
}
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;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
goHome();
return true;
case R.id.general_setting:
generalSetting();
return true;
case R.id.server_settings:
serverSetting();
return true;
case R.id.audio_settings:
audioSetting();
return true;
default:
break;
}
return true;
}
private void goHome() {
Intent i = new Intent(MainActivity.this, home.class);
startActivity(i);
finish();
}
private void generalSetting() {
Intent i = new Intent(MainActivity.this, general.class);
startActivity(i);
finish();
}
private void audioSetting() {
Intent i = new Intent(MainActivity.this, audio.class);
startActivity(i);
finish();
}
private void serverSetting() {
Intent i = new Intent(MainActivity.this, server.class);
startActivity(i);
finish();
}
public void startWriting(View view) {
logMessage("Hi all");
}
private void logMessage(String msg) {
log.append(msg + "\n");
final int scrollAmount = log.getLayout().getLineTop(log.getLineCount())- log.getHeight();
if (scrollAmount > 0)
log.scrollTo(0, scrollAmount);
else
log.scrollTo(0, 0);
}
}
it's because you called 'finish' when you changed activities. calling the main activity again reloads its view to its initial state.
In addition to MetaSnarf's answer: For a deeper understanding of the "Android Task Stack" and saving of the current Activity state, you might want to take a look at http://developer.android.com/guide/components/tasks-and-back-stack.html

setContentView not working when click button

Pease help me with my code.
When i click any button, button1, button2 or button3 opens new activity, but layout is empty, without any text's and others.
Code of activity from calling the new activity:
package com.novator.inweld;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class TentsCatalog extends Activity implements OnClickListener
{
private Button button1;
private Button button2;
private Button button3;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.tents_catalog);
button1 = (Button)findViewById(R.id.button1);
button2 = (Button)findViewById(R.id.button2);
button3 = (Button)findViewById(R.id.button3);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
if(view == button1)
{
Intent intent = new Intent(this, TentPage.class);
intent.putExtra("tentId", "1");
startActivity(intent);
}
if(view == button2)
{
Intent intent = new Intent(this, TentPage.class);
intent.putExtra("tentId", "2");
startActivity(intent);
}
if(view == button3)
{
Intent intent = new Intent(this, TentPage.class);
intent.putExtra("tentId", "3");
startActivity(intent);
}
}
}
Code of my new activity:
package com.novator.inweld;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class TentPage extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent intent= getIntent();
String tentId = intent.getStringExtra("tentId");
if(tentId == "1")
{
setContentView(R.layout.tent1);
}
if(tentId == "2")
{
setContentView(R.layout.tent2);
}
if(tentId == "3")
{
setContentView(R.layout.tent3);
}
}
}
use equals(), not ==
if(tentId.equals("1"))
change onClick method with:
#Override
public void onClick(View v)
{
Intent intent = new Intent(this, TentPage.class);
switch (v.getId()) {
case R.id.button1:
intent.putExtra("tentId", "1");
startActivity(intent);
break;
case R.id.button2:
intent.putExtra("tentId", "2");
startActivity(intent);
break;
case R.id.button3:
intent.putExtra("tentId", "3");
startActivity(intent);
break;
default:
break;
}
and use tentId.equals(""); for String check you must use equals() method and for number value use == like:
if(tentId.equals("1"))
{
setContentView(R.layout.tent1);
}
if(tentId.equals("2"))
{
setContentView(R.layout.tent2);
}
if(tentId.equals("3"))
{
setContentView(R.layout.tent3);
}
Java is a b*%$#ch... Use equals():
if(tentId.equals("1")) ...
Also, according to this answer, Android supports Java 1.7's strings in switch statements, meaning you can rewrite your code in a tidier fashion:
switch(tendId) {
case "1": ...
case "2": ...
case "3": ...
}
Keep in mind that the simplest solution would be to pass tendId as an int and not a string:
intent.putExtra("tendId", 1);
int tendId = intent.getIntExtra("tendId");
Replace your TentPage like:
package com.novator.inweld;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class TentPage extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent intent= getIntent();
String tentId = intent.getStringExtra("tentId");
if(tentId.equals("1"))
{
setContentView(R.layout.tent1);
}
if(tentId.equals("2"))
{
setContentView(R.layout.tent2);
}
if(tentId.equals("3"))
{
setContentView(R.layout.tent3);
}
}
}

Instantiating ImageButtons outside of Activity

Hi Im using several Image buttons that are displayed at the bottom of each activity, and I was wondering if there is any way to instantiate the objects outside of their respective activities Oncreate as they do the same thing in each activity but I do not want to be repeating code..
Any advice would be greatly appreciated thanks.
Marc
at the moment i am receiving a null pointer exception when trying to call the build() function.
Here is my menu where tabs will display at the bottom
package koodoo.hcp.plus;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import koodoo.hcp.utilities.Tabbuilder;
public class Hcp_Menu extends Activity implements OnClickListener {
/**
* Stores all the buttons within the HCP_Menu Activity
*/
ImageButton groupBtn;
ImageButton readingBtn;
ImageButton activityBtn;
ImageButton calendarBtn;
ImageButton ongoingBtn;
Context context = this;
View view = new View(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hcp__menu);
Tabbuilder tb = new Tabbuilder();
tb.build(view, context);
/**
* Create Activity Buttons
*/
//group button
groupBtn = (ImageButton) findViewById(R.id.imageButtonGroup);
groupBtn.setOnClickListener(this);
//reading button
readingBtn = (ImageButton) findViewById(R.id.imageButtonReading);
readingBtn.setOnClickListener(this);
//activity button
activityBtn = (ImageButton) findViewById(R.id.imageButtonActivity);
activityBtn.setOnClickListener(this);
//calendar button
calendarBtn = (ImageButton) findViewById(R.id.imageButtonCalender);
calendarBtn.setOnClickListener(this);
//ongoing button
ongoingBtn = (ImageButton) findViewById(R.id.imageButtonOngoing);
ongoingBtn.setOnClickListener(this);
/**
* create Tab buttons
*//*
//dash tab
dashTab = (ImageButton) findViewById(R.id.dashButton);
dashTab.setOnClickListener(this);
//stats tab
statsTab = (ImageButton) findViewById(R.id.statsButton);
statsTab.setOnClickListener(this);
//invite tab
inviteTab = (ImageButton) findViewById(R.id.inviteButton);
inviteTab.setOnClickListener(this);
//settings tab
settingsTab = (ImageButton) findViewById(R.id.settingsButton);
settingsTab.setOnClickListener(this);
//log tab
logTab = (ImageButton) findViewById(R.id.logButton);
logTab.setOnClickListener(this);*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.hcp__menu, menu);
return true;
}
/**
* onclick function for each button on the Activity.
* #param v
*/
#Override
public void onClick(View v) {
Intent i;
switch (v.getId()){
case R.id.imageButtonGroup: i = new Intent(this, Group.class);
startActivity(i);
break;
case R.id.imageButtonActivity: i = new Intent(this, Activities.class);
startActivity(i);
break;
case R.id.imageButtonCalender: i = new Intent(this, Calender.class);
startActivity(i);
break;
case R.id.imageButtonOngoing: i = new Intent(this, Ongoing.class);
startActivity(i);
break;
case R.id.imageButtonReading: i = new Intent(this, Reading.class);
startActivity(i);
break;
default:
break;
}
}
}
Tabbuilder class
package koodoo.hcp.utilities;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.ImageButton;
import koodoo.hcp.plus.Hcp_Menu;
import koodoo.hcp.plus.Invite;
import koodoo.hcp.plus.Log;
import koodoo.hcp.plus.R;
import koodoo.hcp.plus.Settings;
import koodoo.hcp.plus.Stats;
/**
* Created by Marc Davies on 18/09/2013.
*/
public class Tabbuilder {
ImageButton dashTab;
ImageButton statsTab;
ImageButton inviteTab;
ImageButton settingsTab;
ImageButton logTab;
public void build(View v, final Context context) {
/**
* create Tab buttons
*/
//dash tab
dashTab = (ImageButton) v.findViewById(R.id.dashButton);
dashTab.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(context, Hcp_Menu.class);
}
});
//stats tab
statsTab = (ImageButton) v.findViewById(R.id.statsButton);
statsTab.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(context, Stats.class);
}
});
//invite tab
inviteTab = (ImageButton) v.findViewById(R.id.inviteButton);
inviteTab.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(context, Invite.class);
}
});
//settings tab
settingsTab = (ImageButton) v.findViewById(R.id.settingsButton);
settingsTab.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(context, Settings.class);
}
});
//log tab
logTab = (ImageButton) v.findViewById(R.id.logButton);
logTab.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(context, Log.class);
}
});
}
}
Create a base activity and instantiate buttons in it. Now let other activities inherit the base activity. Dont forget to handle the layouts properly though
you can make a utils class with static initiate Methods.
Those would take a context and an image and return an imageButton. You would still call that in the onCreate of the corresponding Activity, but you wouldnt have to copy paste your code anymore.

Categories

Resources