I am trying to place a fragment in my main activity(ReportFormActivity),which contains a customised listview.I want to inflate a custom layout containing 5 buttons and one spinner into it.I kEEP GETTING THE above error.Following is my complete code.
public class ReportFormActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_report_form);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); //forces the activity to be displayed in landscape mode.
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
public class ButtonRowFragment extends Fragment implements android.view.View.OnClickListener{
Button optionA;
Button optionB;
Button optionC;
Button optionD;
Button optionN;
Spinner interactiveTaskSpinner;
ListView list;
ButtonAdapter adapter;
public ButtonRowFragment CustomListView = null;
public ArrayList<ListModel> CustomListViewValuesArr = new ArrayList<ListModel>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//watch out here
View view= inflater.inflate(R.layout.listview, container, false);
CustomListView = this;
setListData();
Resources res = getResources();
list = (ListView)getView().findViewById(R.id.list);
adapter = new ButtonAdapter(CustomListView, CustomListViewValuesArr,res);
list.setAdapter(adapter);
optionA=(Button)view.findViewById(R.id.button1);
optionB=(Button)view.findViewById(R.id.button2);
optionC=(Button)view.findViewById(R.id.button3);
optionD=(Button)view.findViewById(R.id.button4);
optionN=(Button)view.findViewById(R.id.button5);
optionA.setOnClickListener(this);
optionB.setOnClickListener(this);
optionC.setOnClickListener(this);
optionD.setOnClickListener(this);
optionN.setOnClickListener(this);
interactiveTaskSpinner = (Spinner)view. findViewById(R.id.interactive_task_spinner);
return view;
}
public void setListData() {
for (int i = 0; i < 11; i++) {
final ListModel sched = new ListModel();
/******* Firstly take data in model object ******/
sched.setCompanyName("Button " + i);
sched.setImage("Spinner" + i);
sched.setUrl("http:\\www." + i + ".com");
/******** Take Model Object in ArrayList **********/
CustomListViewValuesArr.add(sched);
}
}
public void onItemClick(int mPosition)
{
ListModel tempValues = ( ListModel ) CustomListViewValuesArr.get(mPosition);
// SHOW ALERT
// Toast.makeText(CustomListView, ""+tempValues.getCompanyName() +" Image:"+tempValues.getImage() +" Url:"+tempValues.getUrl(), Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
switch(view.getId()){
case R.id.button1:
//DO something
optionA.setBackgroundColor(getResources().getColor(R.color.green));
optionC.setBackgroundColor(getResources().getColor(R.color.purple));
optionD.setBackgroundColor(getResources().getColor(R.color.purple));
optionN.setBackgroundColor(getResources().getColor(R.color.purple));
optionB.setBackgroundColor(getResources().getColor(R.color.purple));
break;
case R.id.button2:
//DO something
optionA.setBackgroundColor(getResources().getColor(R.color.purple));
optionC.setBackgroundColor(getResources().getColor(R.color.purple));
optionD.setBackgroundColor(getResources().getColor(R.color.purple));
optionN.setBackgroundColor(getResources().getColor(R.color.purple));
optionB.setBackgroundColor(getResources().getColor(R.color.green));
break;
case R.id.button3:
//DO something
optionA.setBackgroundColor(getResources().getColor(R.color.purple));
optionD.setBackgroundColor(getResources().getColor(R.color.purple));
optionN.setBackgroundColor(getResources().getColor(R.color.purple));
optionB.setBackgroundColor(getResources().getColor(R.color.purple));
optionC.setBackgroundColor(getResources().getColor(R.color.green));
break;
case R.id.button4:
//DO something
optionA.setBackgroundColor(getResources().getColor(R.color.purple));
optionC.setBackgroundColor(getResources().getColor(R.color.purple));
optionN.setBackgroundColor(getResources().getColor(R.color.purple));
optionB.setBackgroundColor(getResources().getColor(R.color.purple));
optionD.setBackgroundColor(getResources().getColor(R.color.green));
break;
case R.id.button5:
//DO something
optionA.setBackgroundColor(getResources().getColor(R.color.purple));
optionC.setBackgroundColor(getResources().getColor(R.color.purple));
optionD.setBackgroundColor(getResources().getColor(R.color.purple));
optionB.setBackgroundColor(getResources().getColor(R.color.purple));
optionN.setBackgroundColor(getResources().getColor(R.color.green));
break;
}
}
}
This is the xml layout for the ReportFormActivity
Below is the layout for listview(meant to be inflated in the listview)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Topic Presentation"
android:textSize="19px" />
<Button
android:id="#+id/button1"
android:layout_width="30dp"
android:layout_height="30dip"
android:background="#color/Purple"
android:text="A"
android:layout_marginLeft="30dp"
android:textColor="#color/white"
android:textSize="15dp"
android:textStyle="bold" />
<Button
android:id="#+id/button2"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="20dp"
android:background="#color/Purple"
android:text="B"
android:textColor="#color/white"
android:textSize="15dp"
android:textStyle="bold" />
<Button
android:id="#+id/button3"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="20dp"
android:background="#color/Purple"
android:text="C"
android:textColor="#color/white"
android:textSize="15dp"
android:textStyle="bold" />
<Button
android:id="#+id/button4"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="20dp"
android:background="#color/Purple"
android:text="D"
android:textColor="#color/white"
android:textSize="15dp"
android:textStyle="bold" />
<Button
android:id="#+id/button5"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginLeft="20dp"
android:background="#color/Purple"
android:text="NTP"
android:textColor="#color/white"
android:textSize="15dp"
android:textStyle="bold" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="31dp" />
</LinearLayout>
Related
I have set up a RecyclerView adapter with ViewPager in an activity namely TvShowEpisodeDetails , it works well but there is one issue, the Layout of RecyclerView is fixed while scrolling up and down in the Fragment(TvShowEpisodeDetailsFragment). But I want it to scroll with them.
The RecyclerView and ViewPager are both set inside viewpager_with_toolbar_overlay.xml Layout , and both has been settup in The Activity.
TvShowEpisodeDetailsFragment is the fragment class which belongs to activity class TvShowEpisodeDetails , the fragment creates as many episodes as a TV Show season can offer.
And off course this issue will be gone if I set RecyclerView adapter inside fragment, but I will get non-fixable highlighting and scrolling issues , that is why I set it inside the activity because it does not give those issues.
I need to make it work somehow inside the activity.
My goal is that RecyclerView and ViewPager has to be in the same layout XML file and they both must either be in the activity or fragment class
Is it possible to make the RecyclerView scroll with rest of the fragment layouts?
or
Is it possible to do it programmatically?
Here is the activity
public class TvShowEpisodeDetails extends MizActivity{
#Override
protected int getLayoutResource() {
return R.layout.viewpager_with_toolbar_overlay;
}
#Override
public void onCreate(Bundle savedInstanceState) {
mBus = MizuuApplication.getBus();
super.onCreate(savedInstanceState);
// Set theme
setTheme(R.style.Mizuu_Theme_NoBackground);
// setting episodeslist
final ArrayList<PlanetModel> episodeslist = new ArrayList<>();
for(TvShowEpisode e : mEpisodes){
episodeslist.add(new PlanetModel(e.mEpisode));
}
// setting RecyclerView
mEpisodesList = (RecyclerView) findViewById(R.id.episodesLIST);
// Setting LinearLayoutManager
LinearLayoutManager layoutManager
= new LinearLayoutManager(this.getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
//mEpisodesList.setLayoutManager(new LinearLayoutManager(mContext));
mEpisodesList.setLayoutManager(layoutManager);
// Setting RecyclerView Adapter
PlanetAdapter.OnItemClickListener indicatorCallback = new PlanetAdapter.OnItemClickListener() {
#Override
public void onItemClick(String item) {
SharedPreferences getPref = getContext().getSharedPreferences("PlanetAdapter", Context.MODE_PRIVATE);
int pos = getPref.getInt("newPosition", 0);
mViewPager.setCurrentItem(pos,false);
}
};
final PlanetAdapter planetAdapter = new PlanetAdapter(episodeslist,indicatorCallback);
mEpisodesList.setAdapter(planetAdapter);
// Setting ViewPager
mViewPager = (ViewPager) findViewById(R.id.awesomepager);
mViewPager.setAdapter(new TvShowEpisodeDetailsAdapter(getSupportFragmentManager()));
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
planetAdapter.setSelectedIndex(position);
planetAdapter.notifyDataSetChanged();
mEpisodesList.smoothScrollToPosition(position);
//mEpisodesList.scrollToPosition(position);
for (int i=0; i<episodeslist.size(); i++)
{
episodeslist.get(i).setPlanetSelected(false);
}
episodeslist.get(position).setPlanetSelected(true);
ViewUtils.updateToolbarBackground(TvShowEpisodeDetails.this, mToolbar, 0, mEpisodes.get(position).getTitle(), Color.TRANSPARENT);
}
});
if (savedInstanceState != null) {
mViewPager.setCurrentItem(savedInstanceState.getInt("tab", 0));
} else {
for (int i = 0; i < mEpisodes.size(); i++) {
if (mEpisodes.get(i).getSeason().equals(MizLib.addIndexZero(mSeason)) && mEpisodes.get(i).getEpisode().equals(MizLib.addIndexZero(mEpisode))) {
mViewPager.setCurrentItem(i);
break;
}
}
}
}
}
viewpager_with_toolbar_overlay
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
android:id="#+id/awesomepager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#068006"
android:layout_marginTop="450dp"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/episodesLIST"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:scrollbars="horizontal" />
</LinearLayout>
<include layout="#layout/toolbar_layout" />
</FrameLayout>
Here is the XML layout of the fragment which is inflated in onCreateView of the fragment class
episode_details.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/abc_input_method_navigation_guard">
<com.miz.views.ObservableScrollView
android:id="#+id/observableScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/episodePhoto"
android:layout_width="match_parent"
android:layout_height="#dimen/backdrop_portrait_height"
android:scaleType="centerCrop"
android:src="#drawable/bg" />
<com.melnykov.fab.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/episodePhoto"
android:layout_alignParentEnd="false"
android:layout_alignParentRight="true"
android:layout_marginTop="#dimen/content_details_fab_negative_margin"
android:layout_marginRight="#dimen/content_details_baseline_margin"
android:src="#drawable/ic_play_arrow_white_36dp"
app:fab_colorNormal="#666"
app:fab_type="mini" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/fab"
android:layout_marginLeft="#dimen/content_details_baseline_margin"
android:layout_marginTop="#dimen/content_details_title_margin_top"
android:layout_marginRight="#dimen/content_details_baseline_margin"
android:layout_toLeftOf="#+id/fab"
android:orientation="vertical">
<TextView
android:id="#+id/movieTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="3"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_title" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/content_details_very_small_margin"
android:layout_marginBottom="#dimen/content_details_baseline_margin"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_subheader"
android:textStyle="bold|italic" />
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:id="#+id/details_area"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#666"
android:baselineAligned="false"
android:elevation="1dp"
android:minHeight="#dimen/content_details_large_margin"
android:orientation="horizontal"
android:paddingLeft="#dimen/content_details_baseline_margin"
android:paddingTop="#dimen/content_details_small_margin"
android:paddingRight="#dimen/content_details_baseline_margin"
android:paddingBottom="#dimen/content_details_small_margin">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="center_horizontal"
android:lines="1"
android:maxLines="1"
android:text="#string/detailsAirDate"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="#dimen/content_details_area_subheader" />
<TextView
android:id="#+id/textReleaseDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_area_header"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/textView61"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="center_horizontal"
android:lines="1"
android:maxLines="1"
android:text="#string/detailsRating"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="#dimen/content_details_area_subheader" />
<TextView
android:id="#+id/textView12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_area_header"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="#dimen/content_details_baseline_margin">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/content_details_baseline_margin"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/director"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_movie_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/writer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_edit_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/guest_stars"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_people_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_folder_open_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_body_text" />
</LinearLayout>
</LinearLayout>
</com.miz.views.ObservableScrollView>
<FrameLayout
android:id="#+id/progress_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg"
android:visibility="gone">
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</FrameLayout>
</FrameLayout>
Update
Fragment
#SuppressLint("InflateParams") public class TvShowEpisodeDetailsFragment extends Fragment {
public TvShowEpisodeDetailsFragment() {}
public static TvShowEpisodeDetailsFragment newInstance(String showId, int season, int episode) {
TvShowEpisodeDetailsFragment pageFragment = new TvShowEpisodeDetailsFragment();
Bundle bundle = new Bundle();
bundle.putString("showId", showId);
bundle.putInt("season", season);
bundle.putInt("episode", episode);
pageFragment.setArguments(bundle);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
mContext = getActivity();
mBus = MizuuApplication.getBus();
mShowFileLocation = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean(SHOW_FILE_LOCATION, true);
mPicasso = MizuuApplication.getPicassoDetailsView(getActivity());
mMediumItalic = TypefaceUtils.getRobotoMediumItalic(mContext);
mMedium = TypefaceUtils.getRobotoMedium(mContext);
mCondensedRegular = TypefaceUtils.getRobotoCondensedRegular(mContext);
mDatabaseHelper = MizuuApplication.getTvEpisodeDbAdapter();
LocalBroadcastManager.getInstance(mContext).registerReceiver(mBroadcastReceiver,
new IntentFilter(LocalBroadcastUtils.UPDATE_TV_SHOW_EPISODE_DETAILS_OVERVIEW));
loadEpisode();
}
#Override
public void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mBroadcastReceiver);
}
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
loadEpisode();
loadData();
}
};
private void loadEpisode() {
if (!getArguments().getString("showId").isEmpty() && getArguments().getInt("season") >= 0 && getArguments().getInt("episode") >= 0) {
Cursor cursor = mDatabaseHelper.getEpisode(getArguments().getString("showId"), getArguments().getInt("season"), getArguments().getInt("episode"));
if (cursor.moveToFirst()) {
mEpisode = new TvShowEpisode(getActivity(),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SHOW_ID)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_TITLE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_PLOT)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_AIRDATE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_DIRECTOR)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_WRITER)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_GUESTSTARS)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_RATING)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_HAS_WATCHED)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_FAVOURITE))
);
mEpisode.setFilepaths(MizuuApplication.getTvShowEpisodeMappingsDbAdapter().getFilepathsForEpisode(
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SHOW_ID)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE))
));
}
cursor.close();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.episode_details, container, false);
}
#Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mBackdrop = (ImageView) view.findViewById(R.id.imageBackground);
mEpisodePhoto = (ImageView) view.findViewById(R.id.episodePhoto);
mDetailsArea = view.findViewById(R.id.details_area);
mTitle = (TextView) view.findViewById(R.id.movieTitle);
mSeasonEpisodeNumber = (TextView) view.findViewById(R.id.textView7);
mDescription = (TextView) view.findViewById(R.id.textView2);
mFileSource = (TextView) view.findViewById(R.id.textView3);
mAirDate = (TextView) view.findViewById(R.id.textReleaseDate);
mRating = (TextView) view.findViewById(R.id.textView12);
mDirector = (TextView) view.findViewById(R.id.director);
mWriter = (TextView) view.findViewById(R.id.writer);
mGuestStars = (TextView) view.findViewById(R.id.guest_stars);
mScrollView = (ObservableScrollView) view.findViewById(R.id.observableScrollView);
mFab = (FloatingActionButton) view.findViewById(R.id.fab);
mFab.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ViewUtils.animateFabJump(v, new SimpleAnimatorListener() {
#Override
public void onAnimationEnd(Animator animation) {
play();
}
});
}
});
...
}
...
}
I have set up a RecyclerView adapter with ViewPager in an activity namely TvShowEpisodeDetails , it works well but there is one issue, the Layout of RecyclerView is fixed while scrolling up and down in the Fragment(TvShowEpisodeDetailsFragment). But I want it to scroll with them.
It's hard to use the RecyclerView outside of the ViewPager page fragment; because you can't synchronize and link the touch/motion events when you scroll the page up/down (or when you swipe to next/previous page) between both the page fragment and a standalone (i.e. activity) RecyclerView. Even that won't be smooth.
So, the RecyclerView should be a part of the ViewPager page.
And off course this issue will be gone if I set RecyclerView adapter inside fragment, but I will get unfixable highlighting and scrolling issues
So, now the issue of adding the RecyclerView in the ViewPager fragment is the highlighting issue of the RecyclerView item when you click on any item or when you swipe the ViewPager to right/left page.
But, the main issue is that there is a RecyclerView instance per page, i.e. if you have 5 pages, then you have 5 RecyclerViews.
So, it's a cumbersome to track highlighting only within the RecyclerView adapter class. And hence manipulating that with OnClickListeners solely will have issues of linking these RecyclerView and adapter instances together to update their highlighting item.
So, a simpler approach is to pass a parameter to the RecyclerView adapter with the selected item (which is definitely equals to the current ViewPager page position).
And then do a check in the onBindViewHolder() if the position equals to the passed-in value, then highlight the item; otherwise keep items with the original color.
So, wrapping this up into actions:
Change the adapter constructor to accept a highlighted_position parameter
public PlanetAdapter(ArrayList<PlanetModel> episodeslist,
int highlightedPosition, OnItemClickListener listener)
Whenever you create the ViewPager fragment using newInstance() pass-in the current position of the page fragment:
So, in the TvShowEpisodeDetails activity:
for (int i = 0; i < mEpisodes.size(); i++)
fragments.add(TvShowEpisodeDetailsFragment
.newInstance(mShowId,
Integer.parseInt(mEpisodes.get(i).getSeason()),
Integer.parseInt(mEpisodes.get(i).getEpisode()),
i)); // The position
And in the TvShowEpisodeDetailsFragment fragment, register this into a field in the fragment argument:
public static TvShowEpisodeDetailsFragment newInstance(String showId, int season, int episode, int position) { // adding position
TvShowEpisodeDetailsFragment pageFragment = new TvShowEpisodeDetailsFragment();
Bundle bundle = new Bundle();
// trimmed code.
bundle.putInt("position", position); // <<<< into the bundle
pageFragment.setArguments(bundle);
return pageFragment;
}
And set that in the adapter creation:
int currentPosition = getArguments().getInt("position");
planetAdapter = new PlanetAdapter(episodeslist, currentPosition, new PlanetAdapter.OnItemClickListener() {
#Override
public void onItemClick(final int pos) {
mCallback.sendText(pos);
}
});
And reflect that in the adapter to highlight the item:
public class PlanetAdapter extends RecyclerView.Adapter<PlanetAdapter.PlanetViewHolder> {
private final int highlightedPos;
public PlanetAdapter(ArrayList<PlanetModel> episodeslist, int highlightedPosition, OnItemClickListener listener) {
this.episodeslist = episodeslist;
this.listener = listener;
this.highlightedPos = highlightedPosition; // <<< set the position
}
#Override
public void onBindViewHolder(PlanetAdapter.PlanetViewHolder vh, final int position) {
TextView tv = (TextView) vh.itemView;
PlanetModel planetModel = episodeslist.get(position);
tv.setText(planetModel.getPlanetName());
tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.bg, 0, 0, 0);
if (highlightedPos == position) { //<<<<< Highlight the item
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryLight));
Log.d("LOG_TAG", "onClick: Highlight item: " + highlightedPos);
} else {
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryDark));
Log.d("LOG_TAG", "onClick: No highlight: " + highlightedPos);
}
}
}
I'm trying to make a stopwatch in one of my fragments but I'm am unable to get the stopwatch to start. Ideally it would start after pressing startButton but I can't even get the start() function to work at all. Right now this is what I have:
Fragment:
public class RunFragment extends Fragment implements View.OnClickListener {
private Chronometer sChronometer;
private long pauseOffset;
private boolean running;
Button startRun;
Button pauseRun;
Button stopRun;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public RunFragment() {
// Required empty public constructor
}
public void disable(View startButton){
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment RunFragment.
*/
// TODO: Rename and change types and number of parameters
public static RunFragment newInstance(String param1, String param2) {
RunFragment fragment = new RunFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_run, container, false);
Button startRun = (Button) v.findViewById(R.id.startRun);
Button pauseRun = (Button) v.findViewById(R.id.pauseRun);
Button stopRun = (Button) v.findViewById(R.id.stopRun);
sChronometer = (Chronometer) v.findViewById(R.id.sChronometer);
startRun.setOnClickListener(this);
pauseRun.setOnClickListener(this);
stopRun.setOnClickListener(this);
return v;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.startRun:
sChronometer.setBase(SystemClock.elapsedRealtime());
sChronometer.start();
Toast.makeText(getActivity().getApplicationContext(), "startRun", Toast.LENGTH_SHORT).show();
break;
case R.id.pauseRun:
Toast.makeText(getActivity().getApplicationContext(), "pauseRun", Toast.LENGTH_SHORT).show();
break;
case R.id.stopRun:
Toast.makeText(getActivity().getApplicationContext(), "stopRun", Toast.LENGTH_SHORT).show();
break;
}
}
I'm not receiving any errors and the Toasts are showing up so I'm not sure what the problem is.
Here is the xml code:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".RunFragment">
<data>
<variable name="runLive" type="com.example.wam1.RunLive"/>
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="450dp"
android:gravity="center"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/startRun"
android:onClick="startRun"
android:text="Start" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/pauseRun"
android:onClick="pauseRun"
android:text="Pause" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/stopRun"
android:onClick="stopRun"
android:text="Stop" />
</LinearLayout>
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginVertical="100dp"
android:layout_marginHorizontal="10dp"
android:background="#f1f1f1"
>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Distance"
android:textStyle="bold"
android:layout_weight="1"
android:gravity= "center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Heart Rate"
android:textStyle="bold"
android:layout_weight="1"
android:gravity= "center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pace"
android:textStyle="bold"
android:layout_weight="1"
android:gravity= "center" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{runLive.distance}"
android:layout_weight="1"
android:gravity= "center"
android:background="#ffffff"
android:layout_marginBottom="1dp"
android:layout_marginHorizontal="1dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{runLive.heartRate}"
android:layout_weight="1"
android:gravity= "center"
android:background="#ffffff"
android:layout_marginRight="1dp"
android:layout_marginBottom="1dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{runLive.pace}"
android:layout_weight="1"
android:gravity= "center"
android:background="#ffffff"
android:layout_marginRight="1dp"
android:layout_marginBottom="1dp"/>
</TableRow>
</TableLayout>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Recomendation"
android:textSize="32sp"
android:layout_centerHorizontal="true"
android:layout_marginTop="250dp"/>
<Chronometer
android:id="#+id/sChronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:format="00:00:00"
android:textSize="35sp">
</Chronometer>
</RelativeLayout>
</layout>
Any help or insight would be greatly appreciated!
since you are implementing an interface 'View.onClickListener', you should define it's method onClick and not your own. That difference can be made from you not overriding the onClick method. Just change your onClick method to
#Override
public void onClick(View view) {
//super.onClick(view);
switch (v.getId()) {
case R.id.startRun:
sChronometer.setBase(SystemClock.elapsedRealtime());
sChronometer.start();
Toast.makeText(getActivity().getApplicationContext(), "startRun", Toast.LENGTH_SHORT).show();
break;
case R.id.pauseRun:
Toast.makeText(getActivity().getApplicationContext(), "pauseRun", Toast.LENGTH_SHORT).show();
break;
case R.id.stopRun:
Toast.makeText(getActivity().getApplicationContext(), "stopRun", Toast.LENGTH_SHORT).show();
break;
}
}
Intro:
To put things into perspective, I am attempting to use fragments to create a Sudoku game.
The Sudoku board consists of 9 sub-grids, each containing 9 cells, so 9 cells in one grid, and 9 of these grids form the Sudoku board, arranged in a 3x3 fashion.
Method:
Home screen containing some information, of which a GridLayout contains 9 Framelayouts where each Sudoku Fragment will be placed into
The 9 Sudoku Fragments will make up the Sudoku board.
sudoku_cell extends a LinearLayout with an onClickListener, since extending a TextView, I was unable to inflate the sudoku_cell layout (Is it possible to do so?)
In my main activity, I have a GridLayout containing 9 FrameLayouts. These layouts have column and row locations set to form a 3x3 matrix, this is where each of the fragments will be added into.
These FrameLayouts are named on a 0-based index: frame00, frame01, frame02, frame10, etc
Documentation says:
As mentioned here on developer.android.com, I am required to have an:
Inflator method for the fragment, i.e. onCreateView() which inflates the fragment
A Layout container of sorts to root/place the fragment in, in the main activity (in my case)
A FragmentManager and FragmentTransactionManager to handle the fragments, adding and commiting them.
Problem:
TL;DR: Simply, my fragments are not showing.
After calling the commit(), I expect to see a 3x3 board of sudoku_grid fragments, each containing 9 sudoku_cells. However, this does not get shown
I have searched SO, reread the documentation, and searched more but cannot understand why it is not showing.
I have tried:
When inflating my fragment, I inflate a sudoku_cell layout instead, this does infact show a 9 cell grid.
However each cell should be a grid containing 9 cells, this leads me to believe that there may be an issue on the Sudoku_Grid - Sudoku_Cell side, possibly the sudoku_cell layout is not being inflated correctly or being rooted correctly.
Usually an LayoutInflator, and ViewGroup is passed allowing one to inflate a layout, but in the case of the sudoku_cell, I cannot find such a method to override, is this the cause?
The code:
sudoku_cell.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/cellText"
android:layout_width="35dp"
android:layout_margin="1px"
android:textSize="18dp"
android:layout_height="35dp"
android:textAlignment="center"
android:textColor="#color/clBlack">
</TextView>
</LinearLayout>
SudokuCell.java
public class SudokuCell extends LinearLayout{
private LinearLayout layout;
private TextView textView;
private Context mContext;
private Point location;
private int index;
public SudokuCell(Context context) {
super(context);
}
public SudokuCell(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layout = (LinearLayout) inflater.inflate(R.layout.sudoku_cell, this, true);
textView = layout.findViewById(R.id.cellText);
setText("");
}
public void setStaticText(String s){
if (textView != null) {
textView.setText(s);
textView.setTypeface(textView.getTypeface(), Typeface.BOLD);
}
}
public void setText(String s){
if (textView != null)
textView.setText(s);
}
public Point getLocation() {
return location;
}
public void setLocation(Point location) {
this.location = location;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
9 of these sudoku_cell's get added to a sudoku_grid as shown below in the onCreateView() and populateGrid() methods:
sudoku_grid.xml
<?xml version="1.0" encoding="utf-8"?>
<GridLayout
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:layout_margin="2px"
android:id="#+id/grid_layout"
android:columnCount="3"
android:rowCount="3">
</GridLayout>
SudokuGrid.java
public class SudokuGrid extends Fragment{
private GridLayout gridLayout;
private List<GridFragmentListener> listeners = new ArrayList<>();
private Context mActitityContext;
private boolean FRAGMENT_LOCATION_CENTRE;
private float SCREEN_DP;
private int GRID_MARGINS_DP = 1;
private int colorOdd, colorEven;
private List<Integer> presetGrid;
private View previousView;
private Drawable previousViewDrawable;
public void addGridListener(GridFragmentListener gridFragmentListener) {
listeners.add(gridFragmentListener);
}
public void removeGridListener(GridFragmentListener gridFragmentListener) {
listeners.remove(gridFragmentListener);
}
protected void notifyValueChanged(View value) {
for (GridFragmentListener listener : listeners) listener.onValueChange(value);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mActitityContext = getActivity();
View v = inflater.inflate(R.layout.sudoku_grid, container, false);
//set grid view
gridLayout = v.findViewById(R.id.grid_layout);
populateGrid();
return v;
}
private void populateGrid() {
for (int i = 0; i < 9; i++) {
SudokuCell sudokuCell = new SudokuCell(mActitityContext);
sudokuCell.setBackgroundColor(((i % 2) == 0) ? R.color.clOdd : R.color.clEven);
System.out.printf("Sudoku Cell ID [ index = " + String.valueOf(i) + " ] - getId() = " + sudokuCell.getId());
sudokuCell.setLocation(getPoint(i));
sudokuCell.setIndex(i);
sudokuCell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
notifyValueChanged(view);
}
});
sudokuCell.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean b) {
SudokuCell cell = (SudokuCell) view;
if (b)
view.setBackgroundColor(ContextCompat.getColor(mActitityContext, R.color.clSelected));
else
view.setBackgroundColor(ContextCompat.getColor(mActitityContext, (cell.getIndex() % 2 == 0) ? R.color.clOdd : R.color.clEven));
}
});
sudokuCell.setStaticText(String.valueOf(i));
gridLayout.addView(sudokuCell, i);
}
}
private Point getPoint(int i) {
int y = 0;
while (i > 2){
y++;
i -= 3;
}
return new Point(i, y);
}
#Override
public void onStart() {
super.onStart();
try {
addGridListener((GridFragmentListener) getActivity());
} catch (ClassCastException e) {
throw new ClassCastException(
getActivity().getClass().toString()
+ " does not implement the DetailsFragment.DetailsFragmentListener interface.");
}
}
#Override
public void onStop() {
super.onStop();
removeGridListener((GridFragmentListener) getActivity());
}
}
In my main activity, I handle the creation of 9 sudoku_grid fragments which are placed into each respective FrameLayout, to form a 3x3 matrix of Sudoku_Grids, which will form the Sudoku board
activity_main_sudoku.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="wrap302.nmu.task1.MainActivitySudoku"
android:background="#color/clDarkGrey">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:id="#+id/linearLayout2">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:text="#string/app_title"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:textColor="#color/clWhite"
android:textAppearance="#style/TextAppearance.AppCompat.Display1"
android:textAlignment="center"
android:textStyle="bold"
android:fontFamily="sans-serif"/>
<TextView
android:text="#string/lblScore"
android:textColor="#color/clWhite"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:id="#+id/lblScore"
android:textAppearance="#style/TextAppearance.AppCompat.Button" android:textAlignment="center"
android:layout_marginBottom="5dp"/>
</LinearLayout>
<GridLayout
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnCount="3"
android:rowCount="3"
android:id="#+id/main_sudokugrid_container">
<FrameLayout
android:layout_column="0"
android:layout_row="0"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame00"/>
<FrameLayout
android:layout_column="1"
android:layout_row="0"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame01"/>
<FrameLayout
android:layout_column="2"
android:layout_row="0"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame02"/>
<FrameLayout
android:layout_column="0"
android:layout_row="1"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame10"/>
<FrameLayout
android:layout_column="1"
android:layout_row="1"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame11"/>
<FrameLayout
android:layout_column="2"
android:layout_row="1"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame12"/>
<FrameLayout
android:layout_column="0"
android:layout_row="2"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame20"/>
<FrameLayout
android:layout_column="1"
android:layout_row="2"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame21"/>
<FrameLayout
android:layout_column="2"
android:layout_row="2"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame22"/>
</GridLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center" android:id="#+id/linearLayout">
<GridLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:paddingTop="0dp">
<Button
android:layout_row="0"
android:layout_column="0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn1"
android:text="1"/>
<Button
android:layout_row="0"
android:layout_column="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn2"
android:text="2"/>
<Button
android:layout_row="0"
android:layout_column="2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn3"
android:text="3"/>
<Button
android:layout_row="1"
android:layout_column="0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn4"
android:text="4"/>
<Button
android:layout_row="1"
android:layout_column="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn5"
android:text="5"/>
<Button
android:layout_row="1"
android:layout_column="2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn6"
android:text="6"/>
<Button
android:layout_row="2"
android:layout_column="0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn7"
android:text="7"/>
<Button
android:layout_row="2"
android:layout_column="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn8"
android:text="8"/>
<Button
android:layout_row="2"
android:layout_column="2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn9"
android:text="9"/>
<Button
android:layout_row="0"
android:layout_column="3"
android:layout_rowSpan="3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_vertical"
android:id="#+id/btnClear"
android:text="Clear"/>
</GridLayout>
</LinearLayout>
</RelativeLayout>
MainActivitySudoku.java
public class MainActivitySudoku extends AppCompatActivity implements GridFragmentListener {
private FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_sudoku);
createSudokuGrid();
}
private void createSudokuGrid() {
fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransactionManager = fragmentManager.beginTransaction();
fragmentTransactionManager.add(R.id.frame00, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame01, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame02, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame10, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame11, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame12, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame20, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame21, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame22, new SudokuGrid());
fragmentTransactionManager.commit();
}
#Override
protected void onStart() {
super.onStart();
Toast.makeText(this, "Activity Started & Viewable", Toast.LENGTH_SHORT).show();
}
// GridFragmentListener
#Override
public void onValueChange(View view) {
//todo something here with received view
}
}
Well, the solution proved simpler than expected.
In short, the solution was to move the SudokuCell constructor code from the
SudokuCell(Context context, AttributeSet attrs)
to the
SudokuCell(Context context)
since that was the constructor I was calling.
A few other changes can be made for improvement, this solves the fragments not being displayed.
Quite a simple error
Ok - I have given you a sample of how to add your fragments so they will display. If you go through this and emulate the process this will assist you. I've used basic examples in the layout so we can have ids to use in the classes.
You'll also need to manage the app lifecycle and the back press button on how you want to manage your stack with your fragments and maintaining any data.
Activity
public class MyActivity extends Activity {
Fragment fragment;
FrameLayout frameLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_myactivity);
View view = this.findViewById(android.R.id.content);
frameLayout = (FrameLayout) findViewById(R.id.frag);
fragment = new MyFragment();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.frag, fragment);
fragmentTransaction.commit();
}
}
Layout for Activity
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
.../...>
.../...
<FrameLayout
android:id="#+id/frag"
// sort out your layout here with the frameLayouts
android:layout_below="#+id/your_id"
/>
.../...
</RelativeLayout>
Fragment
public class MyFragmentextends Fragment {
FragmentManager fragmentManager;
Fragment fragment;
public static MyFragmentnewInstance(String item {
fragment =
new MyFragment();
// pass data from activity
Bundle args = new Bundle();
args.putString(ITEM, item);
fragment.setArguments(args);
return fragment;
}
public DeliveryDisplayFromDispenserFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
item = getArguments().getString(ITEM);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view =
inflater.inflate(R.layout.myfragment, container, false);
}
}
Layout for Fragment
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
.../...>
// fragment layout
</RelativeLayout>
i have a Navigation Drawer that it is a Fragment. now I want to set onitemclickListener for the items in the ListView of the navDrawer. But i cannot do it.
Java Class:
public class Welcome extends AppCompatActivity {
private drawer_navigation dn;
private ListView lv;
private List<HashMap<String,Object>> list= new ArrayList<>();
private final String get_cat="http://advertapp.siavoshdjazmi.ir/get_cat.php";
private final String get_ads="http://advertapp.siavoshdjazmi.ir/get_data.php?page=";
private final String get_ads_by_cat="http://advertapp.siavoshdjazmi.ir/get_data_by_cat.php?cat=";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
Toolbar toolbar= (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
dn = (drawer_navigation) getSupportFragmentManager().findFragmentById(R.id.drawer_navigation);
dn.setUp((DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
getSupportActionBar().setIcon(R.mipmap.ic_launcher);
lv= (ListView)findViewById(R.id.category_lv);
makeCategoryList();
View v= findViewById(R.id.category_lv);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i= new Intent(getApplicationContext(),Advertisment_list.class);
i.putExtra("url_data_by_id",get_ads_by_cat+list.get(position).get("id").toString());
i.putExtra("flag","1");
startActivity(i);
Log.i("app_error","Click Listener");
my_alert("test","test",true);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater= getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id=item.getItemId();
if(id==R.id.settings){
Toast.makeText(getApplicationContext(),"تنظیمات برنامه",Toast.LENGTH_LONG).show();
}
return true;
}
/* Category List Of Navigation Drawer */
public void makeCategoryList(){
DownloaderCategory dc= new DownloaderCategory();
dc.execute(get_cat);
}
private class DownloaderCategory extends AsyncTask<String,Void,String>{
#Override
protected String doInBackground(String... params) {
String temp="";
try{
JSONDownloader jd= new JSONDownloader();
temp= jd.downloadUrl(params[0]);}
catch (Exception e){
Log.i("app_error", "Error in Download Category Task Class//////" + e.toString());
}
return temp;
}
#Override
protected void onPostExecute(String s) {
LoadCategoryList lc= new LoadCategoryList();
lc.execute(s);
}
}
private class LoadCategoryList extends AsyncTask<String, Void, SimpleAdapter>{
#Override
protected SimpleAdapter doInBackground(String... params) {
try {
ParseCat pc = new ParseCat();
list.addAll(pc.parse(params[0]));
}
catch (Exception e){
Log.i("app_error", "Error in Download Category Task Class//////" + e.toString());
}
String[] from={"name","count"};
int[] to ={R.id.cat_name,R.id.cat_count};
// myAdapter adapter = new myAdapter(getBaseContext(),list,R.layout.category_list_drawer,from,to);
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(),list,R.layout.category_list_drawer,from,to);
return adapter;
}
#Override
protected void onPostExecute(SimpleAdapter simpleAdapter) {
lv.setAdapter(simpleAdapter);
}
}
XML file: `
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="192dp"
android:background="#drawable/bgnav"
android:layout_marginBottom="0dp"
android:id="#+id/FrameLayout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/drawer_header_app_name"
android:id="#+id/txt__view"
android:layout_gravity="center"
android:textSize="25dp"
android:layout_marginBottom="10dp"
android:textColor="#080000"
android:textStyle="bold" />
</FrameLayout>
<LinearLayout
android:baselineAligned="false"
android:descendantFocusability="blocksDescendants"
android:focusable="false"
android:clickable="false"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal">
<Button
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="درباره ما"
android:id="#+id/about_us_btn"
android:layout_gravity="center_horizontal"
android:layout_marginTop="15dp"
android:shadowColor="#0b0a0a"
android:textSize="25dp"
android:background="#ee7a36"
android:layout_marginBottom="15dp"
android:onClick="onAboutMeClick" />
<Button
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="خروج"
android:id="#+id/exit_btn_nav"
android:layout_gravity="center_horizontal"
android:layout_marginTop="15dp"
android:textSize="25dp"
android:background="#ee7a36"
android:layout_marginBottom="15dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="دسته بندی"
android:id="#+id/textView"
android:layout_gravity="center_horizontal" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/category_lv"
android:layout_gravity="center_horizontal"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:clickable="false"
android:focusable="false"
/>
</LinearLayout>
catrgory_list_drawer.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">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:background="#da4444"
android:clickable="false"
android:contextClickable="false">
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/category_drawer_list_img"
android:src="#drawable/advertisment"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:contentDescription="#string/drawer_list_img" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/cat_name"
android:layout_marginTop="20dp"
android:layout_marginRight="5dp"
android:textSize="20dp"
android:editable="false" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/cat_count"
android:layout_marginTop="20dp"
android:layout_marginLeft="5dp"
android:editable="true" />
</LinearLayout>
</LinearLayout>
`
I will be so grateful if someone helps me!:)
I'm currently developing an mobile grocery app. I just want to ask you why my code in layout Y cant throw the details from different activity, but layout X can! As you can see, I used checkbox to checked all items you want to purchase, but in Layout Y, if u checked the item you want and click the "add to cart" button it crashed.
Tho I reedit the code based on respective information and copy to layout Y.
Here is my Code
Baby Diaper (Layout X) Java
public class Baby_Diaper extends ActionBarActivity {
ArrayList<String> selection = new ArrayList<String>();
TextView final_text;
Button addtoCart;
Intent i = new Intent(this, Shopping_List.class);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_baby__diaper);
addtoCart = (Button) findViewById(R.id.addtocart);
final_text = (TextView)findViewById(R.id.final_shopping_diaper);
}
public void SelectItem (View view) {
boolean checked = ((CheckBox) view) .isChecked();
switch (view.getId())
{
case R.id.pampers:
if(checked)
{selection.add("Pampers");}
else
{
selection.remove ("Pampers");
}
break;
case R.id.huggies:
if(checked)
{selection.add("Huggies");}
else
{
selection.remove ("Huggies");
}
break;
case R.id.johnsons:
if(checked)
{selection.add("Johnsons");}
else
{
selection.remove ("Johnsons");
}
break;
case R.id.supreme:
if(checked)
{selection.add("Supreme");}
else
{
selection.remove ("Supreme");
}
break;
}
}
public void ocaddtocart(View view){
String final_shopping_selection = "";
for (String Selections : selection){
final_shopping_selection = final_shopping_selection + Selections + "\n";
}
final_text.setText(final_shopping_selection);
final_text.setEnabled(true);}
public void ocgtshoppinglist (View view){
Intent x = new Intent(Baby_Diaper.this, Shopping_List.class);
x.putExtra("items", final_text.getText().toString());
startActivity(x);
}
Baby Food (Layout Y) Java
public class Baby_Food extends ActionBarActivity {
ArrayList<String> selection = new ArrayList<String>();
TextView final_text;
Button addtoFood;
Intent i = new Intent(this, Shopping_List.class);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addtoFood = (Button) findViewById(R.id.addtocart);
final_text = (TextView)findViewById(R.id.final_shopping_food);
setContentView(R.layout.activity_baby__food);
}
public void SelectItem (View view) {
boolean checked = ((CheckBox) view) .isChecked();
switch (view.getId())
{
case R.id.coryandgate:
if(checked)
{selection.add("Cory & Gate");}
else
{
selection.remove ("Cory & Gate");
}
break;
case R.id.gerber:
if(checked)
{selection.add("Gerber");}
else
{
selection.remove ("Gerber");
}
break;
case R.id.hipp:
if(checked)
{selection.add("Hipp");}
else
{
selection.remove ("Hipp");
}
break;
}
}
public void ocaddtocart(View view){
String final_shopping_selection = "";
for (String Selections : selection){
final_shopping_selection = final_shopping_selection + Selections + "\n";
}
final_text.setText(final_shopping_selection);
final_text.setEnabled(true);
}
public void ocgtshoppinglist (View view){
Intent x = new Intent(Baby_Food.this, Shopping_List.class);
x.putExtra("items", final_text.getText().toString());
startActivity(x);
}
Baby Diaper (Layout X) 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="com.example.admin.mobile_grocery.Baby_Diaper"
android:id="#+id/baby_diaper">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pampers"
android:id="#+id/pampers"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="52dp"
android:checked="false"
android:onClick="SelectItem"
/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/huggies"
android:id="#+id/huggies"
android:layout_below="#+id/pampers"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:checked="false"
android:onClick="SelectItem"
/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/johnsons"
android:id="#+id/johnsons"
android:layout_below="#+id/huggies"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:checked="false"
android:onClick="SelectItem"
android:inputType="textNoSuggestions"
/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/supreme"
android:id="#+id/supreme"
android:layout_below="#+id/johnsons"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:checked="false"
android:onClick="SelectItem"
android:inputType="textNoSuggestions"
/>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/addtocart"
android:id="#+id/addtocart"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:inputType="textNoSuggestions"
android:onClick="ocaddtocart" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Hello Shoppers!"
android:id="#+id/final_shopping_diaper"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="80dp" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GO TO SHOPPING LIST"
android:id="#+id/gt_shopping_list"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="ocgtshoppinglist"
/>
Baby Food (Layout Y) 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="com.example.admin.mobile_grocery.Baby_Food"
android:id="#+id/baby_food">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cory & Gate"
android:id="#+id/coryandgate"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="52dp"
android:checked="false"
/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gerber"
android:id="#+id/gerber"
android:layout_below="#+id/coryandgate"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:checked="false"
/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hipp"
android:id="#+id/hipp"
android:layout_below="#+id/gerber"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:checked="false"
/>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ADD TO CART / REMOVE"
android:id="#+id/addtocart"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick="ocaddtocart"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Hello Shoppers!"
android:id="#+id/final_shopping_food"
android:layout_below="#+id/hipp"
android:layout_centerHorizontal="true"
android:layout_marginTop="80dp" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GO TO SHOPPING LIST"
android:id="#+id/gt_shopping_list"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="ocgtshoppinglist" />
When I clicked the link on Logcat it pointed me to
final_text.setText(final_shopping_selection); of layout Y
try to change it in Y
addtoFood = (Button) findViewById(R.id.addtocart);
final_text = (TextView)findViewById(R.id.final_shopping_food);
setContentView(R.layout.activity_baby__food);
to
setContentView(R.layout.activity_baby__food);
addtoFood = (Button) findViewById(R.id.addtocart);
final_text = (TextView)findViewById(R.id.final_shopping_food);
I think your text view is null in addtocart method.