I'm a beginner in android app making and I'm trying to do an app for a project. I found this tutorial and I'm currently trying to put to apps together in android studio. Both are reminders apps, however the second one (the food one), the FAB is not working it register the touch but when it does it says APP keeps stopping. If anybody can help me I'll appreciated.
First Reminder .java
public class MedicineActivity extends AppCompatActivity {
#BindView(R.id.compactcalendar_view)
CompactCalendarView mCompactCalendarView;
#BindView(R.id.date_picker_text_view)
TextView datePickerTextView;
#BindView(R.id.date_picker_button)
RelativeLayout datePickerButton;
#BindView(R.id.toolbar)
Toolbar toolbar;
#BindView(R.id.collapsingToolbarLayout)
CollapsingToolbarLayout collapsingToolbarLayout;
#BindView(R.id.app_bar_layout)
AppBarLayout appBarLayout;
#BindView(R.id.contentFrame)
FrameLayout contentFrame;
#BindView(R.id.fab_add_task)
FloatingActionButton fabAddTask;
#BindView(R.id.coordinatorLayout)
CoordinatorLayout coordinatorLayout;
#BindView(R.id.date_picker_arrow)
ImageView arrow;
private MedicinePresenter presenter;
private SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd", /*Locale.getDefault()*/Locale.ENGLISH);
private boolean isExpanded = false;
public ImageButton imageButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medicine);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
imageButton = (ImageButton) findViewById(R.id.image2button);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent= new Intent(MedicineActivity.this,dashboard_screen.class);
startActivity(intent);
}
});
mCompactCalendarView.setLocale(TimeZone.getDefault(), /*Locale.getDefault()*/Locale.ENGLISH);
mCompactCalendarView.setShouldDrawDaysHeader(true);
mCompactCalendarView.setListener(new CompactCalendarView.CompactCalendarViewListener() {
#Override
public void onDayClick(Date dateClicked) {
setSubtitle(dateFormat.format(dateClicked));
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateClicked);
int day = calendar.get(Calendar.DAY_OF_WEEK);
if (isExpanded) {
ViewCompat.animate(arrow).rotation(0).start();
} else {
ViewCompat.animate(arrow).rotation(180).start();
}
isExpanded = !isExpanded;
appBarLayout.setExpanded(isExpanded, true);
presenter.reload(day);
}
#Override
public void onMonthScroll(Date firstDayOfNewMonth) {
setSubtitle(dateFormat.format(firstDayOfNewMonth));
}
});
setCurrentDate(new Date());
MedicineFragment medicineFragment = (MedicineFragment) getSupportFragmentManager().findFragmentById(R.id.contentFrame);
if (medicineFragment == null) {
medicineFragment = MedicineFragment.newInstance();
ActivityUtils.addFragmentToActivity(getSupportFragmentManager(), medicineFragment, R.id.contentFrame);
}
//Create MedicinePresenter
presenter = new MedicinePresenter(Injection.provideMedicineRepository(MedicineActivity.this), medicineFragment);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.medicine_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_stats) {
Intent intent = new Intent(this, MonthlyReportActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
public void setCurrentDate(Date date) {
setSubtitle(dateFormat.format(date));
mCompactCalendarView.setCurrentDate(date);
}
public void setSubtitle(String subtitle) {
datePickerTextView.setText(subtitle);
}
#OnClick(R.id.date_picker_button)
void onDatePickerButtonClicked() {
if (isExpanded) {
ViewCompat.animate(arrow).rotation(0).start();
} else {
ViewCompat.animate(arrow).rotation(180).start();
}
isExpanded = !isExpanded;
appBarLayout.setExpanded(isExpanded, true);
}
}
First Reminder XML File
<?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:id="#+id/coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="#style/AppTheme.AppBarOverlay"
app:expanded="false"
app:layout_behavior="com.gautam.medicinetime.utils.ScrollingCalendarBehavior">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:id="#+id/collapsingToolbarLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:minHeight="?attr/actionBarSize"
app:contentScrim="?attr/colorPrimary"
app:titleEnabled="false"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:statusBarScrim="?attr/colorPrimaryDark">
<LinearLayout
android:id="#+id/compactcalendar_view_container"
android:layout_width="match_parent"
android:layout_height="250dp"
android:paddingTop="?attr/actionBarSize"
app:layout_collapseMode="parallax"
app:layout_collapseParallaxMultiplier="1.0">
<com.github.sundeepk.compactcalendarview.CompactCalendarView
android:id="#+id/compactcalendar_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
app:compactCalendarBackgroundColor="?attr/colorPrimary"
app:compactCalendarCurrentDayBackgroundColor="#FFC107"
app:compactCalendarCurrentSelectedDayBackgroundColor="#BBDEFB"
app:compactCalendarTextColor="#fff"
app:compactCalendarTextSize="12sp" />
</LinearLayout>
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
style="#style/ToolbarStyle"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/AppTheme.PopupOverlay">
<RelativeLayout
android:id="#+id/date_picker_button"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?android:selectableItemBackground"
android:gravity="center_vertical"
android:clickable="true"
android:focusable="true"
android:orientation="vertical">
<TextView
android:id="#+id/date_picker_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="1"
android:textStyle="bold"
android:textSize="18sp"
android:textColor="#android:color/white" />
<ImageView
android:id="#+id/date_picker_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#id/date_picker_text_view"
android:layout_toRightOf="#id/date_picker_text_view"
app:srcCompat="#drawable/ic_arrow_drop_down"
tools:ignore="ContentDescription,RtlHardcoded" />
</RelativeLayout>
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<RelativeLayout
android:id="#+id/relativeLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#color/design_default_color_background">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="#+id/image2button"
android:layout_width="48dp"
android:layout_height="50dp"
android:background="#drawable/roundbutton"
android:src="#drawable/menu_icon"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.046"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.976" />
</androidx.constraintlayout.widget.ConstraintLayout>
</RelativeLayout>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab_add_task"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/sixteen_dp"
app:fabSize="normal"
app:layout_anchor="#+id/relativeLayout2"
app:layout_anchorGravity="end|bottom"
app:srcCompat="#drawable/ic_add" />
<FrameLayout
android:id="#+id/contentFrame"
android:layout_width="match_parent"
android:layout_height="674dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Second Remider .java
public class FoodActivity extends AppCompatActivity {
FloatingActionButton mCreateRem;
RecyclerView mRecyclerview;
ArrayList<Model> dataholder = new ArrayList<Model>();
//Array list to add reminders and display in recyclerview
myAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food);
mRecyclerview = (RecyclerView) findViewById(R.id.recyclerView_food);
mRecyclerview.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
mCreateRem = (FloatingActionButton) findViewById(R.id.create_reminder);
//Floating action button to change activity
mCreateRem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), FoodAddReminder.class);
startActivity(intent);
//Starts the new activity to add Reminders
}
});
Cursor cursor = new dbManager(getApplicationContext()).readallreminders();
//Cursor To Load data From the database
while (cursor.moveToNext()) {
Model model = new Model (cursor.getString(1), cursor.getString(2), cursor.getString(3));
dataholder.add(model);
}
adapter = new myAdapter(dataholder);
mRecyclerview.setAdapter(adapter);
//Binds the adapter with recyclerview
}
#Override
public void onBackPressed() {
finish();
//Makes the user to exit from the app
super.onBackPressed();
}
}
Second Reminder XML file
<?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=".FoodActivity"
android:id="#+id/Food_Container">
<androidx.appcompat.widget.Toolbar
android:id="#+id/FoodToolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/yellow_light"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:title="What's on you firdge?" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView_food"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="8dp"
android:visibility="invisible"
app:layout_constraintBaseline_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#id/FoodToolbar"
tools:layout_editor_absoluteX="-4dp" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="No food reminder added\n + Add now"
android:textAlignment="center"
android:textSize="18dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/recyclerView_food"
app:layout_constraintStart_toStartOf="#+id/recyclerView_food"
app:layout_constraintTop_toBottomOf="#+id/FoodToolbar"
app:layout_constraintVertical_bias="0.523"
android:visibility="gone"
/>
<ImageView
android:layout_width="379dp"
android:layout_height="46dp"
android:src="#drawable/food_icon"
app:layout_constraintBottom_toTopOf="#+id/textView4"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/FoodToolbar"
app:layout_constraintVertical_bias="0.966"
android:visibility="gone"
/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/create_reminder"
android:layout_width="65dp"
android:layout_height="56dp"
android:src="#drawable/ic_baseline_add_24"
app:backgroundTint="#color/yellow_light"
app:layout_anchorGravity="right|bottom"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.928"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.961" />
</androidx.constraintlayout.widget.ConstraintLayout>
You can not use applicationcontext in here, but if you want you need to add flags to the intent. So easier method for you to use "this" instead:
mCreateRem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(this, FoodAddReminder.class);
startActivity(intent);
//Starts the new activity to add Reminders
}
});
We can only "guess" why, but "not working" and "app keeps stopping" could mean a lot of things and you didn't provide any Log information or an Exception stacktrace. Its also hard to guess what FoodAddReminder.class is, if its an activity, make sure its declared in your AndroidManifest.xml
mCreateRem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(this, FoodAddReminder.class); // <-- is this an activity?
startActivity(intent);
//Starts the new activity to add Reminders
}
});
Check your AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.me.my.project">
<application >
<activity
android:name=".FoodAddReminder"/> <!-- here -->
</application>
</manifest>
If that is not the issue, I suspect that using getApplicationContext(), you're having this crash log
AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this
really what you want?
You should then tell the system you want to start a new task,
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), FoodAddReminder.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
But I would suggest not doing it, instead use your FoodActivity as your calling activity to FoodReminder in this case, and pay attention to this, it should be prefixed with FoodActivity otherwise it will refer to its enclosing anonymous OnClickListener instance.
#Override
public void onClick(View v) {
Intent intent = new Intent(FoodActivity.this, FoodAddReminder.class);
startActivity(intent);
}
If none of these solved your "not working" issue, please provide a more specific Log information and reduce your code to something that is copy-and-paste-able.
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);
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
DatabaseReference reference;
FirebaseRecyclerAdapter<Bookdeets,Bkhomeholder>adapter;
FirebaseRecyclerOptions<Bookdeets> options;
ProgressBar loading;
FloatingActionButton searchbtn;
TextView logout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
reference = FirebaseDatabase.getInstance().getReference().child("books");
reference.keepSynced(true);
recyclerView = (RecyclerView) findViewById(R.id.rv);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
loading=(ProgressBar)findViewById(R.id.loading);
searchbtn=(FloatingActionButton)findViewById(R.id.searchbtn);
logout = (TextView) findViewById(R.id.Logout);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Logout();
}
});
searchbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Opensearchpage();
}
});
options = new FirebaseRecyclerOptions.Builder<Bookdeets>()
.setQuery(reference, Bookdeets.class).build();
adapter = new FirebaseRecyclerAdapter<Bookdeets, Bkhomeholder>(options) {
#Override
protected void onBindViewHolder(#NonNull Bkhomeholder holder, int position, #NonNull Bookdeets model) {
Picasso.get().load(model.getImage()).into(holder.bookimg, new Callback() {
#Override
public void onSuccess() {
loading.setVisibility(View.GONE);
}
#Override
public void onError(Exception e) {
Toast.makeText(getApplicationContext(), "could not get the image", Toast.LENGTH_LONG).show();
loading.setVisibility(View.GONE);
}
});
holder.title.setText(model.getBookname());
}
#NonNull
#Override
public Bkhomeholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardviewlay, parent, false);
return new Bkhomeholder(view);
}
};
GridLayoutManager gridLayoutManager=new GridLayoutManager(getApplicationContext(),3);
recyclerView.setLayoutManager(gridLayoutManager);
adapter.startListening();
recyclerView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
if(adapter!=null)
adapter.startListening();
loading.setVisibility(View.VISIBLE);
}
#Override
protected void onStop() {
super.onStop();
if(adapter!=null)
adapter.stopListening();
}
#Override
protected void onResume() {
super.onResume();
if(adapter!=null)
adapter.startListening();
}
public void Opensearchpage(){
Intent intent=new Intent(this, SearchPage.class);
startActivity(intent);
}
public void Logout() {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(), Login.class));
finish();
}
Bkhomeholder.java
public class Bkhomeholder extends RecyclerView.ViewHolder {
public TextView title;
public ImageView bookimg;
public Bkhomeholder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.bkdettitle);
bookimg = itemView.findViewById(R.id.bkdetimg);
}
activity_main.xml
<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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".homepage.MainActivity"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginTop="4dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:text="Library App"
android:textAlignment="center"
android:textColor="#E21B1B"
android:textSize="32dp"
android:textStyle="bold" />
<androidx.recyclerview.widget.RecyclerView
android:clipChildren="true"
android:id="#+id/rv"
android:layout_width="match_parent"
android:layout_height="525dp"
android:layout_marginStart="8dp"
android:layout_marginTop="75dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/searchbtn"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginStart="345dp"
android:layout_marginTop="480dp"
android:layout_marginEnd="12dp"
android:background="#B3E5FC"
android:clickable="true"
app:srcCompat="#drawable/customicon" />
<ProgressBar
android:id="#+id/loading"
style="?android:attr/progressBarStyle"
android:layout_width="76dp"
android:layout_height="76dp"
android:layout_marginStart="163dp"
android:layout_marginTop="253dp"
android:layout_marginEnd="163dp"
android:layout_marginBottom="253dp"
android:visibility="invisible"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="25dp"
android:id="#+id/Logout"
android:layout_centerHorizontal="true"
android:text="Logout"
android:textAlignment="center"
android:textSize="14sp"
android:layout_marginBottom="8dp"
android:layout_marginTop="565dp"
cardview xml
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cardview="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"
android:id="#+id/bookcardview"
android:layout_width="120dp"
android:layout_height="190dp"
android:layout_margin="5dp"
cardview:cardCornerRadius="4dp">
<LinearLayout
android:id="#+id/bkdetlinear"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:ignore="ExtraText"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"
android:layout_marginEnd="4dp"
>
<ImageView
android:id="#+id/bkdetimg"
android:layout_width="match_parent"
android:layout_height="160dp"
android:background="#2d2d2d"
android:clickable="true"
android:scaleType="fitXY" />
<TextView
android:id="#+id/bkdettitle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Book title"
android:textColor="#2d2d2d"
android:textSize="12sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
i tried setting on click on the cardviewholder that is separate xml file which is inflated in my mainactivity oncreate and set the onclick listener under
onBindViewHolder but i got a error regarding null object refference as if the activity could not detect the cardview
You can set OnClickListener on RecyclerView item inside onBindViewHolder like below:
#Override
protected void onBindViewHolder(#NonNull Bkhomeholder holder, int position, #NonNull Bookdeets model) {
....
holder.title.setText(model.getBookname());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do your operation here
}
});
}
Update: Remove android:clickable="true" from cardview layout like below:
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cardview="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:foreground="?android:attr/selectableItemBackground"
android:id="#+id/bookcardview"
android:layout_width="120dp"
android:layout_height="190dp"
android:layout_margin="5dp"
cardview:cardCornerRadius="4dp">
<LinearLayout
android:id="#+id/bkdetlinear"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:ignore="ExtraText"
android:foreground="?android:attr/selectableItemBackground"
android:layout_marginEnd="4dp"
>
<ImageView
android:id="#+id/bkdetimg"
android:layout_width="match_parent"
android:layout_height="160dp"
android:background="#2d2d2d"
android:scaleType="fitXY" />
<TextView
android:id="#+id/bkdettitle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Book title"
android:textColor="#2d2d2d"
android:textSize="12sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
I'm new to Android and recently created a dashboard for my app. I followed a tutorial but it only covered the front end. I created a layout called content_main.xml with three Cardviews. Each of these Cardviews contains the code
android:clickable="true"
Beginning the back end of things, I created a java receiver class called DashboardActivity (as seen below). I want to make my Cardviews clickable so that when one is clicked, I am taken to another screen within my app. The other screens in my app I am trying to get to are fragments. Each of these screens has its own java class in my "Fragments" folder. One of them, of which I try calling on in the code that follows is called SettingsViewFragment().
So far, I have tried the following. It does nothing.
public class DashboardActivity extends AppCompatActivity {
CardView cd1, cd2, cd3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
cd1 = (CardView) findViewById(R.id.dash_settings);
cd2 = (CardView) findViewById(R.id.dash_profile);
cd3 = (CardView) findViewById(R.id.dash_activity);
cd1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment1 = new SettingsViewFragment();
}
});
}
}
UPDATE: FULL CODE
public class DashboardActivity extends AppCompatActivity {
CardView cd1, cd2, cd3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
cd1 = findViewById(R.id.dash_settings);
cd2 = findViewById(R.id.dash_profile);
cd3 = findViewById(R.id.dash_activity);
cd1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("Testing 123 123 123");
}
});
}
}
And my XML: (it continues for 3 cards this way)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.newproject.DashboardActivity"
tools:showIn="#layout/toolbar">
<FrameLayout
android:id="#+id/dashframe"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:clipToPadding="false"
android:gravity="center"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:id="#+id/dash_settings"
android:foreground="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true"
android:layout_width="160dp"
android:layout_height="190dp"
android:layout_margin="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<ImageView
android:layout_width="64dp"
android:layout_height="64dp"
android:background="#drawable/bg_circle1"
android:src="#drawable/ic_settingspicture"
android:padding="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_marginTop="10dp"
android:text="View your settings"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/lightgray"
android:layout_margin="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Follow along with guided tutorials"
android:padding="5dp"
android:textColor="#android:color/darker_gray"/>
</LinearLayout>
Replace
Fragment fragment1 = new SettingsViewFragment();
With this
Fragment fragment1 = new SettingsViewFragment();
FragmentTransaction fragmentTransaction=getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.Main_Layout,fragment1);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Change Fragment fragment1 = new SettingsViewFragment (); by Toast.makeText (mActivity, "onCLick", Toast.LENGTH_LONG) .show ();
//if show toast The problem is not the onClick, the problem is when loading the fragment
Fragments should be instantiated with the newInstance() static method.
cd1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment settingsFragment = SettingsFragment.newInstance();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.contentView, settingsFragment);
fragmentTransaction.commit();
}
});
In the SettingsFragment
public static SettingsFragment newInstance() {
return new SettingsFragment();
}
XML for content_main
LinearLayout 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"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:id="#+id/dash_settings"
android:layout_width="match_parent"
android:layout_height="wrap_content"
...
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/dash_profile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
...
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/dash_activity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
...
</android.support.v7.widget.CardView>
<FrameLayout
android:id="#+id/contentView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
</FrameLayout>
</LinearLayout>
This will transact the fragment into the FrameLayout that is positioned below the CardViews. Now this is probably not ideal, you would most likely want to launch a new activity that will host the fragment but this should work. Unless this is already in some Activity that hosts the fragment. But the key code is in the onClick.
I have tried to set an OnClickListener to my imageButton but it didn't work. I've seen other questions about the topic but none of the ansqers work for me. Am I doing something wrong?
MainActivity.java
public void Button()
{
View.OnClickListener listSet = new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Toast.makeText(getApplicationContext(), "settings", Toast.LENGTH_LONG).show();
}
};
boton= (ImageButton) findViewById(R.id.imageButton7);
boton.setOnClickListener(listSet);
}
Activity_main.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.xxxx.xxx.MainActivity"
android:orientation="vertical"
android:weightSum="1"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
>
<WebView
android:id="#+id/webV"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true">
</WebView>
<ImageButton
android:id="#+id/imageButton7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="#android:color/background_light"
android:src="#drawable/ic_gear"
tools:background="#android:color/background_light"
tools:ignore="ContentDescription" />
</RelativeLayout>
Set clickable property of ImageButton to true
<ImageButton
android:id="#+id/imageButton7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:clickable="true"
android:background="#android:color/background_light"
android:src="#drawable/ic_gear"
tools:background="#android:color/background_light"
tools:ignore="ContentDescription" />
Try this :
ImageButton ib = (ImageButton) ad.findViewById(R.id.imageButton7);
ib.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "settings", Toast.LENGTH_SHORT).show();
}
});
try:
boton= (ImageButton) findViewById(R.id.imageButton7);
boton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Toast.makeText(this, "settings", Toast.LENGTH_LONG).show();
}
};);
I have a problem with my first application,this is also my first question,i have 2 activity and 2 layout
this is the MainActivit.java
public class MainActivity extends TabActivity {
TabHost tabHost;
public static int meth;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LoadAllVar();
UpdateHud(meth);
TabSwitcher();
}
public static int LoadAllVar(){
//Load all var from files (not added for now)
meth = 200;
return meth;
}
private void UpdateHud(int meth){
String methstring = Integer.toString(meth);
TextView textSell = (TextView)findViewById(R.id.textMethCount);
textSell.setText(methstring);
}
public void TabSwitcher() {
tabHost = getTabHost();
TabHost.TabSpec tab1spec = tabHost.newTabSpec("Tab1");
tab1spec.setIndicator("Cook");
Intent firstintent = new Intent(this, CookTab.class);
tab1spec.setContent(firstintent);
tabHost.addTab(tab1spec);
}
}
and this is the second Activity
public class CookTab extends Activity {
public static int meth;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.cooktab);
LoadVarFromCook();
CheckCookClick();
}
public void LoadVarFromCook (){
meth = LoadAllVar();
String methstring = Integer.toString(meth);
Toast.makeText(getApplicationContext(),methstring,Toast.LENGTH_SHORT).show();
}
public void CheckCookClick (){
Button buttoncook = (Button) findViewById(R.id.buttonCook);
buttoncook.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
meth = meth + 1;
Toast.makeText(getApplicationContext() , "+1" , Toast.LENGTH_SHORT).show();
//HERE I NEED TO UPDATE THE VALUE OF METH INSIDE THE ACTIVITY_MAIN.XML
}
});
}
}
this is the MainActivity layout
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TabHost
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:id="#android:id/tabhost">
<TabWidget
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#android:id/tabs"></TabWidget>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#android:id/tabcontent"></FrameLayout>
</TabHost>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:id="#+id/layoutHUD">
<TextView
android:layout_width="50dp"
android:layout_height="40dp"
android:id="#+id/textMethCount"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="28dp"
android:layout_marginStart="28dp" />
</RelativeLayout>
</RelativeLayout>
and this is the second tab layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="100dp"
android:layout_height="60dp"
android:id="#+id/textMeth"
android:layout_marginTop="250dp"
android:layout_marginLeft="145dp"
android:text="Meth"
android:gravity="center"
android:textSize="29dp"
android:textStyle="bold"/>
<Button
android:layout_width="100dp"
android:layout_height="60dp"
android:id="#+id/buttonCook"
android:layout_below="#+id/textMeth"
android:layout_alignLeft="#+id/textMeth"
android:layout_alignStart="#+id/textMeth"
android:text="Cook"/>
</RelativeLayout>
I need to change the text inside a TextView located inside the activity_main.xml when i press a button inside the cooktab.xml how can i do that? findViewById() dosen't work
P.S. for now i add only one tab ,i will add more tab but for now i think about the first one
Try using EventBus it allows you to call functions in other parts of your app. Alternatively use a standard java interface link
I resolve the problem following this tutorial http://mrbool.com/how-to-create-an-activity-android-with-a-tabhost-view/27990