Android Studio - same menu for all activities (Navigation Drawer) - android-layout

I'm new to Android Studio (and also pretty new to javascrips), so this might be a stupid question.
I do not want to maintain the same code more than once if possible, which is why I am trying to create a navigation-menu, to be used in all my activities.
So far I have created a "BaseActivity" that contains all the functions for my menu. This one works fine.
Now my problem:
In my other activities I can not get it to show up (not without issues anyway). It seems to me like it overwrites the layout.
My base ("BaseActivity"):
public class BaseActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mToggle=new ActionBarDrawerToggle(this, mDrawerLayout, R.string.Open, R.string.Close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
NavigationView NavigationView=(NavigationView)findViewById(R.id.navigation_view);
NavigationView.setNavigationItemSelectedListener(this);
}
#Override
public void setContentView(int layoutResID)
{
super.setContentView(R.layout.activity_base);
ViewGroup content = (ViewGroup) findViewById(R.id.navigation_view);
getLayoutInflater().inflate(layoutResID, content, true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if(id==R.id.nav_Home) {
startActivity(new Intent(this, MainActivity.class));
}
else
if(id==R.id.nav_Activity1) {
startActivity(new Intent(this, Activity1.class));
}
return super.onOptionsItemSelected(item);
}
}
If I change the app to start through this activity the menu works, but the layout seems to be overwritten (it's empty).
When I try to run it normally (MainActivity), I get some issues.
MainActivity:
public class MainActivity extends BaseActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); }}
The menu-icon is there, but I can not click on it.
If I remove the code in my MainActivity it works as before (with the layout problem).
I have tried something like this:
public class MainActivity extends BaseActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ViewGroup content = (ViewGroup) findViewById(R.id.navigation_view);
getLayoutInflater().inflate(R.layout.activity_main, content, true);
}}
Not working well. The layout from MainActivity seems to be implemented in the menu. It looks very strange.
Any ideas how to solve my problem?

Related

Step Counter in Android Studio doesn't count steps

I have a problem with an app I'm trying to develop in Android Studio. I'm trying to develop a step counter using the STEP_COUNTER sensor in a Fragment.I decided to show my results in a TextView ('mStepsSinceReboot'), but it keeps being empty. Do you have any idea on how to make it work?
An hypotesis is that I should use a Service, but online I only found implementations that don't require it.
Thanks in advance for your answer. This is the code of my Fragment.
public class StepFragment extends Fragment implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mStepCounter;
private boolean isSensorPresent;
private TextView mStepsSinceReboot;
public StepFragment() {
// Required empty public constructor
}
public static StepFragment newInstance(String param1, String param2) {
StepFragment fragment = new StepFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v=inflater.inflate(R.layout.fragment_step, container, false);
mStepsSinceReboot=v.findViewById(R.id.stepssincereboot);
mSensorManager=(SensorManager) this.getActivity().getSystemService(getContext().SENSOR_SERVICE);
if (mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)!=null){
mStepCounter=mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
isSensorPresent=true;
}
else{
isSensorPresent=false;
}
return v;
}
#Override
public void onSensorChanged(SensorEvent event) {
mStepsSinceReboot.setText(("Steps since reboot: "+String.valueOf(event.values[0])));
Log.d("Passi", String.valueOf(mStepsSinceReboot));
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onResume(){
super.onResume();
if(isSensorPresent){
mSensorManager.registerListener(this,mStepCounter,SensorManager.SENSOR_DELAY_NORMAL);
}
}
#Override
public void onPause(){
super.onPause();
if(isSensorPresent){
mSensorManager.unregisterListener(this);
}
}
#Override
public void onDestroy(){
super.onDestroy();
mSensorManager=null;
mStepCounter=null;
}
}
you added the permission in the manifest file ?
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION"/>

How to edit a TextView in a fragment from MainActivity

I have a textview in a fragment that I want to edit in MainActivity.java (The parent activity). I've tried many methods such as creating a function in the fragment code:
public class HomeFragment extends Fragment {
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_home, container, false);
return root;
}
public void status(String txt){
TextView textView = getView().findViewById(R.id.status_message);
textView.setText(txt);
}
}
and calling it in MainActivity like so:
public class MainActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HomeFragment fragment = new HomeFragment();
fragment.status("Test");
}
}
But this results in the app crashing. How can I fix this? I am using the Bottom Navigation Activity Template.
Best thing I would advice is to create your fragment instance in your main activity like this:
public class MainActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HomeFragment fragment =
HomeFragment.createInstance("Test");
}
}
And then in your fragment:
public class HomeFragment extends Fragment {
private string text;
public View onCreateView(#NonNull LayoutInflater
inflater, ViewGroup container, Bundle
savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_home,
container, false);
TextView textView =
root.findViewById(R.id.status_message);
return root;
}
public static HomeFragment createInstance(String text)
{
HomeFragment f =new HomeFragment ();
Bundle bundle=new Bundle();
bundle.putString("key", text);
f.set arguments(bundle);
return f;
}
#Override
public void onCreate(#Nullable Bundle
savedInstanceState)
{
super.onCreate(savedInstanceState);
if (getArguments != null) {
text= getArguments.getString("key");
status(text);
}
}
public void status(String txt){
textView.setText(txt);
}
}
Hopes this helps
Fixed this by accessing MainActivity from the fragment rather than accessing Fragment from MainActivity. Instead of changing the textview from MainActivity, send the string you want to put in the textview through a method and change the textview in the fragment.
MainActivity.java
public class MainActivity extends AppCompatActivity{
String text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public String sendData(){
return text;
}
}
HomeFragment.java
public class HomeFragment extends Fragment {
TextView tv;
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_home, container, false);
tv = root.findViewById(R.id.textview);
MainActivity ma = (MainActivity)getActivity();
tv.setText(ma.sendData());
return root;
}
}

setLayout not inflating correct xml layout?

been alright so far. I try to use docs or find my issues.
However my mainActivity has 4 buttons. These buttons depending on which view is clicked passes the R.id.button. I pass this value into an intent which Activity2 uses bundle to get id integer. I then setContentView using this.
However im having issues getting correct view to inflate now, it seems like its loading an old layout. My aim is to inflate 3 separate layout on Activity2 depending which button was clicked.
I know my other other button does inflate another activity and get proper xml layout.
Why are my other 3 buttons not inflating on Activity2 properly?
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button pizza;
Button hamburger;
Button icecream;
Button history;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pizza = findViewById(R.id.buttonPizza);
hamburger = findViewById(R.id.buttonBurger);
icecream = findViewById(R.id.buttonIceCream);
history = findViewById(R.id.buttonHistroy);
pizza.setOnClickListener(this);
hamburger.setOnClickListener(this);
icecream.setOnClickListener(this);
history.setOnClickListener(this);
}
#Override
public void onClick(View v){
int idView = v.getId();
switch(v.getId()) {
case R.id.buttonBurger : startOrderActivity(R.layout.burger_layout);
makeToast(idView);
break;
case R.id.buttonPizza : startOrderActivity(R.layout.pizza_layout);
makeToast(idView);
break;
case R.id.buttonIceCream : startOrderActivity(R.layout.icecream_layout);
makeToast(idView);
break;
case R.id.buttonHistroy : startOrderActivity(R.layout.history_layout);
makeToast(idView);
break;
}
}
private void startOrderActivity(int id){
if(id != R.layout.history_layout) {
Intent intentOrder = new Intent(this, MakeOrderActivity.class);
intentOrder.putExtra("layout", id);
startActivity(intentOrder);
}
else {
Intent intentOrder = new Intent(this, OrderHistoryActivity.class);
intentOrder.putExtra("layout", id);
startActivity(intentOrder);
}
}
public void makeToast(int id){
String txt = String.valueOf(id);
Toast newToast = Toast.makeText(getApplicationContext(),txt,Toast.LENGTH_LONG);
newToast.show();
}
}
public class MakeOrderActivity extends AppCompatActivity {
Button placeOrderButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle data = getIntent().getExtras();
int layoutNum = data.getInt("layout");
setContentView(layoutNum);
placeOrderButton = findViewById(R.id.placeOrder);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.order, menu);
return true;
}
public void onCheckboxClicked(View view){
}
}
Answer is to create a View which is created by getInflator.
https://stackoverflow.com/a/17070408/8443090

How to pass data from activity to fragment?

I'm creating a basic app and i stucked at this point where I'm unable to pass data from an activity to fragment.
EmailPage.java
public class EmailPage extends AppCompatActivity{
ImageButton btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emailpage);
btn = (ImageButton) findViewById(R.id.emailButton);
btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Intent i = new Intent(EmailPage.this, YourName.class);
startActivity(i);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);
}
});
}
}
Email Page
NavHeaderMainMenu1.java
public class NavHeaderMainMenu1 extends Fragment {
public NavHeaderMainMenu1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.nav_header_main_menu1, container , false);
}
}
NavHeaderMainMenu1

ActionBar.Tablistener deprecated

I'm trying to build a swipe tabs view by using fragment activity and actionbar.tablistener. I have referenced other people tutorial and do it, however, it keep on deprecated and do not successful run it. Then I changed to AppComBatActivity and it do not works, show viewgroup error which I don't know why. THen I changed to ActionBarActivity, it worked finally, but no matter how I edit my tab activity, in java class and xml too, it does not show anything.
I have actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS) deprecated as well.
I have attached my code as following...
fragmentmenu.class
public class FragmentMenu extends FragmentActivity implements ActionBar.TabListener {
ActionBar actionBar;
ViewPager viewPager;
FragmentPageAdapter ft;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_menu);
viewPager = (ViewPager)findViewById(R.id.pager);
ft = new FragmentPageAdapter(getSupportFragmentManager());
actionBar = getActionBar();
viewPager.setAdapter(ft);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.addTab(actionBar.newTab().setText("Menu").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Report").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Setting").setTabListener(this));
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
}
</code>
FragmentPagerAdapter
<code>
public class FragmentPageAdapter extends FragmentPagerAdapter {
public FragmentPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new MyActivity();
case 1:
return new Report();
case 2:
return new Setting();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
</code>
One of the fragment
<code>
public class Report extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.report, container, false);
}
}
}}
Please help!
ActionBar.Tablistener is deprecated. You need to use the TabLayout instead.
Check this tutorial for more infos :
http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/

Resources