Tabs > fragments with different layout + actions - java

I'm new to android studio / java language.
I need to set up a pretty straightforward app, but the information I find doesn't let me solve the problem.
Can any of you help :)?
I want to make an app with 3 tabs
(first tab) user enters a decimal number, and after click of a button the result shows a value calculated with the means of a formula
(second tab) same as first tab but with values and formulas
(third tab) information of each formula
I've implemented a (for this use, simplified) code for the first tab.
I know how to code all the three tabs separately, but I don't know how
to merge them together in one app with 3 tabs.
I started with the tabs-template given in android studio, but it demands that every tablayout is the same. I've seen a lot of answers how to have different layouts for each tab, but how do I code the different tabs (e.g. setonclicklistener).
Second problem is that every solution uses android and I have androidx, so the imports won't take. And in dependencies I don't find design V7 or anything of that sort.
Mainactivity.java:
package com.example.soloapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.text.DecimalFormat;
public class MainActivity extends AppCompatActivity {
DecimalFormat numberFormat = new DecimalFormat("#.0");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button calcButton = (Button) findViewById(R.id.calcButton);
calcButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view){
EditText editNum = (EditText) findViewById(R.id.editNum);
TextView resultTextView = (TextView) findViewById(R.id.resultTextView);
double cysC = Double.parseDouble(editNum.getText().toString());
double tempResult = Math.pow(cysC,-0.931);
double resultLong = 70.69 * tempResult;
String result = numberFormat.format(resultLong);
resultTextView.setText(result);
}
});
}
}
activy_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/editNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:ems="10"
android:inputType="numberDecimal"
app:layout_constraintBottom_toTopOf="#+id/resultTextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/resultTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginBottom="168dp"
android:text="Result"
app:layout_constraintBottom_toTopOf="#+id/calcButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/calcButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="200dp"
android:text="CALCULATE"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

I'll add what you need to learn in order to create what you told.
You need to use ViewPager in Android to create swipeable tabs. (If you know WhatsApp, those swipeable three tabs are ViewPager).
You can learn more about ViewPager here.
For using ViewPagers, you need to learn what Fragments are, Fragments in Android are like small activities(but not activities). You embed these Fragments inside your Activities, so you need to put these Fragments inside the Activity that contains your ViewPager.
You can learn about Fragments here.
Although, the first ViewPager link will be sufficient for you to learn everything that you need to learn about creating Swipeable Tabs.
About the second problem that you mentioned.
According to Migrating to AndroidX,
Androidx only maps the original support library API packages into the
androidx namespace.
Basically, they just renamed the package name so that it'd be easy for them to support the updates to libraries.
You can easily find the corresponding androidx package from here.
Migrating to Androidx.

Related

Bottom Navigation Bar pushes down when changing between fragments

In my activity i have a bottom navigation bar and the frame layout to show the fragments everything works fine but the problem is when i start moving from 1 - 4 in sequence the bottom navigation bar stays in its position but when i jump suddenly from 4 to 2 then the bottom navigation bar goes out of screen and when again clicked on the same item then it comes to normal position.
This video will clearly help you get what my problem is Click to watch.
as i guess this is a major problem when considering the UI so kindly help me how can i achieve this. For making things easier i'm posting my codes which contain these elements.
activity_appMain.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AppFragments.AppMain">
<FrameLayout
android:id="#+id/fragments_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/navigation_bar"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/navigation_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="?android:attr/windowBackground"
app:labelVisibilityMode="labeled"
app:menu="#menu/bottom_navigation" />
</RelativeLayout>
AppMain.java
package com.coderedinnovations.allioservices.AppFragments;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.MenuItem;
import android.view.WindowManager;
import com.coderedinnovations.allioservices.AppFragments.FeedbackFragment;
import com.coderedinnovations.allioservices.AppFragments.HomeFragment;
import com.coderedinnovations.allioservices.AppFragments.MyOrdersFragment;
import com.coderedinnovations.allioservices.AppFragments.MyProfileFragment;
import com.coderedinnovations.allioservices.R;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.iid.FirebaseInstanceId;
public class AppMain extends AppCompatActivity {
public void adjustFontScale(Configuration configuration){
configuration.fontScale = (float) 0.9;
DisplayMetrics metrics = getResources().getDisplayMetrics();
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics);
metrics.scaledDensity = configuration.fontScale * metrics.density;
getBaseContext().getResources().updateConfiguration(configuration, metrics);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_main);
adjustFontScale(getResources().getConfiguration());
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
BottomNavigationView bottomNavigationView = findViewById(R.id.navigation_bar);
bottomNavigationView.setOnNavigationItemSelectedListener(navigationItemSelectedListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragments_container, new HomeFragment()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navigationItemSelectedListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()){
case R.id.nav_home:
selectedFragment = new HomeFragment();
break;
case R.id.nav_orders:
selectedFragment = new MyOrdersFragment();
break;
case R.id.nav_feedback:
selectedFragment = new FeedbackFragment();
break;
case R.id.nav_profile:
selectedFragment = new MyProfileFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragments_container,selectedFragment).commit();
return true;
}
};
}
I looked for a similar question like this but none of them have been answered
Edit: Issue only appears when i press from back to front but when i'm going from 1-4 the issue doesn't arise but when i click suddenly from 4 to any other tab the bar gets pushed down.
I really thank everyone's effort for helping me in solving the issue. but somehow i sorted out the problem by my own. In the four fragments one of the fragment I mean the last fragment have the Co-ordinator layout as the parent layout so that what made the bottom bar to push down.
so i solved the issue by taking Constraint layout as the parent layout and added the child into that. thanks for everyone again.
Try this:
1.Add bottom margin 55 dp to framelayout.
2. remove the layout_above from framelayout.
3. add parent top true, center in parent true.
I actually did a layout quite different from yours in a similar enough scenario. Let me modify it and see if this works. In my case instead of a FrameLayout I use a relative layout with a scrollview inside, to allow content of any height. This sets the bottom bar to float at the bottom always.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical">
<FrameLayout
android:id="#+id/fragments_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/navigation_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
app:labelVisibilityMode="labeled"
app:menu="#menu/bottom_navigation" />
</LinearLayout>
In the off chance the frame layout doesn't behave correctly, then wrap it with a relative layout, though I do not think you shall need to.
I'v already watched your video. I copied your code and run it in my workspace, but it works fine. So I actually don't know where the problem lies. Have you consider using ConstraintLayout? I tried to change your xml layout into ConstraintLayout and it also works fine.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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="match_parent">
<FrameLayout
android:id="#+id/fragments_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toTopOf="#id/navigation_bar"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/navigation_bar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:labelVisibilityMode="labeled"
app:menu="#menu/bottom_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>
The constraint of BottomNavigationView to the bottom of parent will make it stay at the bottom. And don't forget to constaint your FrameLayout with BottomNavigationView so that they are not overlayed with each other.
I was facing the same problem. This was mainly because of using coordinatorlayout in the inner screens. Any screen having coordinatorlayout makes the bottom navigation (placed on top) move from its location.
https://stackoverflow.com/a/59844009/13124119 - this answer worked for me also!
In the four fragments one of the fragment I mean the last fragment have the Co-ordinator layout as the parent layout so that what made the bottom bar to push down.
so I solved the issue by taking Constraint layout as the parent layout and added the child into that.
and you have to add the following attributes to Co-ordinator layout.
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"

Cannot find symbol errors in Android Studio Tutorial?

https://developer.android.com/training/basics/firstapp/building-ui.html#Weight
I am doing the tutorial above and to get it to build I had to comment out these lines inside MainActivity.java inside src folder (This code is in the MainActivity class inside OnCreate()).
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
//
// FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
// fab.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
// }
// });
If I do not comment out these lines, I get 'cannot find' errors and can't build, example:
error: cannot find symbol variable toolbar
Can someone explain in plain english why this is happening and how I can fix it? I have tried various import.R fixes that people found to combat Eclipse randomly adding that, but they don't work. My imports:
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
I am using Android Studio like the tutorial says and get the same error on a clean install. Is it my automatically generated imports? Is the tutorial wrong or incompatible with the latest Android Studio? Are my build settings wrong?
The R class is auto-generated based on what is in your *.xml files, whether they are strings, dimensions, colors, ids within layouts, etc.
When you are calling code like this:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
You are saying, "Set the toolbar variable to the widget with an id of toolbar".
In an xml, say you had three textviews like this:
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/text_view_1" />
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/text_view_2" />
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/text_view_3" />
When I build the project, my R.java file will then be updated to have references in java code to those ids that I defined in xml, like this:
public static final int text_view_1=0x7f0c0066;
public static final int text_view_2=0x7f0c0067;
public static final int text_view_3=0x7f0c0068;
To explain it at a very basic level, the R.java file is java code that is generated to reference xml elements within actual java code.
I am guessing that when you created a project in Android Studio, it came with the MainActivity.java class. That's where that code is coming from that you posted above. The part right above that in the default MainActivity.java class is
setContentView(R.layout.activity_main);
This is setting the activity's view to the xml layout file defined in activity_main.xml. Inside of this layout is the following
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="#style/AppTheme.AppBarOverlay"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
My guess is that perhaps your activity_main.xml does not contain this definition for the Toolbar and the FloatingActionButton widget.
If you want to really start from scratch so that you can follow the tutorial you linked, you should delete the MainActivity.java and just go create your own.
I know this is old, but I'm going to answer because this tutorial is still the best for android studios, and it poorly explains this part.
OnCreate() creates the elements you define in XML in Java, by creating the default activity, you still have a
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
and a
fab.setOnClickListener(new View.OnClickListener()
defined in OnCreate, android studios as not created these resources in android.R because you deleted there definitions in XML as part of the tutorial!
Run>Clean and Rerun'app' or ctrl+F5 on Android Studio

Android, ActionBar hiding other widgets

Disclaimer: It's build with CLI only tools, so certainly some "auto-generated lines" are missing
It's a small application with a MainActivity with a EditText and a Button
It works fine, but if I extends now from ActionBarActivity now my EditText and Button are hidden behind the Action Bar
https://developer.android.com/guide/topics/ui/actionbar.html The android documentation does not state about changes needing to be made in the layout.xml nor does the Training guide from which my application is based on
My MainActivity.java
public class MainActivity extends ActionBarActivity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// adding these lines show that the widget are correctly added
//ActionBar actionBar = getSupportActionBar();
//actionBar.hide();
}
}
My main layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText
android:id="#+id/enter_verb"
android:hint="#string/enter_verb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Button
android:text="#string/button_conjugate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
My guess would be that I need to add something in my layout to make it aware there's a Action Bar, but I can't find anywhere what it should be.
Very strange, I've added the line coming from this link
https://developer.android.com/training/basics/actionbar/overlaying.html
Which is:
android:paddingTop="?attr/actionBarSize"
in my LinearLayout tag, and then recompiled, after that the widget were shown but with a padding of the size of the actionBar in addition to the actionBar itself.
I then removed the line, recompiled and it now works as expected
A bug because of temporary files?

Eclipse Android; Bitmap to large: OutOfMemory?

My app is like a photo Album. In every activity is one picture and I can go from one activtiy to the next over a button. The pictures I use are 640x480 and not bigger than 150KB. But very often the app stops working because of an OutOfMemory-Error. Probably are the Bitmaps too large. What do I have to add into my code to add large Bitmaps efficently? Momentarily I even didn't define the Bitmaps in my Java-Code. They are only in XML-Code. I probably have to write s.th in my Java-Code. But what?
package com.example.xxx;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class PictureOne extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.pictureone);}
public void Picture0 (View view){
Intent i = new Intent(this, PageZero.class);
startActivity(i);}}
public void Picture2 (View view){
Intent i = new Intent(this, PageTwo.class);
startActivity(i);}}
XML-Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerInParent="true"
android:layout_marginLeft="14dp"
android:src="#drawable/pic1" />
<ImageView
android:id="#+id/imageView4"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:src="#drawable/left"
android:onClick="Picture0"/>
<ImageView
android:id="#+id/imageView4"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:src="#drawable/right"
android:onClick="Picture2"/>
</RelativeLayout>
I believe that you should use universal image loader by nostra and for viewing just images there is no point of stacking up activities.You can simply use view pager or image flipper.
Look at this link..
https://github.com/nostra13/Android-Universal-Image-Loader.
yes you have to add nostra image loader as a library to your android project.
For loading large Bitmap's efficiently, just refer to this article:
Loading Large Bitmaps Efficiently
As you can see from there:
To avoid java.lang.OutOfMemory exceptions, check the dimensions of a bitmap before decoding it, unless you absolutely trust the source to provide you with predictably sized image data that comfortably fits within the available memory.
Here is the full section on Android Developers on displaying Bitmaps.
But also, you can try to use Picasso library which is very useful for this.

Android- Eclipse can't find ImageButton class

I am fairly experienced with Java/Eclipse, but I'm entirely new to Android development and it's proven to be quite an odd beast so far. I'm currently trying to create an application with two image buttons. My XML is as follows:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="24dp"
android:text="#string/now_playing" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ImageButton
android:id="#+id/StartButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/start_button"
android:contentDescription="#string/start_button" />
<ImageButton
android:id="#+id/StopButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#drawable/stop_button"
android:contentDescription="#string/stop_button" />
</LinearLayout>
</LinearLayout>
This appears to be correct, but the ImageButtons do not render properly in the Graphical Layout tab and there is a message that says, "The following classes could not be found:
- ImageButton (Change to android.widget.ImageButton, Fix Build Path, Edit XML)".
After looking around online a bit, I found that this question has popped up a few times on StackOverflow, but I was unable to find any satisfactory answers. The most common answer was to clean the project, but this has not done anything for me. Any suggestions?
Sometimes the Eclipse Graphical layout tab is unable to draw stuffs whereas the code is fine. Try to run a simple Activity with setContentView(R.layout.yourxml); and see what happen :
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourlayout);
}
}
Post your LogCat if you still have errors.
EDIT : Oh and I didn't see :
On your second ImageButton, replace
android:text="#drawable/stop_button"
by
android:src="#drawable/stop_button"
Try to import the ImageButton class on java.
import android.widget.ImageButton;

Categories