I have a base activity which holds toolbar that I need all over my activities. The toolbar consists of a textView on it. I need to handle click listener on that textView and open my MainActivity. I am not able to achieve it.
Here is my code:
public class BaseActivity extends AppCompatActivity implements View.OnClickListener {
private Toolbar toolbar;
private TextView txtLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.profile_image:
startActivity(new Intent(this, ProfileActivity.class));
break;
case R.id.txtLogin:
startActivity(new Intent(this, LoginActivity.class));
break;
}
}
public void setUpToolbar() {
toolbar = findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
txtLogin = toolbar.findViewById(R.id.txtLogin);
txtLogin.setOnClickListener(this);
}
}
I am calling my setUpToolbar() method from my MainActivity.
Related
I have two activities,one is a MainActivity which has navigation drawer working.The Other is a testActivity which extends from the MainActivity.When I move from the MainActivity to the testActivity the navigation bar appears there but not working when i click there.
I have read too many posts on this like extending navigation drawer activity to other activities but I didnt understand them.
The following is my MainActivity
public class MainActivity extends AppCompatActivity {
private DrawerLayout dl;
private ActionBarDrawerToggle t;
private NavigationView nv;
Button nextBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dl = (DrawerLayout) findViewById(R.id.activity_main);
t = new ActionBarDrawerToggle(this, dl, R.string.Open, R.string.Close);
nextBtn = (Button)findViewById(R.id.nextAct);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,TestActivity.class);
startActivity(intent);
}
});
dl.addDrawerListener(t);
t.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
nv = (NavigationView) findViewById(R.id.nv);
nv.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.account:
Toast.makeText(MainActivity.this, "My Account", Toast.LENGTH_SHORT).show();
break;
case R.id.settings:
Toast.makeText(MainActivity.this, "Settings", Toast.LENGTH_SHORT).show();
break;
case R.id.mycart:
Toast.makeText(MainActivity.this, "My Cart", Toast.LENGTH_SHORT).show();
break;
default:
return true;
}
return true;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(t.onOptionsItemSelected(item))
return true;
return super.onOptionsItemSelected(item);
}
}
The following is the testActivity.
public class TestActivity extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
}
}
The second activity gets the navigation bar as i have extended this from the MainActivity but that is not clickable in this new activity.Can any edit the code so that it will be clickable.
I think that the best way to do this is to use fragments. The navigation drawer + bar stays the same, and you change fragments in the rest of the screen. Hope it helps !
I am trying to launch new activity from intent but it is only working in one case, even though both the activities extend AppCompatActivity. I don't know what the issue is.
the launcher activities are working fine
<manifest>
<activity
android:name=".activities.home_page.HomePageNavActivity"
android:label="#string/title_activity_home_page_nav"
android:theme="#style/AppTheme"
android:windowSoftInputMode="adjustResize" />
<activity
android:name=".activities.UserProfileActivity"
android:parentActivityName=".activities.home_page.HomePageNavActivity"
android:windowSoftInputMode="adjustResize" />
<activity android:name=".activities.ProductDescription"
android:parentActivityName=".activities.home_page.HomePageNavActivity"
android:windowSoftInputMode="adjustResize"/>
MainActivity (HomePageNavActivity)
public class HomePageNavActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page_nav);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
navigation.setSelectedItemId(R.id.navigation_discover);
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment;
switch (item.getItemId()) {
case R.id.navigation_discover:
fragment = new DiscoverFragment();
if(!Constant.currentBottomFragmentSelected.equals("discover") ) {
Constant.currentBottomFragmentSelected = "discover";
loadFragment(fragment);
}
return true;
case R.id.navigation_inbox:
Intent intent=new Intent(HomePageNavActivity.this,ProductDescription.class); //this intent is not working
HomePageNavActivity.this.startActivity(intent);
return true;
case R.id.navigation_profile:
Intent intent1 = new Intent(HomePageNavActivity.this, UserProfileActivity.class); //this intent is working
startActivity(intent1);
return true;
}
return false;
}
};
Activity1 (ProductDescription) (Not working)
public class ProductDescription extends AppCompatActivity {
FloatingActionButton fabLove,fabShare,fabCart;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_description);
}
}
Activity2 (UserProfileActivity) (working)
public class UserProfileActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
utoolbar = (Toolbar) findViewById(R.id.toolbarProfile);
setSupportActionBar(utoolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
imgBtn = findViewById(R.id.imgBtnSettings);
imgBtnLogout = findViewById(R.id.imgBtnLogout);
//remaining code consists of onClickListeners for different buttons
}
}
You have to remove HomePageNavActivity.this.startActivity(intent):
case R.id.navigation_inbox:
Intent intent = new Intent(HomePageNavActivity.this,ProductDescription.class);
startActivity(intent);
return true;
For some reason this activity has the back arrow in the actionbar, but when it is clicked it has no reaction, doesn't even seen to recognize the click. I have other activities that are similar that work fine though. Here is the code with some stuff removed:
public class LanguageActivity extends ActionBarActivity {
private static final String TAG = "LanguageActivity";
#InjectView(R.id.listView)
RecyclerView mRecyclerView;
#State
String selectedLang;
LangViewHolder selectedHolder = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Icepick.restoreInstanceState(this, savedInstanceState);
setContentView(R.layout.recyclerview);
ButterKnife.inject(this);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setTitle(R.string.ad_title_settings_lang);
selectedLang = PreferencesFacade.getInstance().getCurrentLang();
mRecyclerView.setLayoutManager(new TrueWrapContentLinearLayoutManager(this));
List<Pair<String, String>> langList = new LinkedList<>();
langList.add(Constants.Languages.US);
langList.add(Constants.Languages.LATIN_AMERICA_SPANISH);
mRecyclerView.setAdapter(new RecycleViewMappedArrayAdapter(R.layout.view_language_item, new LangViewHolder(mRecyclerView), langList));
}
#Override
protected void onSaveInstanceState(Bundle outState) {
Icepick.saveInstanceState(this, outState);
super.onSaveInstanceState(outState);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void finish() {
super.finish();
PreferencesFacade.getInstance().setCurrentLang(selectedLang);
Log.v(TAG, "Finishing?");
}
public class LangViewHolder extends RecycleViewMappedArrayAdapter.ViewHolder<Pair<String, String>>{
...
}
}
Manifest snippet:
<activity android:name=".activities.LanguageActivity"
android:parentActivityName=".activities.MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".activities.MainActivity"/>
</activity>
This seems to be working for me:
Toolbar tBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(tBar); // sets the Toolbar as the actionbar
tBar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back_white_24dp));
tBar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed(); // calls the System onBackPressed method
}
});
Update:
getDrawable(int id) is depreciated so you should change this line of code:
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= Build.VERSION_CODES.LOLLIPOP){
tBar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back_white_24dp, getApplicationContext().getTheme()));
} else {
tBar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back_white_24dp));
}
why don't You extend AppCompatActivity(i think actionbaractivity is deprecated...)
?
and
Toolbar toolbar = (Toolbar) findViewById(R.id.the_id);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//try this instead
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
My app has a toolbar that should be present on every view. Currently, I do the following in my onCreate() method for each Activity I have:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Does this need to be done in every onCreate() method in every Activity or is there a simpler way? Also, as a side question, how can I implement a "back" feature in the toolbar that takes the user back one action if they click it?
Create a Base class for Activity
public abstract class BaseActivity extends AppCompatActivity {
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResource());
configureToolbar();
}
protected abstract int getLayoutResource();
private void configureToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
FragmentManager fm = getSupportFragmentManager();
if (fm != null && fm.getBackStackEntryCount() > 0) {
fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
} else {
finish();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
And in each Activity extends this BaseActivity to get the ToolBar and implementing the back feature.
At last don't forget to include the ToolBar in each activity layout.
Edit:
Override that method getLayoutResource() in each Activity and pass the layout id.
public class MainActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public int getLayoutResource() {
return R.layout.activity_main;
}
This is my implementation. It removes the need of the getLayoutResources() from the accepted answer and brings back the "setContentView()" in all activities as normal
public abstract class BaseActivity extends AppCompatActivity {
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
protected boolean useToolbar() {
return true;
}
#Override
public void setContentView(int layoutResID) {
View view = getLayoutInflater().inflate(layoutResID, null);
configureToolbar(view);
super.setContentView(view);
}
private void configureToolbar(View view) {
toolbar = (Toolbar) view.findViewById(R.id.toolbar);
if (toolbar != null) {
if (useToolbar()) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} else {
toolbar.setVisibility(View.GONE);
}
}
}
}
From here on you just extend BaseActivity. If you don't want a toolbar you will have to override the useToolbar().
Don't forget to add in activity.xml at the top
<include layout="#layout/toolbar" />
toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</merge>
It depends on your implementation but if you want avoid boilerplate code you should use good programming OO.
An Example using Fragment.
public abstract class FragmentBase extends Fragment {
protected void settingsToolbar(View rootView) {
Toolbar toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
final ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (actionBar != null) {
// TODO add your code and your requirements
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
}
I hope this can give you an idea.
If you have used Activity then Create BaseActivity that extends AppCompatActivity or ActionBarActivity(Deprecated) and move Toolbar code to BaseActivity.
public class BaseActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
}
If you have used Fragment then Create BaseFragment that extends Fragment and move Toolbar code to BaseFragment.
public class BaseFragment extends Fragment {
View main;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
main = inflater.inflate(R.layout.fragment_about, container, false);
Toolbar toolbar = (Toolbar) main.findViewById(R.id.toolbar);
getActivity().setSupportActionBar(toolbar);
return main;
}
}
In main XML layout you have to add Toolbar xml code.
Now in every view(Activity) extends BaseActivity instead of AppCompatActivity or ActionBarActivity so you can get access Toolbar in every view.
public class YourActivity extends BaseActivity{
//your code
}
EDIT1:
main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:theme="#style/toolbarTheme"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/green"
android:minHeight="?attr/actionBarSize" />
</RelativeLayout>
EDIT2:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
add these two lines below setSupportActionBar(toolbar); in BaseActivity.
I hope it helps!
Create a base activity and initialize your tool bar in this class. Now it can be extends to all other child activity.
FirtActivity extends BaseActivity
SecondActivity extends BaseActivity
In base activity toll bar back button click you can check like below mentioned way
if(this instance of FirstActivity){
//do stuff here
}else if(this instance of SecondActivity){
//do stuff here
}
I have a base activity that all of my activities extend from. This class includes basics like a toolbar and a navigation drawer.
I am looking for a solution that will allow me to override a method in extended activities so I can change the type of toolbar that activity will use.
public abstract class BaseActivity extends AppCompatActivity {
private Toolbar mToolbar;
private FrameLayout mContentFrame;
private ActivityFragment mActivityFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(setLayout());
initViews();
initToolbar();
}
protected int setLayout() {
return R.layout.activity_base;
}
//I want to override this and provide a different toolbar layout!
protected int setToolbarLayout(){
return R.layout.toolbar;
}
protected void initViews() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mContentFrame = (FrameLayout) findViewById(R.id.contentFrame);
}
private void initToolbar() {
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mToolbar.setElevation(10f);
}
}
protected void setContentFragment(ActivityFragment fragment) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(getContentFrame().getId(), fragment).commit();
supportInvalidateOptionsMenu();
this.mActivityFragment = fragment;
setTitle(fragment.getTitle(this));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public Toolbar getToolbar() {
return mToolbar;
}
public FrameLayout getContentFrame() {
return mContentFrame;
}
public ActivityFragment getActivityFragment() {
return mActivityFragment;
}
I have tried inflating the toolbar after setContentView() and setting the actionbar to it but it appeared with no icons or widgets!
Ok everyone (whoever it concerns) I figured it out. All I had to do was inflate my contentView prior to calling setContentView(). Once I have that inflated I add the inflated toolbar view!
public abstract class BaseActivity extends AppCompatActivity {
private Toolbar mToolbar;
private FrameLayout mContentFrame;
private ActivityFragment mActivityFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(inflateLayout());
initViews();
initToolbar();
}
protected int getLayoutRes(){
return R.layout.activity_base;
}
protected int getToolbarLayout(){
return R.layout.toolbar;
}
private View inflateLayout() {
View contentView = getLayoutInflater().inflate(getLayoutRes(), null, false);
attachToolbarToLayout(getLayoutInflater(), (ViewGroup) contentView);
return contentView;
}
private void attachToolbarToLayout(LayoutInflater inflater, ViewGroup parent){
mToolbar = (Toolbar) inflater.inflate(getToolbarLayout(),parent,false);
parent.addView(mToolbar,0);
}
protected void initViews() {
mContentFrame = (FrameLayout) findViewById(R.id.contentFrame);
}
private void initToolbar() {
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mToolbar.setElevation(10f);
}
}
protected void setContentFragment(ActivityFragment fragment) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(getContentFrame().getId(), fragment).commit();
supportInvalidateOptionsMenu();
this.mActivityFragment = fragment;
setTitle(fragment.getTitle(this));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public Toolbar getToolbar() {
return mToolbar;
}
public FrameLayout getContentFrame() {
return mContentFrame;
}
public ActivityFragment getActivityFragment() {
return mActivityFragment;
}