I have created three swiping splash screen layout fragments over an splash screen activity, and I want to change the color of the status bar for each fragment which matches the color of the fragment body.
My Code is
Fragment_a.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=".FragmentA">
<ImageView
android:id="#+id/circle1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/circle_filled"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginTop="16dp"
android:layout_marginStart="16dp"/>
<ImageView
android:id="#+id/circle2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/circle_blank"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toEndOf="#id/circle1"
android:layout_marginTop="16dp"
android:layout_marginStart="8dp"/>
<ImageView
android:id="#+id/circle3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/circle_blank"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toEndOf="#id/circle2"
android:layout_marginTop="16dp"
android:layout_marginStart="8dp"/>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="32dp"
android:text="Skip"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_marginTop="120dp"
android:src="#drawable/ic_browsing"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.496"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="68dp"
android:text="Move"
android:textSize="20dp"
app:layout_constraintStart_toStartOf="#+id/imageView2"
app:layout_constraintTop_toBottomOf="#+id/imageView2" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Step by Step"
app:layout_constraintTop_toBottomOf="#id/textView2"
app:layout_constraintStart_toStartOf="#id/textView2"
android:layout_marginTop="6dp"
android:textSize="35sp"
android:textStyle="bold"
android:textColor="#color/black"/>
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a dummy text.\nMade for testing purpose!"
android:textSize="20sp"
android:layout_marginTop="10dp"
app:layout_constraintStart_toStartOf="#+id/textView3"
app:layout_constraintTop_toBottomOf="#+id/textView3" />
</androidx.constraintlayout.widget.ConstraintLayout>
FragmentA.java
package in.pratikchakraborty.liquidswipe;
import android.os.Build;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
public class FragmentA extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public FragmentA() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment FragmentA.
*/
// TODO: Rename and change types and number of parameters
public static FragmentA newInstance(String param1, String param2) {
FragmentA fragment = new FragmentA();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_a, container, false);
if (Build.VERSION.SDK_INT >= 21) {
Window window = this.getActivity().getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(this.getResources().getColor(R.color.white));
}
}
}
I am getting this error while building the project.
AndroidStudioProjects\LiquidSwipe\app\src\main\java\in\pratikchakraborty\liquidswipe\FragmentA.java:65: error: unreachable statement
if (Build.VERSION.SDK_INT >= 21) {
^
You are writing the code for change status color after the return statement so it is not reachable please try below
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_a, container, false);
if (Build.VERSION.SDK_INT >= 21) {
Window window = this.getActivity().getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(this.getResources().getColor(R.color.white));
}
return view;
}
Related
I'm using a recyclerview to show restaurants that are previously saved in a database, and I'm using volley to get their information, but it is not working, I suspect that is a problem with volley code, can you guys help me at this point? I will be very happy!
I've discovered that if I start another activity then I go back to home, it returns the recyclerview again, but if I change the fragment it disapears.
Here is how the app is working for now: Result
Fragment Home code:
package com.example.techtable;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Home extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private ArrayList<restaurantes> restaurantesArrayList;
private static final String url = "https://cybersquare.dev.br/php/obterRestaurantes.php";
TextView txterro;
private RecyclerView recyclerview;
public Home() {
// Required empty public constructor
}
public static Pedidos newInstance(String param1, String param2) {
Pedidos fragment = new Pedidos();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedIntanceState){
super.onViewCreated(view, savedIntanceState);
dataInitialize();
recyclerview = view.findViewById(R.id.recyclerView);
recyclerview.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerview.setHasFixedSize(true);
adapterRestaurante myAdapter = new adapterRestaurante(getContext(),restaurantesArrayList);
recyclerview.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
private void dataInitialize() {
restaurantesArrayList = new ArrayList<>();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
response -> {
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i<array.length(); i++){
JSONObject object = array.getJSONObject(i);
String titulo = object.getString("nome");
String descricao = object.getString("descricao");
int avaliacao = object.getInt("avaliacao");
int valor = object.getInt("valor");
String fotoResto = object.getString("fotoRestaurante");
restaurantesArrayList.add(new restaurantes(titulo, descricao, avaliacao, valor, fotoResto));
}
}catch (Exception e){
}
}, error -> Toast.makeText(getActivity(), error.toString(),Toast.LENGTH_LONG).show());
Volley.newRequestQueue(getActivity()).add(stringRequest);
}
}
Recyclerview adapter:
package com.example.techtable;
import android.content.Context;
import android.media.Image;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class adapterRestaurante extends RecyclerView.Adapter<adapterRestaurante.MyViewHolder>{
Context context;
ArrayList<restaurantes> restaurantesArrayList;
public adapterRestaurante(Context context, ArrayList<restaurantes> restaurantesArrayList) {
this.context = context;
this.restaurantesArrayList = restaurantesArrayList;
}
#NonNull
#Override
public adapterRestaurante.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.layout_linha_pesquisa, parent, false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull adapterRestaurante.MyViewHolder holder, int position) {
restaurantes restaurantes = restaurantesArrayList.get(position);
holder.titResto.setText(restaurantes.titResto);
holder.descResto.setText(restaurantes.descResto);
Picasso.get().load("fotoPerfil").into(holder.fotoResto);
}
#Override
public int getItemCount() {
return restaurantesArrayList.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
ImageView fotoResto;
ImageView primeiraEstrela;
ImageView segundaEstrela;
ImageView terceiraEstrela;
ImageView primeiroDolar;
ImageView segundoDolar;
ImageView terceiroDolar;
TextView titResto;
TextView descResto;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
titResto = itemView.findViewById(R.id.titResto01);
descResto = itemView.findViewById(R.id.descResto01);
fotoResto = itemView.findViewById(R.id.fotoResto01);
primeiraEstrela = itemView.findViewById(R.id.estrela11);
segundaEstrela = itemView.findViewById(R.id.estrela12);
terceiraEstrela = itemView.findViewById(R.id.estrela13);
primeiroDolar = itemView.findViewById(R.id.valor11);
segundoDolar = itemView.findViewById(R.id.valor12);
terceiroDolar = itemView.findViewById(R.id.valor13);
}
}
}
Arraylist restaurantes
package com.example.techtable;
import android.net.Uri;
import android.widget.ImageView;
public class restaurantes {
String titResto;
String descResto;
int avaliacaoResto;
int valorResto;
String fotoResto;
public restaurantes(String titResto, String descResto, int avaliacaoResto, int valorResto, String fotoResto) {
this.titResto = titResto;
this.valorResto = valorResto;
this.avaliacaoResto = avaliacaoResto;
this.fotoResto = fotoResto;
this.descResto = descResto;
}
}
MyViewHolder layout
<?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="wrap_content">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/ConstainerResto01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="15dp"
android:background="#drawable/botaoresto"
android:onClick="teste"
android:paddingTop="20dp"
android:paddingBottom="20dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:id="#+id/fotoResto01"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_marginStart="20dp"
android:scaleType="centerInside"
android:src="#drawable/botaoredondo"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="80dp"
android:layout_marginStart="24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/fotoResto01"
app:layout_constraintTop_toTopOf="parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/constraintLayout7"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_marginEnd="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:id="#+id/estrela11"
android:layout_width="25dp"
android:layout_height="25dp"
android:src="#drawable/ic_posticestrelacheia"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/estrela12"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginStart="25dp"
android:src="#drawable/ic_posticestrelameia"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/estrela13"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginStart="50dp"
android:src="#drawable/ic_posticestrelavazia"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/valor11"
android:layout_width="25dp"
android:layout_height="25dp"
android:src="#drawable/ic_posticdolarcheio"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<ImageView
android:id="#+id/valor12"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginStart="25dp"
android:src="#drawable/ic_posticdolarcheio"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<ImageView
android:id="#+id/valor13"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginStart="50dp"
android:src="#drawable/ic_posticdolarmeia"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="80dp"
android:layout_marginEnd="25dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/constraintLayout7"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/descResto01"
android:layout_width="118dp"
android:layout_height="49dp"
android:fontFamily="#font/roboto_thin"
android:text="Lorem Ipsum Dolor Sit Amet Lorem Ipsum Dolor Sit Amet"
android:textColor="#color/cinza_medio"
android:textSize="15sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/titResto01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/roboto_black"
android:text="Restaurante 01"
android:textColor="#color/laranja"
android:textSize="20sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Fragment Home layout:
<?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"
android:background="#00FFFFFF"
tools:context=".Home">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/constraintLayout8"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="25dp"
android:layout_marginTop="70dp"
android:layout_marginEnd="25dp"
android:layout_marginBottom="1dp"
app:layout_constraintBottom_toTopOf="#+id/recyclerView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/txtUsuario"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:fontFamily="#font/roboto_medium"
android:text="Olá usuário!"
android:textColor="#color/black"
android:textSize="25sp"
app:layout_constraintBottom_toTopOf="#+id/textView29"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView20" />
<ImageView
android:id="#+id/imageView20"
android:layout_width="200dp"
android:layout_height="80dp"
android:src="#drawable/logotechtablecolorida"
app:layout_constraintBottom_toTopOf="#+id/txtUsuario"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView29"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:fontFamily="#font/roboto_light"
android:text="Escolha seu restaurante e faça seu pedido"
android:textAlignment="viewStart"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/txtUsuario" />
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="1dp"
android:layout_marginEnd="1dp"
android:layout_marginBottom="80dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/constraintLayout8" />
</androidx.constraintlayout.widget.ConstraintLayout>
JSON file:
<?php
header('content-type: application/json');
$con = mysqli_connect("localhost","cyber536_admin","mJEn#*a]0Jc*","cyber536_techtable");
mysqli_set_charset($con,'utf-8');
$query = "select nome, avaliacao, descricao, fotoRestaurante, valor from restaurantes;";
$res = mysqli_query($con,$query);
$json_data = array();
while($row = mysqli_fetch_assoc($res)){
$json_data[] = $row;
}
echo json_encode($json_data);
?>
I am following a youtube tutorial on a login/signup screen using ViewPager and tablayout. Unfortunately, both aren't working. I would very much appreciate it if you could help me find the solution for this.
activity_log_in.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=".LogIn">
<ImageView
android:id="#+id/imageview2"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:scaleType="centerCrop"
android:src="#drawable/login_background"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHeight_percent=".27"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/constraintLayout"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:background="#drawable/vie_bg"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHeight_percent=".78"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1">
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHeight_percent=".7"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tab_layout"
app:layout_constraintVertical_bias="0" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tab_layout"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0"
/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab_google"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="#color/white"
android:elevation="35dp"
android:src="#drawable/google"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/view_pager"
app:tint="#null" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab_fb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:backgroundTint="#color/white"
android:elevation="35dp"
android:src="#drawable/facebook"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#id/fab_google"
app:layout_constraintHorizontal_bias="1"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/view_pager"
app:tint="#null" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab_twitter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:backgroundTint="#color/white"
android:elevation="35dp"
android:src="#drawable/twitter"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0"
app:layout_constraintStart_toEndOf="#id/fab_google"
app:layout_constraintTop_toBottomOf="#id/view_pager"
app:tint="#null" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<ImageView
android:id="#+id/logo"
android:layout_width="70dp"
android:layout_height="70dp"
app:layout_constraintVertical_bias=".3"
android:src="#drawable/logo"
app:layout_constraintBottom_toTopOf="#+id/constraintLayout"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#id/imageview2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to KoralGel!"
android:textColor="#color/black"
android:fontFamily="#font/advent_pro_semibold"
android:textSize="30sp"
app:layout_constraintVertical_bias=".2"
app:layout_constraintBottom_toTopOf="#id/constraintLayout"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/logo"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Login.java:
package com.example.koralgel;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;
public class LogIn extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
FloatingActionButton fb, google, twitter;
float v=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
tabLayout=findViewById(R.id.tab_layout);
viewPager= findViewById(R.id.view_pager);
fb= findViewById(R.id.fab_fb);
google= findViewById(R.id.fab_google);
twitter= findViewById(R.id.fab_twitter);
tabLayout.addTab(tabLayout.newTab().setText("Login"));
tabLayout.addTab(tabLayout.newTab().setText("Signup"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final LoginAdapter adapter= new LoginAdapter(getSupportFragmentManager(),this,tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
fb.setTranslationY(300);
google.setTranslationY(300);
twitter.setTranslationY(300);
tabLayout.setTranslationY(300);
fb.setAlpha(v);
google.setAlpha(v);
twitter.setAlpha(v);
tabLayout.setAlpha(v);
fb.animate().translationY(0).setDuration(1000).setStartDelay(400).start();
google.animate().translationY(0).setDuration(1000).setStartDelay(600).start();
twitter.animate().translationY(0).setDuration(1000).setStartDelay(800).start();
tabLayout.animate().translationY(0).setDuration(1000).setStartDelay(100).start();
}
}
LoginAdapter.jave:
package com.example.koralgel;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentStatePagerAdapter;
public class LoginAdapter extends FragmentStatePagerAdapter {
private Context context;
int totalTabs;
public LoginAdapter(FragmentManager fm, Context context, int totalTabs) {
super(fm);
this.context = context;
this.totalTabs = totalTabs;
}
#Override
public int getCount() {
return totalTabs;
}
public Fragment getItem(int position) {
switch (position) {
case 0:
login_tab_fragment LogInFragment = new login_tab_fragment();
return LogInFragment;
case 1:
signup_tab_fragment SignupFragment = new signup_tab_fragment();
return SignupFragment;
default:
return null;
}
}
}
login_tab_fragment.java:
public class login_tab_fragment extends Fragment {
EditText email,pass;
Button login;
TextView forgotPass;
float v=0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState){
ViewGroup root = (ViewGroup)
inflater.inflate(R.layout.login_tab_fragment,container,false);
email= root.findViewById(R.id.email);
login= root.findViewById(R.id.button);
pass= root.findViewById(R.id.password);
forgotPass= root.findViewById(R.id.forgotPass);
email.setTranslationY(300);
login.setTranslationY(300);
pass.setTranslationY(300);
forgotPass.setTranslationY(300);
email.setAlpha(v);
login.setAlpha(v);
pass.setAlpha(v);
forgotPass.setAlpha(v);
email.animate().translationY(0).setDuration(800).setStartDelay(300).start();
pass.animate().translationY(0).setDuration(800).setStartDelay(500).start();
forgotPass.animate().translationY(0).setDuration(800).setStartDelay(500).start();
login.animate().translationY(0).setDuration(800).setStartDelay(700).start();
return root;
}
}
signup_tab_fragment.java:
public class signup_tab_fragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState){
ViewGroup root = (ViewGroup)
inflater.inflate(R.layout.signup_tab_fragment,container,false);
return root;
}
}
The outcome is just a blank ViewPager and tablayout. Please help me!
On the main screen I have 7 buttons (days) and a fragment.
For every day of the week I wanted to generate a fragment with some EditTexts and a ListView, but creating 7 fragments with the same layout and almost the same class content seems too repetitive.
I only did it for Monday and Tuesday.
The only difference between MondayFragment and TuesdayFragment is that in TuesdayFragment I renamed the variable mondayTV to tuesdayTV and in layout I changed the ids of the submit button and the ListView. Also the key for Bundle is different. I don't think it's worth posting it since it's so similar to MondayFragment.
I want to know if it's possible to create a fragment template and use it to generate a fragment for every button of the activity given this code I wrote. There is still a lot to work on when it comes to functionality but I can't get this idea out of my head.
MainActivity.java
package com.example.dietmanagement;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public Button monday, tuesday, wednesday, thursday, friday, saturday, sunday;
final MondayFragment mondayFragment = new MondayFragment();
final TuesdayFragment tuesdayFragment = new TuesdayFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*Intent i = getIntent();
String current_user = i.getStringExtra("current_user");
TextView current_user_txtview = findViewById(R.id.current_user);
current_user_txtview.setText("Welcome, " + current_user);*/
monday = (Button)findViewById(R.id.monday_btn);
tuesday = (Button)findViewById(R.id.tuesday_btn);
wednesday = (Button)findViewById(R.id.wednesday_btn);
thursday = (Button)findViewById(R.id.thursday_btn);
friday = (Button)findViewById(R.id.friday_btn);
saturday = (Button)findViewById(R.id.saturday_btn);
sunday = (Button)findViewById(R.id.sunday_btn);
monday.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFragment(mondayFragment);
getDay(mondayFragment, "monday", (String) monday.getContentDescription());
}
});
tuesday.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFragment(tuesdayFragment);
getDay(tuesdayFragment, "tuesday", (String) tuesday.getContentDescription());
}
});
}
private void openFragment(final Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.daysfragment, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
public void getDay(final Fragment fragment, String key, String value)
{
Bundle bnd = new Bundle();
bnd.putString(key, value);
fragment.setArguments(bnd);
}
}
Activity_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"
android:background="#color/background_green"
tools:context=".MainActivity">
<Button
android:id="#+id/tuesday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:contentDescription="#string/tuesday_context"
android:text="#string/tuesday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.194"
app:layout_constraintStart_toEndOf="#+id/monday_btn"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.017" />
<TextView
android:id="#+id/main_title"
android:layout_width="147dp"
android:layout_height="93dp"
android:fontFamily="sans-serif-medium"
android:text="#string/welcome_label"
android:textColor="#FFFFFF"
android:textSize="70sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.414"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.049" />
<Button
android:id="#+id/monday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:contentDescription="#string/monday_context"
android:text="#string/monday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.16"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.017" />
<Button
android:id="#+id/thursday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:text="#string/thursday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.018"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.172" />
<Button
android:id="#+id/sunday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:text="#string/sunday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="28sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.786"
app:layout_constraintStart_toEndOf="#+id/saturday_btn"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.172" />
<Button
android:id="#+id/saturday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:text="#string/saturday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="28sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.225"
app:layout_constraintStart_toEndOf="#+id/friday_btn"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.172" />
<Button
android:id="#+id/friday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:text="#string/friday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.137"
app:layout_constraintStart_toEndOf="#+id/thursday_btn"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.172" />
<Button
android:id="#+id/wednesday_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/button_states"
android:text="#string/wednesday"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.369"
app:layout_constraintStart_toEndOf="#+id/tuesday_btn"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.017" />
<ImageView
android:id="#+id/logo"
android:layout_width="52dp"
android:layout_height="58dp"
android:layout_marginStart="8dp"
android:layout_marginTop="52dp"
android:contentDescription="#string/app_name"
app:layout_constraintStart_toEndOf="#+id/main_title"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_logo" />
<TextView
android:id="#+id/current_user"
android:layout_width="362dp"
android:layout_height="27dp"
android:text="#string/current_user"
android:textAlignment="viewEnd"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/main_title"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.938"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.318" />
<FrameLayout
android:id="#+id/daysfragment"
android:layout_width="match_parent"
android:layout_height="460dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MondayFragment.java
package com.example.dietmanagement;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MondayFragment extends Fragment {
public TextView mondayTV;
public ArrayList<String> hour_food;
public ArrayAdapter<String> listViewAdapter;
public ListView listView;
public EditText input_meal;
public EditText input_time;
public Button submit;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_monday, container, false);
mondayTV = (TextView) v.findViewById(R.id.day);
Bundle bndMon = getArguments();
String day = bndMon.getString("monday");
mondayTV.setText(day);
hour_food = new ArrayList<String>();
listViewAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, hour_food);
listView = (ListView)v.findViewById(R.id.monday_list_item);
listView.setAdapter(listViewAdapter);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
hour_food.remove(position);
Toast.makeText(getActivity(), "Meal Removed", Toast.LENGTH_SHORT).show();
listViewAdapter.notifyDataSetChanged();
return true;
}
});
input_meal = v.findViewById(R.id.input_meal);
input_time = v.findViewById(R.id.input_time);
submit = (Button) v.findViewById(R.id.submit_food_btn);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(TextUtils.isEmpty(input_time.getText())) {
Toast.makeText(getActivity(), "Empty time input", Toast.LENGTH_SHORT).show();
} else if(TextUtils.isEmpty(input_meal.getText())){
Toast.makeText(getActivity(), "Empty meal input", Toast.LENGTH_SHORT).show();
}
else
{
hour_food.add(String.format("%s - %s", input_meal.getText().toString(), input_time.getText().toString()));
listViewAdapter.notifyDataSetChanged();
input_meal.setText("");
input_time.setText("");
}
}
});
return v;
}
}
fragment_monday.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background_green"
tools:context=".MondayFragment">
<TextView
android:id="#+id/day"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="#string/day" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="#+id/input_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autofillHints="#string/time"
android:hint="#string/time"
android:inputType="time" />
<EditText
android:id="#+id/input_meal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autofillHints="#string/meal"
android:hint="#string/meal"
android:inputType="textAutoCorrect|textCapSentences" />
</LinearLayout>
<Button
android:id="#+id/submit_food_btn_monday"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/submit"
android:background="#color/white"
android:textColor="#color/background_green"
android:layout_gravity="end"
android:layout_marginTop="10dp"/>
<ListView
android:id="#+id/monday_list_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
strings.xml
Create DayFragment and layout only for one day. Pass extra information for Fragment and handle situations for different days with that extra information (in your case it looks like only String from bundle is different).
fragment_day.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background_green">
<TextView
android:id="#+id/day"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="#string/day" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="#+id/input_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autofillHints="#string/time"
android:hint="#string/time"
android:inputType="time" />
<EditText
android:id="#+id/input_meal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autofillHints="#string/meal"
android:hint="#string/meal"
android:inputType="textAutoCorrect|textCapSentences" />
</LinearLayout>
<Button
android:id="#+id/submit_food_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/submit"
android:background="#color/white"
android:textColor="#color/background_green"
android:layout_gravity="end"
android:layout_marginTop="10dp"/>
<ListView
android:id="#+id/list_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
DayFragment.java
public class DayFragment extends Fragment {
private TextView dayTV;
private ArrayList<String> hour_food;
private ArrayAdapter<String> listViewAdapter;
private ListView listView;
private EditText input_meal;
private EditText input_time;
private Button submit;
private String text;
public DayFragment(String text) {
this.text = text;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_day, container, false);
dayTV = v.findViewById(R.id.day);
dayTV.setText(text);
hour_food = new ArrayList<>();
listViewAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, hour_food);
listView = v.findViewById(R.id.list_item);
listView.setAdapter(listViewAdapter);
listView.setOnItemLongClickListener((parent, view, position, id) -> {
hour_food.remove(position);
Toast.makeText(getActivity(), "Meal Removed", Toast.LENGTH_SHORT).show();
listViewAdapter.notifyDataSetChanged();
return true;
});
input_meal = v.findViewById(R.id.input_meal);
input_time = v.findViewById(R.id.input_time);
submit = v.findViewById(R.id.submit_food_btn);
submit.setOnClickListener(v1 -> {
if (TextUtils.isEmpty(input_time.getText())) {
Toast.makeText(getActivity(), "Empty time input", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(input_meal.getText())) {
Toast.makeText(getActivity(), "Empty meal input", Toast.LENGTH_SHORT).show();
} else {
hour_food.add(String.format("%s - %s", input_meal.getText().toString(), input_time.getText().toString()));
listViewAdapter.notifyDataSetChanged();
input_meal.setText("");
input_time.setText("");
}
});
return v;
}
}
Use constructor for passing information.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button monday = findViewById(R.id.monday_btn),
tuesday = findViewById(R.id.tuesday_btn),
wednesday = findViewById(R.id.wednesday_btn),
thursday = findViewById(R.id.thursday_btn),
friday = findViewById(R.id.friday_btn),
saturday = findViewById(R.id.saturday_btn),
sunday = findViewById(R.id.sunday_btn);
openFragment(monday);
openFragment(tuesday);
openFragment(wednesday);
openFragment(thursday);
openFragment(friday);
openFragment(saturday);
openFragment(sunday);
}
private void openFragment(Button btn) {
btn.setOnClickListener(v -> {
String contentDescription = btn.getContentDescription().toString();
getSupportFragmentManager().beginTransaction()
.replace(R.id.daysfragment, new DayFragment(contentDescription))
.addToBackStack(null)
.commit();
});
}
}
In MainActivity openFragment() method takes a Button parameter and with that Button and sets onClickListener to that Button. When you click any Button it gets content description from that Button and passing it to Fragment and opens that Fragment with that content description.
I'm trying to make a stopwatch in one of my fragments but I'm am unable to get the stopwatch to start. Ideally it would start after pressing startButton but I can't even get the start() function to work at all. Right now this is what I have:
Fragment:
public class RunFragment extends Fragment implements View.OnClickListener {
private Chronometer sChronometer;
private long pauseOffset;
private boolean running;
Button startRun;
Button pauseRun;
Button stopRun;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public RunFragment() {
// Required empty public constructor
}
public void disable(View startButton){
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment RunFragment.
*/
// TODO: Rename and change types and number of parameters
public static RunFragment newInstance(String param1, String param2) {
RunFragment fragment = new RunFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_run, container, false);
Button startRun = (Button) v.findViewById(R.id.startRun);
Button pauseRun = (Button) v.findViewById(R.id.pauseRun);
Button stopRun = (Button) v.findViewById(R.id.stopRun);
sChronometer = (Chronometer) v.findViewById(R.id.sChronometer);
startRun.setOnClickListener(this);
pauseRun.setOnClickListener(this);
stopRun.setOnClickListener(this);
return v;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.startRun:
sChronometer.setBase(SystemClock.elapsedRealtime());
sChronometer.start();
Toast.makeText(getActivity().getApplicationContext(), "startRun", Toast.LENGTH_SHORT).show();
break;
case R.id.pauseRun:
Toast.makeText(getActivity().getApplicationContext(), "pauseRun", Toast.LENGTH_SHORT).show();
break;
case R.id.stopRun:
Toast.makeText(getActivity().getApplicationContext(), "stopRun", Toast.LENGTH_SHORT).show();
break;
}
}
I'm not receiving any errors and the Toasts are showing up so I'm not sure what the problem is.
Here is the xml code:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".RunFragment">
<data>
<variable name="runLive" type="com.example.wam1.RunLive"/>
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="450dp"
android:gravity="center"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/startRun"
android:onClick="startRun"
android:text="Start" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/pauseRun"
android:onClick="pauseRun"
android:text="Pause" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/stopRun"
android:onClick="stopRun"
android:text="Stop" />
</LinearLayout>
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginVertical="100dp"
android:layout_marginHorizontal="10dp"
android:background="#f1f1f1"
>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Distance"
android:textStyle="bold"
android:layout_weight="1"
android:gravity= "center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Heart Rate"
android:textStyle="bold"
android:layout_weight="1"
android:gravity= "center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pace"
android:textStyle="bold"
android:layout_weight="1"
android:gravity= "center" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{runLive.distance}"
android:layout_weight="1"
android:gravity= "center"
android:background="#ffffff"
android:layout_marginBottom="1dp"
android:layout_marginHorizontal="1dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{runLive.heartRate}"
android:layout_weight="1"
android:gravity= "center"
android:background="#ffffff"
android:layout_marginRight="1dp"
android:layout_marginBottom="1dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{runLive.pace}"
android:layout_weight="1"
android:gravity= "center"
android:background="#ffffff"
android:layout_marginRight="1dp"
android:layout_marginBottom="1dp"/>
</TableRow>
</TableLayout>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Recomendation"
android:textSize="32sp"
android:layout_centerHorizontal="true"
android:layout_marginTop="250dp"/>
<Chronometer
android:id="#+id/sChronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:format="00:00:00"
android:textSize="35sp">
</Chronometer>
</RelativeLayout>
</layout>
Any help or insight would be greatly appreciated!
since you are implementing an interface 'View.onClickListener', you should define it's method onClick and not your own. That difference can be made from you not overriding the onClick method. Just change your onClick method to
#Override
public void onClick(View view) {
//super.onClick(view);
switch (v.getId()) {
case R.id.startRun:
sChronometer.setBase(SystemClock.elapsedRealtime());
sChronometer.start();
Toast.makeText(getActivity().getApplicationContext(), "startRun", Toast.LENGTH_SHORT).show();
break;
case R.id.pauseRun:
Toast.makeText(getActivity().getApplicationContext(), "pauseRun", Toast.LENGTH_SHORT).show();
break;
case R.id.stopRun:
Toast.makeText(getActivity().getApplicationContext(), "stopRun", Toast.LENGTH_SHORT).show();
break;
}
}
I have a fragment that contains a PercentRelativeLayout that I want to replace with another fragment on a button click. Here is the outer fragment xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.percent.PercentRelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.percent.PercentRelativeLayout
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
app:layout_widthPercent="92%"
app:layout_heightPercent="80%"
app:layout_marginTopPercent="15%">
<android.support.percent.PercentRelativeLayout
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:text="Vecka 49"
android:id="#+id/weekOneTextView"/>
<android.support.percent.PercentRelativeLayout
app:layout_widthPercent="100%"
app:layout_heightPercent="0%"
android:layout_below="#+id/weekOneTextView"
android:id="#+id/displayWeekOne">
</android.support.percent.PercentRelativeLayout>
<TextView
android:layout_alignParentLeft="true"
app:layout_widthPercent="45%"
app:layout_heightPercent="5%"
app:layout_marginTopPercent="2%"
android:layout_below="#+id/displayWeekOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Vecka 50"
android:id="#+id/weekTwoTextView"
android:clickable="true"/>
<android.support.percent.PercentRelativeLayout
app:layout_widthPercent="100%"
app:layout_heightPercent="0%"
android:layout_below="#+id/weekTwoTextView"
android:id="#+id/displayWeekTwo">
</android.support.percent.PercentRelativeLayout>
<TextView
android:layout_alignParentLeft="true"
app:layout_widthPercent="45%"
app:layout_heightPercent="5%"
app:layout_marginTopPercent="2%"
android:layout_below="#+id/displayWeekTwo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Vecka 51"
android:id="#+id/weekThreeTextView"
android:clickable="true"/>
<android.support.percent.PercentRelativeLayout
app:layout_widthPercent="100%"
app:layout_heightPercent="0%"
android:layout_below="#+id/weekThreeTextView"
android:id="#+id/displayWeekThree">
</android.support.percent.PercentRelativeLayout>
<TextView
android:layout_alignParentLeft="true"
android:layout_below="#+id/displayWeekThree"
app:layout_widthPercent="45%"
app:layout_heightPercent="5%"
app:layout_marginTopPercent="2%"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Vecka 52"
android:id="#+id/weekFourTextView"
android:clickable="true"/>
<android.support.percent.PercentRelativeLayout
app:layout_widthPercent="100%"
app:layout_heightPercent="0%"
android:layout_below="#+id/weekFourTextView"
android:id="#+id/displayWeekFour">
</android.support.percent.PercentRelativeLayout>
</android.support.percent.PercentRelativeLayout>
</android.support.percent.PercentRelativeLayout>
</android.support.percent.PercentRelativeLayout>
Here is the onClick method in the fragments Java file
private void setOnClickListeners(){
mWeekOneTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DropDownWeekFragment dropDownWeekFragment = new DropDownWeekFragment();
FragmentManager manager = getFragmentManager();
manager.beginTransaction().add(R.id.displayWeekOne, dropDownWeekFragment).commit();
}
});
I want to replace the PercentRelativeLayout with ID displayWeekOne with a fragment, here is the for the fragment I wish to replace with
<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="layout.DropDownWeekFragment">
<android.support.percent.PercentRelativeLayout
app:layout_widthPercent="80%"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Måndag"
android:id="#+id/monday"
app:layout_marginTopPercent="2%"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tisdag"
android:id="#+id/tuesday"
android:layout_below="#id/monday"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/wednessday"
android:layout_below="#id/tuesday"
android:text="Onsdag"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/thursday"
android:layout_below="#id/wednessday"
android:text="Torsdag"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/friday"
android:layout_below="#id/thursday"
android:text="Fredag"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/saturday"
android:layout_below="#id/friday"
android:text="Lördag"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/sunday"
android:layout_below="#id/saturday"
android:text="Söndag"/>
</android.support.percent.PercentRelativeLayout>
</android.support.percent.PercentRelativeLayout>
And here is the Java for that fragment
package layout;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.studentconsulting.mypages.R;
import static android.content.ContentValues.TAG;
public class DropDownWeekFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public DropDownWeekFragment() {
// Required empty public constructor
}
public static DropDownWeekFragment newInstance(String param1, String param2) {
DropDownWeekFragment fragment = new DropDownWeekFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
Log.d("hej", "oncreate");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_drop_down_week, container, false);
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
I read in the documentation that I can use replace() to replace another fragment, but I want to replace the PercentRelativeLayout if that is possible, or add the fragment to the outer fragments xml
FragmentManager manager = getFragmentManager();
manager.beginTransaction().replace(R.id.displayWeekOne, dropDownWeekFragment).commit();
You can use replace() to replace one Fragment with another Fragment, as well as a Layout with a Fragment.
Not tested. Hope it works.