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
Related
I wanna have same fab transformation behavior as shown in
Material Website in Full Screen (or morph) section.
I have tried default FabTransformationScrimBehavior and FabTransformationSheetBehavior. but scrim behavior doesn't do anything and sheet behavior don't animate just like I wanted and also it reduce the elevation of the fab to value 0f. and I haven't found any way to unexpand fab. and I wanna know how to use fab transformation behavior. Actually I didn't find any doc on how to use it. So Please help
Code
This is the code that I used:
this is the code of first activity:-
final FloatingActionButton actionButton = findViewById(R.id.add_fab);
actionButton.setOnClickListener(view -> {
actionButton.setExpanded(!actionButton.isExpanded());
});
And this is the xml of first activity:-
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
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"
xmlns:tools="http://schemas.android.com/tools">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<include layout="#layout/include_generic_toolbar" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/list_rv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:paddingBottom="76dp"
app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior"
tools:listitem="#layout/media_list_item_card" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/add_fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
android:includeFontPadding="false"
android:text="Add Media"
android:textAllCaps="false"
android:visibility="visible"
app:srcCompat="#drawable/ic_add_24"/>
<com.google.android.material.circularreveal.CircularRevealFrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="invisible"
app:layout_behavior="com.google.android.material.transformation.FabTransformationSheetBehavior"
>
<fragment
android:id="#+id/fab_transformation"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.zimong.ssms.fragments.AddMediaFragment"
/>
</com.google.android.material.circularreveal.CircularRevealFrameLayout>
And the code of AddMediaFragment(second screen):-
package com.zimong.ssms.fragments;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.DialogFragment;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.zimong.ssms.R;
import com.zimong.ssms.common.model.User;
import com.zimong.ssms.extended.CallbackHandlerImpl;
import com.zimong.ssms.model.Source;
import com.zimong.ssms.model.ZResponse;
import com.zimong.ssms.service.AppService;
import com.zimong.ssms.service.ServiceLoader;
import com.zimong.ssms.util.Constants;
import com.zimong.ssms.util.Util;
import java.util.Calendar;
import java.util.Date;
import retrofit2.Call;
import retrofit2.Response;
public class AddMediaFragment extends DialogFragment {
private ArrayAdapter<Source> adapter;
private TextView source;
private int checkedItem = 0;
private TextView mediaDate;
private Date currentSelectedDate;
public static AddMediaFragment newInstance() {
AddMediaFragment fragment = new AddMediaFragment();
Bundle bundle = new Bundle();
fragment.setArguments(bundle);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_FRAME, R.style.AppTheme_Light);
setHasOptionsMenu(true);
}
private void getSources() {
final User user = Util.getUser(getActivity());
AppService service = ServiceLoader.createService(AppService.class);
Call<ZResponse> call = service.mediaGallerySources(Constants.DEFAULT_PLATFORM, user.getToken());
call.enqueue(new CallbackHandlerImpl<Source[]>(getActivity(), true, true, Source[].class) {
#Override
protected void failure(Throwable t) {
}
#Override
protected void failure(Response<ZResponse> response) {
}
#Override
protected void success(Source[] response) {
if (response.length > 0) {
source.setText(response[0].getName());
}
adapter = new ArrayAdapter<Source>(getContext(), R.layout.dialog_singlechoice_item, response) {
#Override
public long getItemId(int position) {
return getItem(position).getPk();
}
};
}
});
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_add_media, container, false);
TextView headline = view.findViewById(R.id.media_headline);
Toolbar toolbar = view.findViewById(R.id.toolbar);
((AppCompatActivity) getContext()).setSupportActionBar(toolbar);
source = view.findViewById(R.id.source);
mediaDate = view.findViewById(R.id.media_date);
Calendar fromDateInstance = Calendar.getInstance();
currentSelectedDate = fromDateInstance.getTime();
mediaDate.setText(Util.formatDate(fromDateInstance.getTime(), "dd MMM yyyy"));
final DatePickerDialog fromDatePicker = new DatePickerDialog(getContext(), (datePicker, year, month, date) -> {
fromDateInstance.set(Calendar.YEAR, year);
fromDateInstance.set(Calendar.MONTH, month);
fromDateInstance.set(Calendar.DATE, date);
currentSelectedDate = fromDateInstance.getTime();
mediaDate.setText(Util.formatDate(currentSelectedDate, "dd MMM yyyy"));
}, fromDateInstance.get(Calendar.YEAR), fromDateInstance.get(Calendar.MONTH), fromDateInstance.get(Calendar.DATE));
mediaDate.setOnClickListener(v -> fromDatePicker.show());
source.setOnClickListener(v -> alertDialog());
getSources();
return view;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
getActivity().onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
private void alertDialog() {
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(getContext());
builder.setTitle("Source");
builder.setSingleChoiceItems(adapter, checkedItem, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
source.setText(adapter.getItem(which).getName());
checkedItem = which;
dialog.dismiss();
}
});
builder.show();
}
}
And the xml of Add Media is:-
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.circularreveal.coordinatorlayout.CircularRevealCoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/myCoordinatorLayout"
android:layout_width="match_parent"
android:background="#color/white"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="com.google.android.material.appbar.AppBarLayout$Behavior"
android:theme="#style/AppTheme.AppBarOverlay">
<include layout="#layout/include_toolbar" />
</com.google.android.material.appbar.AppBarLayout>
<include
layout="#layout/content_add_media"
android:layout_width="match_parent"
app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior"
android:layout_height="match_parent"/>
</com.google.android.material.circularreveal.coordinatorlayout.CircularRevealCoordinatorLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.circularreveal.CircularRevealLinearLayout
android:id="#+id/dial"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_gravity="bottom|center_horizontal"
android:visibility="invisible"
android:layout_marginBottom="16dp"
app:layout_anchor="#id/fab"
app:layout_anchorGravity="top|center_horizontal"
android:background="#color/colorPrimary"
app:layout_behavior="com.google.android.material.transformation.FabTransformationSheetBehavior">
<ImageButton
android:id="#+id/back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/back"/>
</com.google.android.material.circularreveal.CircularRevealLinearLayout>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:backgroundTint="#color/colorPrimary"
app:srcCompat="#android:drawable/ic_dialog_email"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
For the FabTransformationSheetBehavior to work, you need to change the isExpanded value.
on change of this value, expand and collapse animation will be called and visibility of the linearlayout and fab button will be handled automatically. Don't change visibility manually as this would block transformation animation.
Use back button to transform back to FAB.
val fab: FloatingActionButton = findViewById<FloatingActionButton>(R.id.fab)
fab.setOnClickListener { fab.isExpanded = !fab.isExpanded } // this sets isExpanded as true
val back = findViewById<ImageButton>(R.id.back)
back.setOnClickListener{ fab.isExpanded = !fab.isExpanded } // this sets isExpanded as false
i wanted to use intro slider to my App
i learned it by this video https://www.youtube.com/watch?v=byLKoPgB7yA&t=22s
I do like video tutorial but I have a problem with dots
when I slide to any page the dots(. ) will be copy and increase
where is my problem and what should I do ?
package time.one.just.show.introslyder;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private ViewPager mSlideViewPager;
private LinearLayout mDotsLayout;
private SlyderAdapter slyderAdapter;
//dots of any Slide pages
private TextView[] mDots;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSlideViewPager = findViewById(R.id.viewPager);
mDotsLayout = findViewById(R.id.dots);
slyderAdapter = new SlyderAdapter(this);
mSlideViewPager.setAdapter(slyderAdapter);
addDotsIndiccator(0);
mSlideViewPager.addOnPageChangeListener(viewListener);
}
private void addDotsIndiccator(int position) {
mDots = new TextView[3];
for (int i = 0; i < mDots.length; i++) {
mDots[i] = new TextView(this);
mDots[i].setText(Html.fromHtml("•"));
mDots[i].setTextSize(35);
mDots[i].setTextColor(getResources().getColor(R.color.colorWhiteNearToGray));
mDotsLayout.addView(mDots[i]);
}
if (mDots.length > 0) {
mDots[position].setTextColor(getResources().getColor(R.color.colorWite));
}
}
ViewPager.OnPageChangeListener viewListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i1) {
}
#Override
public void onPageSelected(int i) {
addDotsIndiccator(i);
}
#Override
public void onPageScrollStateChanged(int i) {
}
};}
And this is my SideAdapter class
package time.one.just.show.introslyder;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class SlyderAdapter extends PagerAdapter {
Context context;
LayoutInflater layoutInflater;
public SlyderAdapter(Context context) {
this.context = context;
}
public int[] slide_imagesArray = {
R.drawable.eat,
R.drawable.men,
R.drawable.sleep};
public String[] slide_headerArray = {
"EAT", "men", "code"};
public String[] slide_descriptionArray = {
"this is 1st", "this is 2nd", "this is 3rd"
};
#Override
public int getCount() {
return slide_headerArray.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object o) {
return view == o;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.slide_layoout, container, false);
ImageView slideImageView = (ImageView) view.findViewById(R.id.slideImage);
TextView slideheader = (TextView) view.findViewById(R.id.slideheader);
TextView slidedescription = (TextView) view.findViewById(R.id.slideDescription);
slideImageView.setImageResource(slide_imagesArray[position]);
slideheader.setText(slide_headerArray[position]);
slidedescription.setText(slide_descriptionArray[position]);
container.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((RelativeLayout) object);
}
}
and this is my SliderLayout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent" android:layout_height="match_parent">
<ImageView
android:id="#+id/slideImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="89dp"
app:srcCompat="#drawable/eat" />
<TextView
android:id="#+id/slideheader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="122dp"
android:layout_marginBottom="287dp"
android:text="بدون نیاز به اینترنت"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/slideDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="0dp"
android:layout_marginBottom="171dp"
android:text="آرشیو کامل این خواننده محبوب همیشه در جیب شم ، ، هر کدام ز آهنگ ها را خواستید می توانید دانلود کنید و هر زمان دلتون خوست به آن ها گوش بدهید حتی بدون نیز به اینترنت" />
</RelativeLayout>
and activtymain xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:background="#drawable/main_background"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
<LinearLayout
android:id="#+id/dots"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:orientation="horizontal"></LinearLayout>
</RelativeLayout>
I found a solution
just by add this inside my App
mDotsLayout.removeAllViews();
thank you all
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>
I have three tabs with an unique fragment. How by images:
3 tab and a fragment
First problem is that when I click on "I watch it" on a movie and swipe on Watched's tab, this tab isn't updated.
https://i.imgur.com/AnnN3Zq.png?1
https://i.imgur.com/DsLGn3r.png
After if I swipe/tap on Notify's tab and comeback on Watched's tab, the tab has been updated. Why? Where am I wrong?
CoreActivity.java
package com.example.msnma.movienotifier;
import android.annotation.TargetApi;
import android.app.FragmentTransaction;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.example.msnma.movienotifier.MoviesFragment;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TabHost;
import android.widget.Toast;
import com.example.msnma.movienotifier.adapter.MoviesAdapter;
import com.example.msnma.movienotifier.notify.NotificationReceiver;
import com.example.msnma.movienotifier.event.TwoPaneEvent;
import org.greenrobot.eventbus.EventBus;
import butterknife.BindView;
import static android.support.v4.view.PagerAdapter.POSITION_NONE;
import static com.google.common.reflect.Reflection.initialize;
import static java.security.AccessController.getContext;
public class CoreActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener {
SectionsPageAdapter mSectionsPageAdapter;
#BindView(R.id.movies)
ViewPager mViewPager;
#BindView(R.id.tabs)
TabLayout tabLayout;
boolean twoPane;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_core);
Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
if (findViewById(R.id.movie_detail) != null) {
twoPane = true;
}
mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager(), twoPane);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setOffscreenPageLimit(1);
mViewPager.setAdapter(mSectionsPageAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.addOnTabSelectedListener(
new TabLayout.ViewPagerOnTabSelectedListener(mViewPager) {
#Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
final int numTab = tab.getPosition();
//Toast.makeText(getApplicationContext(),tab.getText(), Toast.LENGTH_LONG).show();
switch (tab.getPosition()) {
case 0: {
MoviesAdapter.setTipo(String.valueOf(MoviesFragment.Type.NOTIFY));
break;
}
case 1: {
MoviesAdapter.setTipo(String.valueOf(MoviesFragment.Type.SUGGESTED));
break;
}
case 2: {
MoviesAdapter.setTipo(String.valueOf(MoviesFragment.Type.WATCHED));
break;
}
}
}
});
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
//mViewPager.setCurrentItem(position);
// ci sono vicinissimo alla soluzione.
if(position == 0 || position == 2) {
Fragment getFragment = getSupportFragmentManager().getFragments().get(position);
if (getFragment instanceof MoviesFragment) {
MoviesFragment thisFragment = (MoviesFragment) getFragment;
thisFragment.onRefresh();
Log.i("REFRESH","Dovrebbe essere refreshato");
}
Log.i("PAGINASELEZIONATA", "Esegue onResume " + position);
}
//Toast.makeText(CoreActivity.this,"Tab "+position,Toast.LENGTH_LONG).show();
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
EventBus.getDefault().postSticky(new TwoPaneEvent(twoPane));
}
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_second, menu);
//MenuItem item = menu.findItem(R.id.search);
//searchView.setMenuItem(item);
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);
}
public void pressAccountButton(MenuItem item)
{
Intent intent = new Intent(this, AccountActivity.class);
startActivity(intent);
}
//nuovo codice
#Override
protected void onResume()
{
super.onResume();
if (!(mSectionsPageAdapter == null)) {
mSectionsPageAdapter.notifyDataSetChanged();
Log.i("INFOonResume", "Metodo onResume eseguito");
}
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
//Log.i("INFOTAB", "La tabella selezionata è "+tab.getTag());
onResume();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
}
Tap Notify's tap (believe also could tap on Suggested) and tap again Watched's tap
Second problem
In Watched's tab the textView are cut, why? How can I solve this?
MoviesAdapter.java
package com.example.msnma.movienotifier.adapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.example.msnma.movienotifier.MainActivity;
import com.example.msnma.movienotifier.MoviesFragment;
import com.example.msnma.movienotifier.R;
import com.example.msnma.movienotifier.database.MovieDatabase;
import com.example.msnma.movienotifier.databaseModel.MovieDBModel;
import com.example.msnma.movienotifier.model.Movie;
import java.util.Calendar;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Optional;
import static android.app.PendingIntent.getActivity;
import static com.example.msnma.movienotifier.MoviesFragment.*;
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.ViewHolder>{
private Context context;
private List<Movie> movies;
private View itemView;
private RecyclerView rv;
//per la data
private EditText fromDateEtxt;
private boolean active = false;
//private Context context;
private static String tipo = "NOTIFY";
public MoviesAdapter(Context context, List<Movie> movies) {
this.context = context;
this.movies = movies;
}
#Override
public MoviesAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView;
/*if(getTipo().equals("Suggested"))
{
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_movie, parent, false);
return new ViewHolder(itemView);
}
else if(getTipo().equals("Watched"))
{
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_movie_watched, parent, false);
return new ViewHolder(itemView);
}
else if(getTipo().equals("Notify"))
{*/
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_movie, parent, false);
return new ViewHolder(itemView);
//}
//return null;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
Movie movie = movies.get(position);
Glide.with(context)
.load(movie.getPosterUrl())
.placeholder(R.drawable.poster_placeholder)
.into(holder.posterView);
holder.title_movie.setText(movie.getTitle());
// prende solo la data + anno
String yourString = String.valueOf(movie.getReleaseDate());
String date = yourString.substring(0, 10);
String year = yourString.substring(yourString.length()-5,yourString.length());
holder.release_date.setText(date+year);
if(getTipo().equals("NOTIFY"))
{
Toast.makeText(context,"Notify", Toast.LENGTH_LONG).show();
holder.notifyButton.setVisibility(View.GONE);
holder.watchedButton.setVisibility(View.GONE);
holder.removeButton.setVisibility(View.VISIBLE);
}
//solo se è di tipo suggested
if(getTipo().equals("SUGGESTED"))
{
//disabilitare bottone remove
holder.removeButton.setVisibility(View.GONE);
holder.notifyButton.setVisibility(View.VISIBLE);
holder.watchedButton.setVisibility(View.VISIBLE);
Toast.makeText(context,"Suggested", Toast.LENGTH_LONG).show();
holder.notifyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*String testo = movies.get(position).getTitle().toString();
Toast tostato = Toast.makeText(context,testo,Toast.LENGTH_SHORT);
tostato.show();*/
alertFormElements(position);
}
});
holder.watchedButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*String testo = movies.get(position).getTitle()+ "\n" + "I WATCH IT";
Toast tostato = Toast.makeText(context,testo,Toast.LENGTH_SHORT);
tostato.show();*/
// public MovieDBModel(int id, String title, String overview, String posterUrl, String backdropUrl, String trailerUrl,
// Date releaseDate, float rating, boolean adult){
MovieDBModel mdm = new MovieDBModel(movies.get(position).getId(), movies.get(position).getTitle(), movies.get(position).getOverview(),
movies.get(position).getPosterUrl(), movies.get(position).getBackdropUrl(), movies.get(position).getTrailerUrl(),
movies.get(position).getReleaseDate(), movies.get(position).getRating(), movies.get(position).isAdult());
MovieDatabase.insertMovie(mdm, 2, MainActivity.getMovieDatabase());
String testo = "Added " + movies.get(position).getTitle() + "\n" + "in tab watched";
Toast tostato = Toast.makeText(context, testo, Toast.LENGTH_SHORT);
tostato.show();
}
});
}
if (getTipo().equals("WATCHED"))
{
holder.notifyButton.setVisibility(View.GONE);
holder.watchedButton.setVisibility(View.GONE);
holder.removeButton.setVisibility(View.VISIBLE);
holder.removeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
//da implementare
}
});
Toast.makeText(context,"WATCHED", Toast.LENGTH_LONG).show();
}
}
//nuovo codice riguardo l'alerDialog
public final void alertFormElements(final int position)
{
/*
* Inflate the XML view. activity_main is in
* res/layout/form_elements.xml
*/
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View formElementsView = inflater.inflate(R.layout.form_elements,
null, false);
// You have to list down your form elements
/*final CheckBox myCheckBox = (CheckBox) formElementsView
.findViewById(R.id.myCheckBox);*/
final RadioGroup genderRadioGroup = (RadioGroup) formElementsView
.findViewById(R.id.NotifyAlertRadioGroup);
//nuovo codice
genderRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
switch (checkedId)
{
case R.id.OneDayRadioButton:
actv(false);
break;
case R.id.ReleaseDayRadioButton:
actv(false);
break;
case R.id.OnRadioButton:
actv(true);
break;
}
}
});
//questo sarà sostituito con un calendario.
/*final EditText nameEditText = (EditText) formElementsView
.findViewById(R.id.nameEditText);*/
//parte data
fromDateEtxt = (EditText) formElementsView.findViewById(R.id.nameEditText);
fromDateEtxt.setEnabled(active);
fromDateEtxt.setClickable(active);
fromDateEtxt.setInputType(InputType.TYPE_NULL);
fromDateEtxt.requestFocus();
//metodo data
//setDateTimeField();
//fromDatePickerDialog.show();
fromDateEtxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Calendar c = Calendar.getInstance();
DatePickerDialog dpd = new DatePickerDialog( context ,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
fromDateEtxt.setText(dayOfMonth + "-"
+ (monthOfYear + 1) + "-" + year);
}
},
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
dpd.show();
}
});
// the alert dialog
new AlertDialog.Builder(context).setView(formElementsView)
.setTitle(movies.get(position).getTitle()+" Notify")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#TargetApi(11)
public void onClick(DialogInterface dialog, int id) {
//fromDateEtxt.setText(dateFormatter.format(newDate.getTime()));
String toastString = "";
String titleMovie = movies.get(position).getTitle();
String releaseDate = String.valueOf(movies.get(position).getReleaseDate());
String date = releaseDate.substring(0, 10);
String year = releaseDate.substring(releaseDate.length()-5,releaseDate.length());
releaseDate = date+year;
toastString = toastString + titleMovie + "\n" + releaseDate +"\n";
/*
* Detecting whether the checkbox is checked or not.
*/
/*if (myCheckBox.isChecked()) {
toastString += "Happy is checked!\n";
} else {
toastString += "Happy IS NOT checked.\n";
}*/
/*
* Getting the value of selected RadioButton.
*/
// get selected radio button from radioGroup
int selectedId = genderRadioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
RadioButton selectedRadioButton = (RadioButton) formElementsView
.findViewById(selectedId);
if(selectedRadioButton.getId() == R.id.OnRadioButton)
{
toastString += "Selected radio button is: " + fromDateEtxt.getText();
}
else {
toastString += "Selected radio button is: "
+ selectedRadioButton.getText() + "!\n";
}
/*
* Getting the value of an EditText.
*/
/*toastString += "Name is: " + nameEditText.getText()
+ "!\n";*/
Toast toast = Toast.makeText(context, toastString, Toast.LENGTH_LONG);
toast.show();
dialog.cancel();
}
}).show();
}
//nuovo codice
/*#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_movie, null);
holder = new ViewHolder();
holder.title_movie = (TextView) convertView.findViewById(R.id.movie_title);
holder.release_date = (TextView) convertView
.findViewById(R.id.movie_release_date);
Movie row_pos = movies.get(position);
//holder.profile_pic.setImageResource(row_pos.getProfile_pic_id());
holder.title_movie.setText(row_pos.getTitle());
holder.release_date.setText((CharSequence) row_pos.getReleaseDate());
//holder.contactType.setText(row_pos.getContactType());
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}*/
#Override
public void onViewRecycled(ViewHolder holder) {
super.onViewRecycled(holder);
Glide.clear(holder.posterView);
}
#Override
public int getItemCount() {
return movies.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.poster)
public ImageView posterView;
#BindView(R.id.movie_title)
public TextView title_movie;
#BindView(R.id.movie_release_date)
public TextView release_date;
#BindView(R.id.editNotify)
public Button notifyButton;
#BindView(R.id.iWatchItMovie)
public Button watchedButton;
#BindView(R.id.remove)
public Button removeButton;
public ViewHolder(View v) {
super(v);
ButterKnife.bind(this, v);
}
}
//parte per attivare/disattivare l'editText
private void actv(final boolean active)
{
fromDateEtxt.setEnabled(active);
if (active)
{
fromDateEtxt.requestFocus();
}
}
public static void setTipo(String tipo) {
MoviesAdapter.tipo = tipo;
}
public static String getTipo() {
return tipo;
}
}
For first, you can try adding similar logic to onPageScrolled
Fragment getFragment = getSupportFragmentManager().getFragments().get(position);
if (getFragment instanceof MoviesFragment) {
MoviesFragment thisFragment = (MoviesFragment) getFragment;
if ((position == 0 || position == 2) && positionOffset == 0.0 && positionOffsetPixels == 0)
thisFragment.onRefresh();
}
OK, #user47845 for (This is my list_item_movie.xml) you can try changed to this and tell us how are you doing.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="350px">
<android.support.constraint.ConstraintLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/card_background">
<ImageView
android:id="#+id/poster"
android:layout_width="120dp"
android:layout_height="139dp"
android:layout_marginEnd="10dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="10dp"
android:layout_marginStart="2dp"
android:contentDescription="TODO"
android:scaleType="centerCrop"
android:src="#drawable/poster_placeholder"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/movie_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:textSize="20dip"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/poster"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/movie_release_date"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textSize="20dip"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/poster"
app:layout_constraintTop_toBottomOf="#+id/movie_title" />
<Button
android:id="#+id/editNotify"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:onClick="pressEditNotifyButton"
android:text="Notify"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#+id/poster" />
<Button
android:id="#+id/iWatchItMovie"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:text="I watch it"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold"
app:layout_constraintEnd_toStartOf="#+id/remove"
app:layout_constraintStart_toEndOf="#+id/movie_title"
app:layout_constraintBottom_toBottomOf="parent" />
<Button
android:id="#+id/remove"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="21dp"
android:layout_marginRight="21dp"
android:background="#android:color/transparent"
android:text="Remove"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/iWatchItMovie" />
</android.support.constraint.ConstraintLayout>
</FrameLayout>
This is my list_item_movie.xml:
<?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="350px">
<!--android:layout_height="?android:attr/listPreferredItemHeight">-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_marginTop="4dp"
android:layout_marginBottom="4dp"
android:background="#drawable/card_background">
<ImageView
android:id="#+id/poster"
android:layout_width="185px"
android:layout_height="277px"
android:src="#drawable/poster_placeholder"
android:scaleType="centerCrop"
android:contentDescription="TODO" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center_vertical">
<TextView
android:id="#+id/movie_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textStyle="bold"
android:layout_gravity="left|center_vertical"
android:textSize="20dip"
android:layout_marginLeft="10dip"
/>
<TextView
android:id="#+id/movie_release_date"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="left|center_vertical"
android:textSize="20dip"
android:layout_marginLeft="10dip"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="bottom"
android:orientation="horizontal">
<Button
android:id="#+id/editNotify"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:onClick="pressEditNotifyButton"
android:text="Notify"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold" />
<Button
android:id="#+id/iWatchItMovie"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:text="I watch it"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold" />
<Button
android:id="#+id/remove"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:text="Remove"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</FrameLayout>
EDIT:
I have solved so:
<?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="350px">
<!--android:layout_height="?android:attr/listPreferredItemHeight">-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="2dp"
android:layout_marginTop="4dp"
android:layout_marginRight="2dp"
android:layout_marginBottom="4dp"
android:orientation="horizontal"
android:background="#drawable/card_background">
<ImageView
android:id="#+id/poster"
android:layout_width="185px"
android:layout_height="277px"
android:contentDescription="TODO"
android:scaleType="centerCrop"
android:src="#drawable/poster_placeholder" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/movie_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:layout_marginLeft="10dip"
android:layout_weight="1"
android:textSize="20dip"
android:textStyle="bold" />
<TextView
android:id="#+id/movie_release_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:layout_marginLeft="10dip"
android:layout_weight="1"
android:textSize="20dip" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="bottom"
android:orientation="horizontal">
<Button
android:id="#+id/editNotify"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:onClick="pressEditNotifyButton"
android:text="Notify"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold" />
<Button
android:id="#+id/iWatchItMovie"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:text="I watch it"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold" />
<Button
android:id="#+id/remove"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:text="Remove"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</FrameLayout>
I'm trying to inflate a RecyclerView which has as StaggeredGrid Layout, but it is not showing anything. I've pretty much copied previous code I've used before for the RecyclerView so I'm kind of stumped.
In MuseumStoriesViewHolder.onCreateViewHolder() the return of holder has the following value ViewHolder{337ec22b position=-1 id=-1, oldPos=-1, pLpos:-1 unboundundefined adapter position no parent} I'm not sure if this is realated, but it was something that seemed off to me.
It also might help to know that the fragment I'm inflating this RecyclerView is a nested Fragment.
Any help would be greatly appreciated.
MuseumFragment
package com.example.android.radiobuttontestproject.fragments;
import android.app.Activity;
import android.os.Bundle;
import android.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.android.radiobuttontestproject.R;
import com.example.android.radiobuttontestproject.adapters.MuseumStoriesAdapter;
import com.example.android.radiobuttontestproject.helpers.pojo.StoryObject;
import com.example.android.radiobuttontestproject.test.SampleDataFactory;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
public class MuseumFragment extends Fragment {
private List<StoryObject> storyObjectList;
private StaggeredGridLayoutManager storyGridLayoutManager;
private MuseumStoriesAdapter storyAdapter;
#Bind(R.id.stories_recycler_view) RecyclerView storiesRecyclerView;
public static MuseumFragment newInstance() {
MuseumFragment fragment = new MuseumFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
public MuseumFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_museum, container, false);
ButterKnife.bind(this, view);
//Sets up the stories
SampleDataFactory sampleDataFactory = new SampleDataFactory();
storyObjectList = sampleDataFactory.getSampleStories(
getResources().getStringArray(R.array.test_titles_for_grid_museum1),
getResources().getStringArray(R.array.test_desc_for_grid_museum1));
storyGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
storiesRecyclerView.setLayoutManager(storyGridLayoutManager);
storyAdapter = new MuseumStoriesAdapter(getActivity().getApplicationContext(), storyObjectList);
storiesRecyclerView.setAdapter(storyAdapter);
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
MuseumStoriesAdapter
package com.example.android.radiobuttontestproject.adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.radiobuttontestproject.R;
import com.example.android.radiobuttontestproject.helpers.pojo.StoryObject;
import java.util.List;
public class MuseumStoriesAdapter extends RecyclerView.Adapter<MuseumStoriesAdapter.MuseumStoriesViewHolder> {
private List<StoryObject> itemList;
private LayoutInflater inflater;
private Context context;
public MuseumStoriesAdapter(Context context, List<StoryObject> itemList) {
this.itemList = itemList;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
#Override
public MuseumStoriesViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View view = inflater.inflate(R.layout.view_box_small, viewGroup, false);
MuseumStoriesViewHolder holder = new MuseumStoriesViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MuseumStoriesViewHolder holder, int position) {
holder.title.setText(itemList.get(position).getTitle());
holder.desc.setText(itemList.get(position).getDescription());
}
#Override
public int getItemCount() {
return itemList.size();
}
class MuseumStoriesViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView type,title,desc;
public MuseumStoriesViewHolder(View itemView) {
super(itemView);
//Tried Butterknife, but it doesn't seem like it was working in the view holder. - Peter
type = (TextView) itemView.findViewById(R.id.small_box_type);
title = (TextView) itemView.findViewById(R.id.small_box_title);
desc = (TextView) itemView.findViewById(R.id.small_box_desc);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Clicked Position = " + getPosition(), Toast.LENGTH_SHORT).show();
}
}
}
fragment_museum.xml
<ScrollView
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="com.example.android.radiobuttontestproject.fragments.MuseumFragment">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1">
<TextView
android:id="#+id/museum_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/header_margin"
android:gravity="center"
android:textSize="#dimen/font_larger"
android:text="#string/museum_header" />
<android.support.v7.widget.RecyclerView
android:id="#+id/stories_recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>
view_box_small.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/small_box_margin"
android:background="#color/small_box_background_color">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!--TODO Make layout_height wrap contenet -->
<ImageView
android:layout_width="match_parent"
android:layout_height="120dp"
android:background="#color/test_color2"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:src="#drawable/abc_btn_rating_star_off_mtrl_alpha"
/>
</FrameLayout>
<TextView
android:id="#+id/small_box_type"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/font_small"
android:textColor="#color/font_red"
android:text="Object"
/>
<TextView
android:id="#+id/small_box_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/font_large"
android:textColor="#color/font_black"
android:text="Sample Text Here"
/>
<TextView
android:id="#+id/small_box_desc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/font_normal"
android:textColor="#color/font_black"
android:textStyle="italic"
android:text="Sample Text Here"
/>
</LinearLayout>