I cannot add any function for my fragment's java files - java

UPDATES
I added more java files just in case you find them helpful. I figured that I may need to write codes to connect between MainActivity.java and my fragments, but the codes I followed from several YouTube videos do not work. I would be greatly appreciated if you can write me a line of code to connect the fragment.
END OF UPDATES
Whenever I try to add functions in my fragment file, it does not work. I think I may miss some codes in MainActivity.java, but I have no idea what to add to make my fragment's java files work.
Here is my fragment's java file (I did not touch anything but added a simple function to show a check mark when a button is clicked):
package com.example.dailybible3;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
/**
* A simple {#link Fragment} subclass.
* Use the {#link FragmentBible#newInstance} factory method to
* create an instance of this fragment.
*/
public class FragmentBible 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 FragmentBible() {
// 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 fragment_bible.
*/
// TODO: Rename and change types and number of parameters
public static FragmentBible newInstance(String param1, String param2) {
FragmentBible fragment = new FragmentBible();
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 view = inflater.inflate(R.layout.fragment_bible, container, false);
Button btn_complete = (Button) view.findViewById(R.id.complete_button);
btn_complete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ImageView check_mark = (ImageView) view.findViewById(R.id.check_mark);
int visibility = check_mark.getVisibility();
if(visibility == View.VISIBLE)
{
check_mark.setVisibility(View.INVISIBLE);
}
else
{
check_mark.setVisibility(View.VISIBLE);
}
}
});
return view;
}
}
Just in case, here is my xml file as well:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FragmentBible"
android:theme="#style/FontStyle">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary"
android:orientation="vertical">
<TextView
android:id="#+id/white_background_round"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:background="#drawable/white_background_round" />
<RelativeLayout
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/white_background_round"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp">
<TextView
android:id="#+id/title_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_2"
android:textColor="#color/colorPrimary"
android:textSize="45sp"
android:textStyle="bold"/>
<ImageView
android:id="#+id/title_image"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_alignTop="#+id/title_string"
android:layout_alignBottom="#+id/title_string"
android:layout_marginLeft="20dp"
android:layout_toEndOf="#+id/title_string"
android:background="#drawable/ic_bible_english" />
</RelativeLayout>
<ImageView
android:id="#+id/button_background"
android:layout_width="wrap_content"
android:layout_marginTop="10dp"
android:layout_height="30dp"
android:layout_alignStart="#+id/white_background_round"
android:layout_alignEnd="#+id/white_background_round"
android:layout_marginRight="60dp"
android:layout_marginLeft="60dp"
android:layout_below="#+id/title"
android:background="#drawable/light_background_round_english" />
<Button
android:id="#+id/niv"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignTop="#+id/button_background"
android:layout_alignStart="#+id/button_background"
android:layout_alignBottom="#+id/button_background"
android:layout_toStartOf="#+id/centerline"
android:text="NIV"
android:textColor="#color/colorPrimary"
android:textStyle="bold"
android:background="#android:color/transparent"/>
<Button
android:id="#+id/kjv"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignTop="#+id/button_background"
android:layout_alignEnd="#+id/button_background"
android:layout_alignBottom="#+id/button_background"
android:layout_toEndOf="#+id/centerline"
android:text="KJV"
android:textColor="#color/colorPrimary"
android:textStyle="bold"
android:background="#android:color/transparent"/>
<TextView
android:id="#+id/centerline"
android:layout_width="1dp"
android:layout_height="10dp"
android:layout_alignBottom="#+id/button_background"
android:layout_centerHorizontal="true"
android:layout_below="#+id/title"
android:background="#color/colorPrimary"
android:layout_margin="5dp"
android:layout_alignTop="#+id/button_background"
android:elevation="10dp"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/complete_button"
android:layout_below="#+id/button_background"
android:layout_alignStart="#+id/white_background_round"
android:layout_alignEnd="#+id/white_background_round"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/subtitle1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Leviticus 2"
android:textColor="#color/colorPrimaryLight"
android:textSize="25sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/subtitle_text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/subtitle1"
android:layout_alignStart="#+id/subtitle1"
android:layout_marginEnd="20dp"
android:text="1) When anyone brings a grain offering to the Lord, their offering is to be of the finest flour. They are to pour olive oil on it, put incense on it 2) and take it to Aaron’s sons the priests. The priest shall take a handful of the flour and oil, together with all the incense, and burn this as a memorial portion on the altar, a food offering, an aroma pleasing to the Lord."
android:textColor="#color/colorPrimary"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="#+id/subtitle2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/subtitle_text1"
android:text="Leviticus 2"
android:textColor="#color/colorPrimaryLight"
android:textSize="25sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/subtitle_text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/subtitle2"
android:layout_alignStart="#+id/subtitle2"
android:layout_marginEnd="20dp"
android:text="1) When anyone brings a grain offering to the Lord, their offering is to be of the finest flour. They are to pour olive oil on it, put incense on it 2) and take it to Aaron’s sons the priests. The priest shall take a handful of the flour and oil, together with all the incense, and burn this as a memorial portion on the altar, a food offering, an aroma pleasing to the Lord."
android:textColor="#color/colorPrimary"
android:textSize="15sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/subtitle3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/subtitle_text2"
android:text="Leviticus 2"
android:textColor="#color/colorPrimaryLight"
android:textSize="25sp"
android:textStyle="bold" />
<TextView
android:id="#+id/subtitle_text3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/subtitle3"
android:layout_alignStart="#+id/subtitle3"
android:layout_marginEnd="20dp"
android:text="1) When anyone brings a grain offering to the Lord, their offering is to be of the finest flour. They are to pour olive oil on it, put incense on it 2) and take it to Aaron’s sons the priests. The priest shall take a handful of the flour and oil, together with all the incense, and burn this as a memorial portion on the altar, a food offering, an aroma pleasing to the Lord."
android:textColor="#color/colorPrimary"
android:textSize="15sp"
android:textStyle="bold"/>
</RelativeLayout>
</ScrollView>
<TextView
android:id="#+id/complete_button_background"
android:layout_width="wrap_content"
android:layout_height="60sp"
android:layout_alignBottom="#+id/white_background_round"
android:layout_alignRight="#+id/white_background_round"
android:layout_alignLeft="#+id/white_background_round"
android:layout_marginRight="75dp"
android:layout_marginLeft="75sp"
android:layout_marginBottom="20sp"
android:background="#drawable/light_background_round_english" />
<ImageView
android:id="#+id/check_mark"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/complete_button"
android:layout_alignLeft="#+id/complete_button"
android:layout_alignRight="#+id/complete_button"
android:layout_alignTop="#+id/complete_button"
android:elevation="10dp"
android:visibility="invisible"
android:src="#drawable/ic_check_english"/>
<TextView
android:id="#+id/complete_button_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Complete"
android:layout_alignTop="#+id/complete_button_background"
android:layout_alignLeft="#+id/complete_button_background"
android:layout_alignBottom="#+id/complete_button_background"
android:layout_marginLeft="10sp"
android:layout_marginTop="10sp"
android:layout_marginBottom="10sp"
android:gravity="center"
android:textSize="30sp"
android:textColor="#color/colorPrimary"
android:textStyle="bold"/>
<Button
android:id="#+id/complete_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/complete_button_background"
android:layout_alignBottom="#+id/complete_button_background"
android:layout_alignTop="#+id/complete_button_background"
android:layout_marginTop="7sp"
android:layout_marginBottom="7sp"
android:layout_marginRight="10sp"
android:layout_marginLeft="10sp"
android:layout_toEndOf="#+id/complete_button_text"
android:background="#drawable/white_button_round" />
</RelativeLayout>
</FrameLayout>
And here is MainActivity.java:
package com.example.dailybible3;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabLayout;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.example.dailybible3.ui.main.SectionsPagerAdapter;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
}
Also, here is the adapter:
package com.example.dailybible3.ui.main;
import android.content.Context;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import com.example.dailybible3.R;
/**
* A [FragmentPagerAdapter] that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
#StringRes
private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2, R.string.tab_text_3, R.string.tab_text_4, R.string.tab_text_5};
private final Context mContext;
public SectionsPagerAdapter(Context context, FragmentManager fm) {
super(fm);
mContext = context;
}
#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).
return PlaceholderFragment.newInstance(position + 1);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}
#Override
public int getCount() {
// Show 5 total pages.
return 5;
}
}
And here is PlaceHolderFragment.java:
package com.example.dailybible3.ui.main;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.example.dailybible3.R;
/**
* A placeholder fragment containing a simple view.
*/
public class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
private PageViewModel pageViewModel;
public static PlaceholderFragment newInstance(int index) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle bundle = new Bundle();
bundle.putInt(ARG_SECTION_NUMBER, index);
fragment.setArguments(bundle);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageViewModel = ViewModelProviders.of(this).get(PageViewModel.class);
int index = 1;
if (getArguments() != null) {
index = getArguments().getInt(ARG_SECTION_NUMBER);
}
pageViewModel.setIndex(index);
}
#Override
public View onCreateView(
#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = null;
switch(getArguments().getInt(ARG_SECTION_NUMBER))
{
case 1:
root = inflater.inflate(R.layout.fragment_main, container, false);
break;
case 2:
root = inflater.inflate(R.layout.fragment_bible, container, false);
break;
case 3:
root = inflater.inflate(R.layout.fragment_notes, container, false);
break;
case 4:
root = inflater.inflate(R.layout.fragment_alarm, container, false);
break;
case 5:
root = inflater.inflate(R.layout.fragment_records, container, false);
break;
}
return root;
}
}
And here is the PageViewModel.java (which I am not quite sure why it is needed):
package com.example.dailybible3.ui.main;
import androidx.arch.core.util.Function;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Transformations;
import androidx.lifecycle.ViewModel;
public class PageViewModel extends ViewModel {
private MutableLiveData<Integer> mIndex = new MutableLiveData<>();
private LiveData<String> mText = Transformations.map(mIndex, new Function<Integer, String>() {
#Override
public String apply(Integer input) {
return "Hello world from section: " + input;
}
});
public void setIndex(int index) {
mIndex.setValue(index);
}
public LiveData<String> getText() {
return mText;
}
}
Any help is greatly appreciated!

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

fragments and bottomNavigationView

enter image description hereI'm totally new in android studio and java.
I created one bottomNavigation for my app and I used 3 fragments and it's totally fine and working.
but now I want to add one seekBar and click listener on one of my fragments but I couldn't do it.
my question is in which life cycle view or function I have to add this seek bar click listener?
I want to add this code as a seekbar listener
seekBar.findViewById(R.id.seekBar);
textView.findViewById(R.id.textView3);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
textView.setText(progress+"/100");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
**View**
<?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:id="#+id/f2"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SecondFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:orientation="vertical"
android:padding="10dp"
android:gravity="center"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="#string/diary_pgae_sleep" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="0/24" />
<SeekBar
android:id="#+id/seekBar"
style="#style/AppTheme"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:layout_weight="1"
android:max="24"
android:progress="0"
android:progressDrawable="#drawable/track1"
android:thumb="#drawable/thumb"
android:thumbTint="#color/colorPrimaryDark"
android:indeterminate="false"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
**Code**
package com.example.myapplication;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;
import android.widget.TextView;
/**
* A simple {#link Fragment} subclass.
* Use the {#link SecondFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class SecondFragment extends Fragment {
SeekBar seekBar;
TextView textView;
// 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 SecondFragment() {
// 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 SecondFragment.
*/
// TODO: Rename and change types and number of parameters
public static SecondFragment newInstance(String param1, String param2) {
SecondFragment fragment = new SecondFragment();
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_second, container, false);
}
}
For this, you actually need separate java files that, in the class declaration, extends 'Fragment'. This is a really good youtube video for it:
https://www.youtube.com/watch?v=bNpWGI_hGGg
Hope this helps.

Parse-Server Android : Adding buttons inside a Tab ListFragment with ListView

I'm trying to add Parse API data with a tab Fragment. The ListView
is working fine and I need to add 2 filter Buttons between the
Fragment tab Buttons and the ListView. Below I attached what I'm
trying to get
MainActivity.java
import android.support.design.widget.TabLayout;
import android.support.v4.app.ListFragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
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.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.parse.Parse;
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 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.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
Parse.initialize(new Parse.Configuration.Builder(this)
.applicationId("")
.server("")
.build()
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private EventFragment eventFragment = new EventFragment();
private IndividualsFragment individualsFragment = new IndividualsFragment();
private OrganizationFragment orgFragment = new OrganizationFragment();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
OrganizationFragment tab1= orgFragment;
return tab1;
case 1:
EventFragment tab2= eventFragment;
return tab2;
case 2:
IndividualsFragment tab3= individualsFragment;
return tab3;
}
return null ;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Directory";
case 1:
return "EVENTS";
case 2:
return "INDIVIDUALS";
}
return null;
}
}
}
This is a Fragment tab.
I want to 2 Buttons between the Fragment tab Buttons and the ListView items
EventFragment.java
import android.app.ListActivity;
import android.app.ListFragment;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import java.util.ArrayList;
import java.util.List;
public class EventFragment
extends android.support.v4.app.ListFragment
implements FindCallback<ParseObject> {
private List<ParseObject> mOrganization = new ArrayList<ParseObject>();
#Override
public void onViewCreated(View view, Bundle b) {
super.onViewCreated(view, b);
EventAdapter adaptor = new EventAdapter(getActivity(), mOrganization);
setListAdapter(adaptor);
// This is like calling fetchList()
ParseQuery.getQuery("Event").findInBackground(this);
}
/**
* This is needed by implementing the callback on the class
**/
#Override
public void done(List<ParseObject> scoreList, ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + scoreList.size() + " Event");
mOrganization.clear();
mOrganization.addAll(scoreList);
((EventAdapter) getListAdapter()).notifyDataSetChanged();
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
}
this is the xml file of the ListView
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.swipe.com.MainActivity">
<com.example.rihan.swip.RoundRectCornerImageView
android:id="#+id/imageView"
android:layout_gravity="center"
android:layout_height="110dp"
android:layout_width="110dp"
tools:minWidth="30dp"
tools:maxWidth="50dp"
tools:minHeight="30dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="14dp"
android:layout_marginStart="14dp"
android:layout_marginTop="19dp"
android:scaleType="fitXY"/>
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/organizationname"
tools:textSize="10sp"
android:textSize="10sp"
android:layout_below="#+id/idposition"
android:layout_alignLeft="#+id/idposition"
android:layout_alignStart="#+id/idposition"
android:paddingTop="10px" />
<TextView
android:id="#+id/user"
android:text="Username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="12sp"
android:textColor="#000"
android:layout_alignBaseline="#+id/name"
android:layout_alignBottom="#+id/name"
android:layout_toRightOf="#+id/name"
android:layout_toEndOf="#+id/name"
android:paddingLeft="10dp"
android:fontFamily="sans-serif" />
<TextView
android:text="yy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/idposition"
android:textSize="10sp"
android:layout_below="#+id/name"
android:layout_alignLeft="#+id/name"
android:layout_alignStart="#+id/name" />
<TextView
android:id="#+id/name"
android:text="Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:minWidth="5dp"
android:layout_marginLeft="12dp"
android:layout_marginStart="12dp"
tools:textStyle="bold"
android:textColor="#000"
android:textSize="12sp"
android:textStyle="bold"
android:layout_alignTop="#+id/imageView"
android:layout_toRightOf="#+id/imageView"
android:layout_toEndOf="#+id/imageView"
android:layout_marginTop="13dp"
android:fontFamily="sans-serif" />
</RelativeLayout>
this is activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.swipe.com.MainActivity">
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:layout_height="40dp"
android:background="#drawable/nav"
android:id="#+id/button2"
android:layout_weight="1"
android:layout_width="40dp"
android:layout_alignBottom="#+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
tools:paddingLeft="25dp"
tools:layout_marginLeft="20dp" />
<Button
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#drawable/i"
android:id="#+id/button"
android:layout_weight="1"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<ImageView
app:srcCompat="#drawable/logo"
android:id="#+id/imageView2"
android:layout_weight="1"
tools:layout_marginLeft="15dp"
android:layout_width="280dp"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/button"
android:layout_toStartOf="#+id/button"
android:layout_height="50dp" />
</RelativeLayout>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
If we quote Android | ListFragment
ListFragment has a default layout that consists of a single list view. However, if you desire, you can customize the fragment layout by returning your own view hierarchy from onCreateView(LayoutInflater, ViewGroup, Bundle).
And also from the documentation
your view hierarchy must contain a ListView object with the id "#android:id/list"
Let's call this **some_list_view.xml**
Notice not #+id/list, but #android:id/list
<?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:paddingLeft="8dp"
android:paddingRight="8dp">
<!-- TODO: Add your buttons here -->
<ListView android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"/>
<TextView android:id="#id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="No data"/>
</LinearLayout>
One of your error exists in onViewCreated. You have no inflater there.
Implement the other method like the documentation says.
And you don't need to find the ListView.
Use findViewById to find other views.
For example,
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.some_list_view, parent, false);
}
#Override
public void onViewCreated(View view, Bundle b) {
super.onViewCreated(view, b);
// Button filter1 = (Button) view.findViewById(...);
// filter1.setOnClickListener....
EventAdapter adaptor = new EventAdapter(getActivity(), mOrganization);
setListAdapter(adaptor);
// This is like calling fetchList()
ParseQuery.getQuery("Event").findInBackground(this);
}
#Override
public void done(List<ParseObject> scoreList, ParseException e) {
if (e == null) {
...
}
}
getListView() already will return you your ListView, therefore, notice I didn't need to find it. But if you did, this is how.
(ListView) view.findViewById(android.R.id.list);
So, that's just a matter of making an XML file with that mentioned ID value set to a ListView like shown above.

How to pass values between fragments while using a viewpager in android

I am creating a sign up form which has been divided into three fragments.The three fragments are connected by a viewpager.I can traverse throught the fragments with next and previous buttons.I want the data from the first and second fragment to be available in the third fragment.One option is to use sharedpreferences.Is there any other approach.
The main class:
package pl.looksok.viewpagerdemo;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class MainActivity extends FragmentActivity {
ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyPagerAdapter pageAdapter = new MyPagerAdapter(getSupportFragmentManager());
pager = (ViewPager)findViewById(R.id.myViewPager);
pager.setAdapter(pageAdapter);
}
public void selectFragment(int position){
pager.setCurrentItem(position, true);
// true is to animate the transaction
}
}
The main xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<pl.looksok.viewpagerdemo.CustomViewPager
android:id="#+id/myViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
The first fragment:
package pl.looksok.viewpagerdemo;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
public class FragmentBlue extends Fragment {
Button btnnext1;
RelativeLayout frag1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blue, container, false);
btnnext1=(Button) view.findViewById(R.id.btnnext1);
frag1=(RelativeLayout) view.findViewById(R.id.frag1);
btnnext1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
((MainActivity)getActivity()).selectFragment(1);
}
});
return view;
}
}
The first xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#4ECDC4"
android:id="#+id/frag1"
>
<Button
android:id="#+id/btnnext1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="NEXT" />
<EditText
android:id="#+id/txtfname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtmname"
android:layout_alignParentTop="true"
android:ems="10"
android:hint="FIRST NAME" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/txtmname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtfname"
android:layout_centerHorizontal="true"
android:layout_marginTop="24dp"
android:ems="10"
android:hint="MIDDLE NAME" />
<EditText
android:id="#+id/txtlname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtmname"
android:layout_below="#+id/txtmname"
android:layout_marginTop="23dp"
android:ems="10"
android:hint="LAST NAME" />
<EditText
android:id="#+id/txtdob"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtlname"
android:layout_centerVertical="true"
android:ems="10"
android:hint="DOB" />
</RelativeLayout>
The second fragment:
package pl.looksok.viewpagerdemo;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
public class FragmentGreen extends Fragment {
Button btnnext2,btnprev2;
RelativeLayout frag2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_green, container, false);
btnnext2=(Button) view.findViewById(R.id.btnnext2);
btnprev2=(Button) view.findViewById(R.id.btnprev2);
frag2=(RelativeLayout) view.findViewById(R.id.frag2);
btnnext2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
((MainActivity)getActivity()).selectFragment(2);
}
});
btnprev2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)getActivity()).selectFragment(0);
}
});
return view;
}
}
The second fragment's xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#C7F464"
android:id="#+id/frag2"
>
<Button
android:id="#+id/btnnext2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginRight="60dp"
android:text="NEXT" />
<Button
android:id="#+id/btnprev2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginRight="68dp"
android:layout_toLeftOf="#+id/btnnext2"
android:text="PREV" />
<EditText
android:id="#+id/txtgender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/btnnext2"
android:ems="10"
android:hint="GENDER" />
<EditText
android:id="#+id/txtmaritalstatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtgender"
android:layout_below="#+id/txtgender"
android:layout_marginTop="24dp"
android:ems="10"
android:hint="MARITAL STATUS" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/txtoccupation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtmaritalstatus"
android:layout_below="#+id/txtmaritalstatus"
android:layout_marginTop="23dp"
android:ems="10"
android:hint="OCCUPATION" />
<EditText
android:id="#+id/txtusername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtoccupation"
android:layout_centerVertical="true"
android:ems="10"
android:hint="USERNAME" />
<EditText
android:id="#+id/txtpassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtusername"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:ems="10"
android:hint="PASSWORD"
android:inputType="textPassword" />
</RelativeLayout>
The third fragment:
package pl.looksok.viewpagerdemo;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.support.v4.app.Fragment;
public class FragmentPink extends Fragment {
Button btnnext3,btnprev3;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_pink, container, false);
btnnext3=(Button) view.findViewById(R.id.btnnext3);
btnprev3=(Button) view.findViewById(R.id.btnprev3);
btnnext3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
btnprev3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)getActivity()).selectFragment(1);
}
});
return view;
}
}
The third fragment's xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF6B6B">
<Button
android:id="#+id/btnnext3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="NEXT" />
<Button
android:id="#+id/btnprev3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="PREV" />
<EditText
android:id="#+id/txtaddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:ems="10"
android:hint="ADDRESS" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/txtdistrict"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtaddress"
android:layout_below="#+id/txtaddress"
android:layout_marginTop="30dp"
android:ems="10"
android:hint="DISTRICT" />
<EditText
android:id="#+id/txtstate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtdistrict"
android:layout_centerHorizontal="true"
android:layout_marginTop="41dp"
android:ems="10"
android:hint="STATE" />
<EditText
android:id="#+id/txtpincode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtstate"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:ems="10"
android:hint="PINCODE" />
</RelativeLayout>
The adapter:
package pl.looksok.viewpagerdemo;
import java.util.ArrayList;
import java.util.List;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MyPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
this.fragments = new ArrayList<Fragment>();
fragments.add(new FragmentBlue());
fragments.add(new FragmentGreen());
fragments.add(new FragmentPink());
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
}
I also created a class which has string values.I was wondering if i could create an object and set the fields as properties for that object
The class with the fields:
package pl.looksok.viewpagerdemo;
import java.io.Serializable;
public class RegistrationValues implements Serializable {
String fname;
String mname;
String lname;
String dob;
String gender;
String marital_status;
String occupation;
String username;
String password;
String address;
String district;
String state;
String pincode;
String nationality;
String email;
String phno;
String bank_acno;
String bank_branch;
String bank_ifsc;
String bank_swift;
}
So the question is how to pass the values in the first and second fragment to the last fragment without using Sharedpreferences.
The easy approach would be to let the RegistrationValues instance reside in your MainActivity instance:
public class MainActivity extends FragmentActivity {
ViewPager pager;
RegistrationValues values; //add this
public RegistrationValues getValues() { //add this
return values; //add this
}; //add this
In your fragments, use ((MainActivity) getActivity()).getValues() to update the values and to actually get the values in the third fragment or so.
Note: You should probably save the values instance in your MainActivity's onSaveInstance and restore it in your MainActivity's onCreate.
i think that for values passing between fragments you can use listener and dispatcher patterns and singleton pattern, which will manage listeners and dispatchers, because fragments are not Activities and you can't pass values via Intents.
A very common pattern is for the fragments to provide an interface by which values may be passed to them, and to use the containing activity as a hub. To see an example of this, use Eclipse or Android Studio to instantiate a new Master/Detail Flow activity and look at the code for the ListActivity.
But I would argue that in this case, you probably don't want to do that. Your data record looks like something you want to maintain in your persistence layer (Model), maybe mutate through a service (Controller) and pull up as needed into the fragment (View). Separate UI from business logic, and use an Adapter to keep the data in sync.

Activities togglebutton when clicking a part of an image

I'm currently trying to make a small application in java, and I have encountered a small problem.
I need to activate a togglebutton when I touch a particular area of the image that I have provided.
I enclose the code of my pages.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="4dip" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal" >
<Button
android:id="#+id/btnPag1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lights"
tools:ignore="HardcodedText" >
</Button>
<Button
android:id="#+id/btnPag2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Automation"
tools:ignore="HardcodedText" >
</Button>
<Button
android:id="#+id/btnPag3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Garden"
tools:ignore="HardcodedText" />
</LinearLayout>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1" >
</android.support.v4.view.ViewPager>
</LinearLayout>
page1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000000"
android:gravity="center_horizontal|center_vertical"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Light 1"
android:textAppearance="?android:attr/textAppearanceLarge"
tools:ignore="HardcodedText" />
<ToggleButton
android:id="#+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Light 2"
android:textAppearance="?android:attr/textAppearanceLarge"
tools:ignore="HardcodedText" />
<ToggleButton
android:id="#+id/toggleButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Light 3"
android:textAppearance="?android:attr/textAppearanceLarge"
tools:ignore="HardcodedText" />
<ToggleButton
android:id="#+id/toggleButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Light 4"
android:textAppearance="?android:attr/textAppearanceLarge"
tools:ignore="HardcodedText" />
<ToggleButton
android:id="#+id/toggleButton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton"
tools:ignore="HardcodedText" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/casa"
tools:ignore="ContentDescription" />
</LinearLayout>
page2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000000"
android:gravity="center_horizontal|center_vertical"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gate"
android:textAppearance="?android:attr/textAppearanceLarge"
tools:ignore="HardcodedText" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activates"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
page3.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000000"
android:gravity="center_horizontal|center_vertical"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Irrigation"
android:textAppearance="?android:attr/textAppearanceLarge"
tools:ignore="HardcodedText" />
<ToggleButton
android:id="#+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
MercuryActivity.java
package it.anddev.bradipao.mercury;
// derived from http://thepseudocoder.wordpress.com/2011/10/05/android-page-swiping-using-viewpager/
import java.util.List;
import java.util.Vector;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MercuryActivity extends FragmentActivity implements Page1Fragment.OnPageListener {
// list contains fragments to instantiate in the viewpager
List<Fragment> fragments = new Vector<Fragment>();
// page adapter between fragment list and view pager
private PagerAdapter mPagerAdapter;
// view pager
private ViewPager mPager;
// activity data
public String p2text,p3text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// creating fragments and adding to list
fragments.add(Fragment.instantiate(this,Page1Fragment.class.getName()));
fragments.add(Fragment.instantiate(this,Page2Fragment.class.getName()));
fragments.add(Fragment.instantiate(this,Page3Fragment.class.getName()));
// creating adapter and linking to view pager
this.mPagerAdapter = new PagerAdapter(super.getSupportFragmentManager(),fragments);
mPager = (ViewPager) super.findViewById(R.id.pager);
mPager.setAdapter(this.mPagerAdapter);
// upper bar button listener, allows direct page access
Button button = (Button)findViewById(R.id.btnPag1);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(0); // go to first page
}
});
button = (Button)findViewById(R.id.btnPag2);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(1); // go to second page
}
});
button = (Button)findViewById(R.id.btnPag3);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(2); // go to third page
}
});
}
// page 1 fragment listener implementation
#Override
public void onPage1(String s) {
// set activity data with received string
p2text = new String(s+" 2");
p3text = new String(s+" 3");
// page 2 fragment update
Page2Fragment f2 = (Page2Fragment) fragments.get(1);
f2.ptext = p2text;
// if page 2 view is already created, update
View v2 = f2.getView();
if (v2!=null) {
}
// page 3 fragment update
Page3Fragment f3 = (Page3Fragment) fragments.get(2);
f3.ptext = p3text;
// if page 3 view is already created, update
View v3 = f3.getView();
if (v3!=null) {
}
}
}
Page1Fragment.java
package it.anddev.bradipao.mercury;
import android.app.Activity;
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 android.widget.LinearLayout;
public class Page1Fragment extends Fragment {
public String ptext="..PAGE 1..";
// activity listener interface
private OnPageListener pageListener;
public interface OnPageListener {
public void onPage1(String s);
}
// onAttach : set activity listener
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// if implemented by activity, set listener
if(activity instanceof OnPageListener) {
pageListener = (OnPageListener) activity;
}
// else create local listener (code never executed in this example)
else pageListener = new OnPageListener() {
#Override
public void onPage1(String s) {
Log.d("PAG1","Button event from page 1 : "+s);
}
};
}
// onCreateView :
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
// fragment not when container null
if (container == null) {
return null;
}
// inflate view from layout
View view = (LinearLayout)inflater.inflate(R.layout.page1,container,false);
// update text
return view;
}
// set text helper function
}
Page2Fragment.java
package it.anddev.bradipao.mercury;
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.LinearLayout;
public class Page2Fragment extends Fragment {
public String ptext="..PAGE 2..";
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
// fragment not when container null
if (container == null) {
return null;
}
// inflate view from layout
View view = (LinearLayout)inflater.inflate(R.layout.page2,container,false);
// update text
return view;
}
// set text helper function
}
Page3Fragment.java
package it.anddev.bradipao.mercury;
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;
import android.widget.LinearLayout;
public class Page3Fragment extends Fragment {
Button btnWrite;
public String ptext="..PAGE 3..";
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
// fragment not when container null
if (container == null) {
return null;
}
// inflate view from layout
View view = (LinearLayout)inflater.inflate(R.layout.page3,container,false);
// update text
return view;
}
}
PageAdapter.java
package it.anddev.bradipao.mercury;
import java.util.List;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class PagerAdapter extends FragmentPagerAdapter {
// fragments to instantiate in the viewpager
private List<Fragment> fragments;
// constructor
public PagerAdapter(FragmentManager fm,List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
// return access to fragment from position, required override
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
// number of fragments in list, required override
#Override
public int getCount() {
return this.fragments.size();
}
}

Categories

Resources