Android image slider text change - java

I have used this for android image swipe. It's working fine. But I need some customization in it. I need text and button bellow image and text should be change according to image swipe. And the text and button should not swipe.
What I did i put two text view and button on fragment_page.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="center_horizontal"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:background="#drawable/background"
android:weightSum="1">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="wrap_content"
android:layout_height="217dp"
android:layout_weight="0.71">
</android.support.v4.view.ViewPager>
<TextView
style="#style/bigFont"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textBold"
android:layout_marginTop="20dp"
android:textColor="#color/text_color"
android:layout_centerHorizontal="true"/>
<TextView
style="#style/smallFont"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/textsmall"
android:layout_marginTop="20dp"
android:layout_below="#+id/textBold"
android:textColor="#color/text_color"
android:layout_centerHorizontal="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="REGISTER NOW"
android:id="#+id/button2"
android:background="#drawable/button_design"
android:textColor="#color/text_color"
android:padding="#dimen/abc_action_bar_content_inset_material"
android:layout_below="#+id/textsmall"
android:layout_centerHorizontal="true"
android:layout_marginTop="60dp" />
</LinearLayout>
here is my class.
package com.example.rocku28.mdt;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class Slider extends FragmentActivity {
static final int NUM_ITEMS = 4;
ImageFragmentPagerAdapter imageFragmentPagerAdapter;
ViewPager viewPager;
TextView boldTxt,smallTxt;
Button regButton;
public static final String[] IMAGE_NAME = {"one", "two", "three", "four"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
boldTxt = (TextView) findViewById(R.id.textBold);
smallTxt = (TextView) findViewById(R.id.textsmall);
imageFragmentPagerAdapter = new ImageFragmentPagerAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(imageFragmentPagerAdapter);
}
public static class ImageFragmentPagerAdapter extends FragmentPagerAdapter {
public ImageFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public Fragment getItem(int position) {
SwipeFragment fragment = new SwipeFragment();
return SwipeFragment.newInstance(position);
}
}
public static class SwipeFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View swipeView = inflater.inflate(R.layout.swipe_fragment, container, false);
ImageView imageView = (ImageView) swipeView.findViewById(R.id.imageView);
Bundle bundle = getArguments();
int position = bundle.getInt("position");
String imageFileName = IMAGE_NAME[position];
int imgResId = getResources().getIdentifier(imageFileName, "drawable", "com.example.rocku28.mdt");
imageView.setImageResource(imgResId);
setText(position);
return swipeView;
}
public void setText(int position){
// here I tried to change text on text view
switch (position){
case 0:
new Slider().boldTxt.setText(R.string.verify_licence);
new Slider().smallTxt.setText(R.string.take_back_picture);
break;
case 1:
// boldTxt.setText(R.string.verify_licence);
// smallTxt.setText(R.string.take_front_picture);
break;
case 2:
// boldTxt.setText(R.string.dashboard);
// smallTxt.setText(R.string.choose_option_to_call);
break;
case 3:
// boldTxt.setText(R.string.helpline);
// smallTxt.setText(R.string.call_call_center);
break;
}
}
static SwipeFragment newInstance(int position) {
SwipeFragment swipeFragment = new SwipeFragment();
Bundle bundle = new Bundle();
bundle.putInt("position", position);
swipeFragment.setArguments(bundle);
return swipeFragment;
}
}
}
check settext method. Here I tried to change text but problem is this context is in another class and it's static so I couldn't able to change it. How could I make it working?

Related

Cannot see widgets in tab layout in android studio

I am facing the problem of cannot see widgets in tab layouts. I have created textview and button in Overview Fragment but I cannot see them when run code. Is it right to initialize textviews and buttons in oncreateview() of fragment which we don't want to transfer to another tab. I have searched a lot about my problem but cannot get any hint. Code is given below:
package com.example.progluattempt;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import com.google.android.material.tabs.TabItem;
import com.google.android.material.tabs.TabLayout;
public class GlucosePlotterTips extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_glucose_plotter_tips);
TabLayout Tablayout1 = findViewById(R.id.Tablayout1);
TabItem OverviewTab = findViewById(R.id.Overviewtab);
TabItem HistoryTab = findViewById(R.id.Historytab);
TabItem TipsTab = findViewById(R.id.Tipstab);
ViewPager Viewpager1 = findViewById(R.id.viewpagery1);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), Tablayout1.getTabCount());
Viewpager1.setAdapter(pagerAdapter);
Tablayout1.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Viewpager1.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
//PgeAdapter
package com.example.progluattempt;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
public class PagerAdapter extends FragmentPagerAdapter {
private int numoftabs;
public PagerAdapter(FragmentManager fm, int numoftabs){
super(fm);
this.numoftabs = numoftabs;
}
#NonNull
#Override
public Fragment getItem(int position) {
switch(position){
case 0:
return new OverviewFragment();
case 1:
return new HistoryFragment();
case 2:
return new TipsFragment();
default:
return null;
}
}
#Override
public int getCount() {
return numoftabs;
}
}
//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=".GlucosePlotterTips">
<com.google.android.material.tabs.TabLayout
android:id="#+id/Tablayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.004">
<com.google.android.material.tabs.TabItem
android:id="#+id/Overviewtab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Overview" />
<com.google.android.material.tabs.TabItem
android:id="#+id/Historytab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="History" />
<com.google.android.material.tabs.TabItem
android:id="#+id/Tipstab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tips" />
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewpagery1"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
//fragmentOverview
<FrameLayout 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=".OverviewFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="183dp"
android:orientation="vertical">
<TextView
android:id="#+id/textViewov2"
android:layout_width="match_parent"
android:layout_height="56dp"
android:text="#string/overview1"
android:textColor="#color/black"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:id="#+id/textViewov3"
android:layout_width="match_parent"
android:layout_height="46dp"
android:text="TextView"
android:textColor="#color/black"
android:textSize="18sp" />
</LinearLayout>
<Button
android:id="#+id/buttonov2"
android:layout_width="277dp"
android:layout_height="93dp"
android:layout_gravity="center"
android:text="#string/planner"
android:textColor="#color/black"
android:textSize="24sp"
app:backgroundTint="#color/Yellow" />
//OverviewFragment
package com.example.progluattempt;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class OverviewFragment extends Fragment {
TextView Results, Condition;
Button Mybuttonov2;
public OverviewFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_overview, container, false);
Results = (TextView) view.findViewById(R.id.textViewov2);
Intent i =getActivity().getIntent();
String LatestReading=i.getStringExtra("TimeofReading");
Results.setText("Last Checked: " +LatestReading);
//type
Condition = (TextView) view.findViewById(R.id.textViewov3);
String TypeofDiab = i.getStringExtra("Concentration");
Condition.setText("" +TypeofDiab);
//Button
Mybuttonov2 = (Button) view.findViewById(R.id.buttonov2);
//to display conditon of user
if(Condition.getText() != null){
String num;
int numi=0;
num = Condition.getText().toString();
try{
numi = Integer.parseInt(num);
}catch(NumberFormatException ex){
}
if(numi <= 70){
System.out.println("Hypoglycemia");}
else if(numi >=70 & numi <= 140){
System.out.println("Fine");}
else if(numi>140 & numi <200){
System.out.println("Prediabetes");}
else {
System.out.println("Hyperglycemia");
}
}
//to add click event for button
Mybuttonov2.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent i3 = new Intent(getActivity(), SensorScreen.class );
startActivity(i3);
}
});
return view;
}
}
Logcat
When run emulator

Creating Flashcards in Android using Fragments

I am trying to make a simple flash card program where the user selects if they want a addition, subtraction, or multiplication problem and then use a separate fragment to show the flash card. When I run the program it doesn't seem to make it to the first fragment as it just keeps loading in the emulator. What am I doing wrong?
Main Activity
package com.example.johnt.hw4;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainAvtivity";
private SectionsStatePageAdapter mSectionStatePagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: Started.");
mSectionStatePagerAdapter = new SectionsStatePageAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById( R.id.list_fragment_port );
// setup the page
setupViewPager(mViewPager);
setViewPager(0);
/*
if (findViewById( R.id.list_fragment_port ) != null ) {
// create the fragment
ListFragment listFragment = new ListFragment();
// replace anything that was there before
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// replace any existing fragment
transaction.add( R.id.list_fragment_port, listFragment );
transaction.commit();
}
*/
}
private void setupViewPager(ViewPager viewPager) {
SectionsStatePageAdapter adapter = new SectionsStatePageAdapter(getSupportFragmentManager());
adapter.addFragment(new ListFragment(), "ListFragment");
adapter.addFragment(new DataFragment(), "DataFragment");
viewPager.setAdapter(adapter);
}
public void setViewPager(int fragmentNumber) {
mViewPager.setCurrentItem(fragmentNumber);
}
public void onListFragmentInteraction(int operatorIndex) {
//create a new data fragment with appropriate information
DataFragment dataFragment = DataFragment.newInstance( operatorIndex );
// replace anything that was there before
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// replace any existing fragment
transaction.replace( R.id.list_fragment_port, dataFragment );
// activate the back button
transaction.addToBackStack(null);
transaction.commit();
}
}
SectionStatePageAdapter
package com.example.johnt.hw4;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class SectionsStatePageAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public SectionsStatePageAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
}
ListFragment
package com.example.johnt.hw4;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class ListFragment extends Fragment {
private static final String TAG = "ListFragment";
//private OnListFragmentInteractionListener mListener;
public final static int OPERATOR_ADDITION = 1;
public final static int OPERATOR_SUBTRACTION = 2;
public final static int OPERATOR_MULTIPLICATION = 3;
private Button addition;
private Button subtraction;
private Button multiplication;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View listfrag = inflater.inflate(R.layout.fragment_list, container, false);
// deal with the buttons
addition = (Button) listfrag.findViewById( R.id.btn_addition );
subtraction = (Button) listfrag.findViewById( R.id.btn_subtraction );
multiplication = (Button) listfrag.findViewById( R.id.btn_multiplication );
addition.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onButtonPressed( OPERATOR_ADDITION );
}
});
subtraction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onButtonPressed( OPERATOR_SUBTRACTION );
}
});
multiplication.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onButtonPressed( OPERATOR_MULTIPLICATION );
}
});
return listfrag;
}
public void onButtonPressed( int operatorIndex ) {
((MainActivity)getActivity()).setViewPager(1);
//mListener.onListFragmentInteraction( operatorIndex );
}
/*
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnListFragmentInteractionListener {
void onListFragmentInteraction( int operatorIndex );
}
*/
}
DataFragment
package com.example.johnt.hw4;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.Random;
public class DataFragment extends Fragment {
private static final String TAG = "DataFragment";
private static final String ARGS_OPERATOR = "operatorIndex";
private int operatorIndex = 1;
public static DataFragment newInstance(int operatorIndex) {
DataFragment fragment = new DataFragment();
Bundle args = new Bundle();
args.putInt(ARGS_OPERATOR, operatorIndex);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflate the layout for this fragment
View datafrag = inflater.inflate(R.layout.fragment_data, container, false);
// get a link to the textview
TextView num1 = (TextView) datafrag.findViewById( R.id.tv_num1 );
TextView num2 = (TextView) datafrag.findViewById( R.id.tv_num2 );
TextView num3 = (TextView) datafrag.findViewById( R.id.tv_num3 );
TextView operator = (TextView) datafrag.findViewById( R.id.tv_operator );
Random r = new Random();
switch ( operatorIndex ) {
case ListFragment.OPERATOR_ADDITION:
int x = r.nextInt(100); // 0 - 99
int y = r.nextInt(100); // 0 - 99
int z = x + y;
num1.setText("" + x);
num2.setText(""+y);
num3.setText(""+z);
operator.setText("+");
break;
case ListFragment.OPERATOR_SUBTRACTION:
int a = r.nextInt(100); // 0 - 99
int b = r.nextInt(100 - a + 1) + a; // a - 99
int c = a - b;
num1.setText(a);
num2.setText(b);
num3.setText(c);
operator.setText("-");
break;
case ListFragment.OPERATOR_MULTIPLICATION:
int v = r.nextInt(100); // 0 - 99
int m = r.nextInt(100); // 0 - 99
int n = v * m;
num1.setText(v);
num2.setText(m);
num3.setText(n);
operator.setText("X");
break;
}
return datafrag;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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">
<android.support.v4.view.ViewPager
android:id="#+id/list_fragment_port"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</android.support.constraint.ConstraintLayout>
fragment_list.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<Button
android:id="#+id/btn_addition"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Addition"
android:textSize="25sp"
app:layout_constraintBottom_toTopOf="#+id/btn_subtraction"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/btn_subtraction"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/btn_multiplication"
android:layout_alignParentTop="true"
android:text="Subtraction"
android:textSize="25sp"
app:layout_constraintBottom_toTopOf="#+id/btn_multiplication"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btn_addition" />
<Button
android:id="#+id/btn_multiplication"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Multiplication"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btn_subtraction" />
</android.support.constraint.ConstraintLayout>
fragment_data.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<TextView
android:id="#+id/tv_num1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="num1"
android:textSize="25sp"
app:layout_constraintBottom_toTopOf="#+id/tv_operator"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/tv_num2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="num2"
android:textSize="25sp"
app:layout_constraintBottom_toTopOf="#+id/tv_equals"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tv_operator" />
<TextView
android:id="#+id/tv_num3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="num3"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tv_equals" />
<TextView
android:id="#+id/tv_operator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="operator"
android:textSize="25sp"
app:layout_constraintBottom_toTopOf="#+id/tv_num2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tv_num1" />
<TextView
android:id="#+id/tv_equals"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="="
android:textSize="25sp"
app:layout_constraintBottom_toTopOf="#+id/tv_num3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tv_num2" />
</android.support.constraint.ConstraintLayout>

Implementing Swipe functionality on portion of screen while using bottom navigation?

I am developing my first Android application as part of a college project. I am relatively new to java. My application consists of a bottom navigation, which contains 4 separate pages. Within these pages I have a head section, containing a title, contact button and logout button.
Underneath the head section I wish to have a midsection which will in itself contain 3 swipe panels containing information. Essentially there should be 3 panels for each page, with there being 4 pages (So 4 sets of 3 swipe panels).
This is where I'm having difficulty.. I'm unsure of how to nest the fragments so that only that midsection will be swipe-able. Here is a screenshot of what I have so far:
Screenshot of app
Here is my Code for my MainActivity.java class:
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
private static final String SELECTED_ITEM = "arg_selected_item";
private BottomNavigationView mBottomNav;
private int mSelectedItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBottomNav = (BottomNavigationView) findViewById(R.id.navigation);
mBottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
selectFragment(item);
return true;
}
});
MenuItem selectedItem;
if (savedInstanceState != null) {
mSelectedItem = savedInstanceState.getInt(SELECTED_ITEM, 0);
selectedItem = mBottomNav.getMenu().findItem(mSelectedItem);
} else {
selectedItem = mBottomNav.getMenu().getItem(0);
}
selectFragment(selectedItem);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(SELECTED_ITEM, mSelectedItem);
super.onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
MenuItem homeItem = mBottomNav.getMenu().getItem(0);
if (mSelectedItem != homeItem.getItemId()) {
// select home item
selectFragment(homeItem);
} else {
super.onBackPressed();
}
}
private void selectFragment(MenuItem item) {
Fragment frag = null;
// init corresponding fragment
switch (item.getItemId()) {
case R.id.menu_home:
frag = MenuFragment.newInstance(getString(R.string.text_home),
getString(R.string.test_home));
break;
case R.id.menu_notifications:
//Call to a function that does the stuff here
frag = MenuFragment.newInstance(getString(R.string.text_notifications),
getString(R.string.test_notifications));
break;
case R.id.menu_search:
frag = MenuFragment.newInstance(getString(R.string.text_search),
getString(R.string.test_search));
break;
case R.id.menu_followed:
frag = MenuFragment.newInstance(getString(R.string.text_follow),
getString(R.string.test_follow));
}
// update selected item
mSelectedItem = item.getItemId();
// uncheck the other items.
for (int i = 0; i< mBottomNav.getMenu().size(); i++) {
MenuItem menuItem = mBottomNav.getMenu().getItem(i);
menuItem.setChecked(menuItem.getItemId() == item.getItemId());
}
if (frag != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.container, frag, frag.getTag());
ft.commit();
}
}
}
Here is the acitivity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:design="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.socialivemusic.socialivetestproject.MainActivity">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#ff292929">
</FrameLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_weight="0.06"
android:background="#ff000000"
android:textAlignment="center"
design:menu="#menu/bottom_nav_items" />
</LinearLayout>
And here is my MenuFragment.java class:
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
public class MenuFragment extends Fragment {
private static final String ARG_TEXT = "arg_text";
private static final String ARG_TESTSTRING = "arg_testString";
private String mText;
private String mTest;
private View mContent;
private TextView mTextView;
private TextView mTestView;
private Button contactButton;
private Button logoutButton;
public static Fragment newInstance(String text, String testString) {
Fragment frag = new MenuFragment();
Bundle args = new Bundle();
args.putString(ARG_TEXT, text);
args.putString(ARG_TESTSTRING, testString);
frag.setArguments(args);
return frag;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_menu, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// retrieve text and color from bundle or savedInstanceState
if (savedInstanceState == null) {
Bundle args = getArguments();
mText = args.getString(ARG_TEXT);
mTest = args.getString(ARG_TESTSTRING);
} else {
mText = savedInstanceState.getString(ARG_TEXT);
mTest = savedInstanceState.getString(ARG_TESTSTRING);
}
// initialize views
mContent = view.findViewById(R.id.fragment_content);
mTextView = (TextView) view.findViewById(R.id.text);
mTestView = (TextView) view.findViewById(R.id.test);
contactButton = (Button) view.findViewById(R.id.contactButton);
logoutButton = (Button) view.findViewById(R.id.logoutbutton);
// set text and background color
mTextView.setText(mText);
mTestView.setText(mTest);
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(ARG_TEXT, mText);
outState.putString(ARG_TESTSTRING, mTest);
super.onSaveInstanceState(outState);
}
}
Here is the fragments_menu.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.socialivemusic.socialivetestproject.MenuFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_marginLeft="17dp"
android:layout_marginRight="17dp"
android:layout_height="150dp"
android:layout_marginTop="15dp"
android:background="#ff434343"
android:weightSum="1">
<Button
android:text="CONTACT"
android:textColor="#ffffff"
android:layout_width="420dp"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:layout_height="90dp"
android:layout_gravity="center"
android:id="#+id/contactButton"
android:layout_weight="0.33"
android:background="#drawable/round_button"
android:textSize="20sp"/>
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_gravity="center"
android:textColor="#969696"
android:textSize="40sp"
android:textStyle="bold"
android:layout_weight="0.355"
/>
<Button
android:text="LOGOUT"
android:textColor="#ffffff"
android:layout_width="420dp"
android:layout_height="90dp"
android:layout_gravity="center"
android:id="#+id/logoutbutton"
android:layout_weight="0.33"
android:background="#drawable/logout_button"
android:textSize="20sp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_marginLeft="17dp"
android:layout_marginRight="17dp"
android:layout_height="match_parent"
android:layout_marginBottom="15dp"
android:layout_marginTop="185dp"
android:background="#ff434343">
<TextView
android:id="#+id/test"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</RelativeLayout>
The second LinearLayout in the above file is the one which should be the swipe-panel. The only other files on the project are xml files dealing with layout of the bottom navigation bar itself, so not relevant to the trouble I'm having.
Does anyone have any recommendations on how to approach this? A helping hand on how to start this part of the project would be amazing! Thanks in advance!

android - findViewById NULL under using Fragment

I do not speak English well. So a lot of it is awkward. Also, I wish me to understand, so I used the google translator.
I had the source code from the Null Pointer Error.
how can I it fix?
First It's Xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ToggleButton
android:id="#+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.50"
android:text="ToggleButton" />
<ToggleButton
android:id="#+id/toggleButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.50"
android:text="ToggleButton" />
</LinearLayout>
<android.support.v4.view.ViewPager
android:id="#+id/pager2"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
</LinearLayout>
It's java File
package ui.tab;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.kdevproject.game.mining.R;
public class Tab2Activity extends Fragment{
// newInstance constructor for creating fragment with arguments
public static Tab2Activity newInstance() {
Tab2Activity tab2Activity = new Tab2Activity();
return tab2Activity;
}
// Store instance variables based on arguments passed
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
// Inflate the view for the fragment based on layout XML
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_tab2, container, false);
if (container == null) {
return null;
}
ViewPager mViewPager = (ViewPager) getView().findViewById(R.id.pager2);
return view;
}
}
class MyPagerAdapter extends FragmentPagerAdapter {
private static int NUM_ITEMS = 6;
public MyPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Returns total number of pages
#Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show FirstFragment
return Tab2_1Activity.newInstance();
case 1:
return Tab2_1Activity.newInstance();
}
return null;
}
// Returns the page title for the top indicator
#Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
}
Use view instead of getView() in onCreateView to initialize ViewPager :
ViewPager mViewPager = (ViewPager)view.findViewById(R.id.pager2);

NullPointerException in a Fragment when adding a EditText

I am using a tabbed layout, created using the wizard, and have a fragment ready to go. I have added some EditTexts to my fragment, and am all ready to go, however, when running the app, I get a NullPointerException at my EditText declaration.
Fragment Code:
package com.boreas.snowdaycalculatorsp2;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class AdvancedFragment extends Fragment {
EditText inSnow, durnStorm, pSnow, pTime, fSnow, wSpeed, sGround;
public double inchSnow, durationStorm, peakSnow, peakTime, finalSnow, windSpeed, snowGround, result;
TextView results;
Button calc;
String resInt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
inSnow = (EditText) getView().findViewById(R.id.inchesSnow);
durnStorm = (EditText)getView().findViewById(R.id.durationStorm);
pSnow = (EditText) getView().findViewById(R.id.peakRate);
pTime = (EditText)getView().findViewById(R.id.peakRateTime);
fSnow = (EditText) getView().findViewById(R.id.finalRate);
wSpeed = (EditText) getView().findViewById(R.id.windSpeed);
sGround = (EditText) getView().findViewById(R.id.snowGround);
results = (TextView) getView().findViewById(R.id.resultView);
calc = (Button) getView().findViewById(R.id.button);
return inflater.inflate(R.layout.advfrag_layout, container, false);
}
}
Fragment XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="#000000"
android:layout_height="match_parent">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/inchesSnow"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:hint="Inches of Snow"
android:singleLine="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/durationStorm"
android:layout_below="#+id/inchesSnow"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:hint="Duration of Storm"
android:singleLine="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/peakRate"
android:layout_below="#+id/durationStorm"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:hint="Peak Snow Rate"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:layout_alignParentStart="false"
android:singleLine="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/peakRateTime"
android:layout_below="#+id/peakRate"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:hint="Time of Peak Snow Rate"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:singleLine="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberSigned"
android:ems="10"
android:id="#+id/finalRate"
android:layout_below="#+id/peakRateTime"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:hint="Final Snow Rate"
android:singleLine="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberSigned"
android:ems="10"
android:id="#+id/windSpeed"
android:layout_below="#+id/finalRate"
android:layout_alignParentLeft="true"
android:hint="Wind Speed"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:layout_alignParentRight="true"
android:singleLine="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/snowGround"
android:layout_below="#+id/windSpeed"
android:layout_alignParentLeft="true"
android:hint="Snow Already on Ground"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:layout_alignParentRight="true"
android:singleLine="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate"
android:id="#+id/button"
android:layout_below="#+id/snowGround"
android:layout_centerHorizontal="true"
android:layout_marginTop="39dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/resultView"
android:layout_below="#+id/button"
android:layout_alignRight="#+id/button"
android:layout_marginTop="41dp"
android:layout_alignLeft="#+id/button" />
</RelativeLayout>
Main Activity:
package com.boreas.snowdaycalculatorsp2;
import java.util.Locale;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
Fragment fragment;
switch (position){
case 0:
fragment = new BasicFragment();
break;
case 1:
fragment = new AdvancedFragment();
break;
default:
throw new IllegalArgumentException("Invalid Section Number");
}
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return "Basic";
case 1:
return "Advanced";
}
return null;
}
}
}
Any ideas on what is causing the NullPointerException?
Either you should initialize your view using view object using inflater
like this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.advfrag_layout, container, false);
inSnow = (EditText) view.getView().findViewById(R.id.inchesSnow);
durnStorm = (EditText)view.getView().findViewById(R.id.durationStorm);
pSnow = (EditText)view. getView().findViewById(R.id.peakRate);
pTime = (EditText)view.getView().findViewById(R.id.peakRateTime);
fSnow = (EditText)view. getView().findViewById(R.id.finalRate);
wSpeed = (EditText)view. getView().findViewById(R.id.windSpeed);
sGround = (EditText) view.getView().findViewById(R.id.snowGround);
results = (TextView)view. getView().findViewById(R.id.resultView);
calc = (Button)view. getView().findViewById(R.id.button);
return view;
}
Or you should initialize it in OnActivityCreated like this
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
nSnow = (EditText) getView().findViewById(R.id.inchesSnow);
durnStorm = (EditText)getView().findViewById(R.id.durationStorm);
pSnow = (EditText) getView().findViewById(R.id.peakRate);
pTime = (EditText)getView().findViewById(R.id.peakRateTime);
fSnow = (EditText) getView().findViewById(R.id.finalRate);
wSpeed = (EditText) getView().findViewById(R.id.windSpeed);
sGround = (EditText) getView().findViewById(R.id.snowGround);
results = (TextView) getView().findViewById(R.id.resultView);
calc = (Button) getView().findViewById(R.id.button);
}
Note: You are getting error because OnCreateView is trying to execute before OnCreate of Activity has finished .
Change onCreateView to
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.advfrag_layout, container, false);
// inflate the layout
inSnow = (EditText) view.findViewById(R.id.inchesSnow);
// use the inflated view object to initialize edittext
durnStorm = (EditText)view.findViewById(R.id.durationStorm);
pSnow = (EditText) view.findViewById(R.id.peakRate);
pTime = (EditText)view.findViewById(R.id.peakRateTime);
fSnow = (EditText)view.findViewById(R.id.finalRate);
wSpeed = (EditText) view.findViewById(R.id.windSpeed);
sGround = (EditText) view.findViewById(R.id.snowGround);
results = (TextView) view.findViewById(R.id.resultView);
calc = (Button) view.findViewById(R.id.button);
return view; // return view
}
You have to inflate the View in onCreateView
View rootView = inflater.inflate(R.layout.advfrag_layout,
container, false);
inSnow = (EditText) rootView.findViewById(R.id.inchesSnow);
This should fix the problem
You need to initialize the view you are using so it knows where to find your editText.

Categories

Resources