Common Progress bar in every activity Android - java

I have modify the solution. I am able to get the progress bar but the progress bar never gets hide
Here is class to create a progress bar with relative layout
public class ProgressBarHandler {
private ProgressBar mProgressBar;
private Context mContext;
private View _baseView;
private View _hideView;
public ProgressBarHandler(Context context,View baseView, View hideView) {
mContext = context;
_baseView = baseView;
_hideView = hideView;
ViewGroup layout = (ViewGroup) _baseView;//((Activity) context).findViewById(android.R.id.content).getRootView();
mProgressBar = new ProgressBar(context, null, android.R.attr.progressBarStyleLarge);
mProgressBar.setIndeterminate(true);
RelativeLayout.LayoutParams params = new
RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
RelativeLayout rl = new RelativeLayout(context);
rl.setGravity(Gravity.CENTER);
rl.addView(mProgressBar);
layout.addView(rl, params);
hide();
}
public void show() {
mProgressBar.setVisibility(View.VISIBLE);
_hideView.setVisibility(View.INVISIBLE);
}
public void hide() {
mProgressBar.setVisibility(View.INVISIBLE);
_hideView.setVisibility(View.VISIBLE);
}
}
This is my xml file
<FrameLayout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"
android:orientation="vertical"
android:id="#+id/profile_activity">
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:id="#+id/layout_to_hide"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:expandedTitleTextAppearance="#android:color/transparent"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#mipmap/wallpaper"
android:orientation="vertical">
<com.deerwalk.androidcommon.RoundedImageView
android:id="#+id/profile_image"
android:layout_width="100dp"
app:civ_border_color="#EEEEEE"
app:civ_border_width="4dp"
app:civ_shadow="true"
app:civ_shadow_radius="10"
app:civ_shadow_color="#8BC34A"
android:layout_height="100dp"
android:layout_alignWithParentIfMissing="false"
android:layout_centerInParent="true"
android:layout_gravity="center"
android:layout_margin="20dp"
android:src="#drawable/avatar" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_below="#+id/profile_image"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/txt_name"
android:layout_gravity="center_horizontal"
android:text=""
android:textColor="#color/white" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/txt_dob"
android:layout_gravity="center_horizontal"
android:text=""
android:layout_marginTop="5dp"
android:textColor="#color/white" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
</android.support.v7.widget.RecyclerView>
</android.support.design.widget.CoordinatorLayout>
</FrameLayout>
Here is the activity class which call the progress bar
public class ProfileActivity extends AppCompatActivity {
FrameLayout profile_root_layout;
CoordinatorLayout layot_to_hide;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
profile_root_layout = (FrameLayout) findViewById(R.id.profile_activity);
layot_to_hide = (CoordinatorLayout) findViewById(R.id.layout_to_hide);
new userProfileTask().execute();
}
public class userProfileTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
new ProgressBarHandler(getBaseContext(),profile_root_layout,layot_to_hide).show();
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Void... params) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
new ProgressBarHandler(getBaseContext(),profile_root_layout,layot_to_hide).hide();
}
}
}
The progress bar never gets hides.Where I am doing mistake.

Make a separate class then make a static method with the parameter on it the parameter contain Activity ... call this method on ur activity and pass the Activity name in it

Its very simple, you can do in multiple ways.
1) You can define base activity and write your code for progress dialog and extends all activity from BaseActivity used Progressdialog.
2) You can have custom separate class and used in all activities.
etc
Here is good example you can modify your code like this example.
ProgressHud
Or use this too.

I would suggest create a dialog and call in your activity class like this
dialog = new Dialog(getActivity(), android.R.style.Theme_Black);
View views = LayoutInflater.from(getActivity()).inflate(R.layout.activity_dialog, null);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawableResource(R.color.feed_item_bg);
dialog.setContentView(views);
dialog.show();
and in your async task onPostExecute dismiss dialog
dialog.dismiss();

public static void getProgress(Activity activity,FrameLayout relativeLayout){
final ProgressBar pb;
int progressStatus = 0;
final Handler handler = new Handler();
pb = new ProgressBar(activity, null, android.R.attr.progressBarStyleHorizontal);
LayoutParams lp = new LayoutParams(550,LayoutParams.WRAP_CONTENT);
pb.setLayoutParams(lp);
LayoutParams params = (LayoutParams) pb.getLayoutParams();
pb.setLayoutParams(params);
pb.getProgressDrawable().setColorFilter(Color.BLUE, PorterDuff.Mode.SRC_IN);
relativeLayout.addView(pb);
new Thread(new Runnable() {
#Override
public void run() {
int progressStatus = 0;
while(progressStatus < 100){
progressStatus +=1;
try{
Thread.sleep(20);
}catch(InterruptedException e){
e.printStackTrace();
}
final int finalProgressStatus = progressStatus;
handler.post(new Runnable() {
#Override
public void run() {
pb.setProgress(finalProgressStatus);
}
});
}
}
}).start(); // Start the operation
}

You could use a parent Activity. This activity class extends AppCompatActivity . Other Activities will extend this Activity. For example the name of this activity is AbstractActivty.
public class AbstractActivty extends AppCompatActivity{
AlertDialog alertDialogProgressBar;
public void showLoadingProgressBar(String message, boolean cancalable) {
if (isActivityPaused)
return;
AlertDialog.Builder adb = new AlertDialog.Builder(this);
View view = getLayoutInflater().inflate(R.layout.alert_dialog_progressbar_layout,null);
TextView tv = (TextView) view.findViewById(R.id.idTextViewMessage);
tv.setText(message);
adb.setView(view);
alertDialogProgressBar = adb.create();
alertDialogProgressBar.setCancelable(cancalable);
alertDialogProgressBar.show();
}
public void closeProgressBar() {
if (alertDialogProgressBar == null) {
return;
}
alertDialogProgressBar.hide();
}
}
This class have a method which could be called by any other activity that extends
AbstractActivty
class MainActivty extends AbstractActivty{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// when require to show progressbar
showLoadingProgressBar("Loading....",true)
// when required to hide call
closeProgressBar();
}
}
Note in Alert Dialog we have used a custom layout
"alert_dialog_progressbar_layout.xml"
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="#dimen/text_padding_l">
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guidelineVertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent=".3"
/>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="#+id/guidelineVertical"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
<TextView
android:id="#+id/idTextViewMessage"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Loading...."
android:textColor="#color/colorPrimary"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/guidelineVertical"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Hope this will be of help . Thank you.

Related

Why is second floating action button not working?

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.

Issues with Android Soft Keyboard and panAdjust

I am trying to achieve similar effect to the one found in Todoits application where you can click on FAB and it shows a floating popup for adding new task.
This is how it looks:
The closest to it I managed to achieve is this:
It is nearly there, but I want the popup to be about 10dp above the keyboard and scroll the recycle viewer to the last item but I can't get it there :/ Currently, the popup is centred.
I have tried before adding the popup to the bottom of the screen and setting android:windowSoftInputMode="adjustResize" but this was moving my bottom navigation above the keyboard too. Setting windowsSoftInputMode to panAdjust was cutting away the toolbar and few items from the list.
Have you got any suggestions about how to achieve similar effect to the one in Todoist? Maybe with a DialogFragment?
Below is my current code (navigation bar implementation is still not completed):
MainActivity:
public class MainActivity extends AppCompatActivity {
private WorkoutsListFragment workoutsListFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar myToolbar = findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
ActionBar actionBar = getSupportActionBar();
this.workoutsListFragment = new WorkoutsListFragment();
getSupportFragmentManager()
.beginTransaction()
.add(R.id.main_layout, workoutsListFragment)
.commit();
}
}
WorkoutListFragment:
public class WorkoutsListFragment extends Fragment
implements View.OnClickListener, WorkoutListViewHolderInterface {
private RecyclerView recyclerView;
private WorkoutListRecycleViewAdapter recycleViewAdapter;
private AddBoxView addBoxView;
private FloatingActionButton actionButton;
private InputMethodManager imm;
private WorkoutViewModel workoutViewModel;
private boolean addBoxStatus;
public WorkoutsListFragment() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.addBoxStatus = false;
//Irrelevant code removed (Dagger 2 DI)
this.workoutViewModel =
ViewModelProviders.of(this, workoutViewModelFactory).get(WorkoutViewModel.class);
workoutViewModel.init(7);
workoutViewModel.getWorkout().observe(this, w -> this.updateWorkoutsList(w, false));
this.imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
}
#Override
public View onCreateView(
#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_workouts_list, container, false);
this.recyclerView = view.findViewById(R.id.workoutsList);
// this.recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager recyclerViewLayoutManager = new LinearLayoutManager(getContext());
this.recyclerView.setLayoutManager(recyclerViewLayoutManager);
this.recycleViewAdapter = new WorkoutListRecycleViewAdapter(this);
this.recyclerView.setAdapter(recycleViewAdapter);
this.actionButton = view.findViewById(R.id.floating_action_add_workout);
this.actionButton.setOnClickListener(this);
this.addBoxView = new AddBoxView(Objects.requireNonNull(getContext()));
FrameLayout.LayoutParams addBoxLayoutParams =
new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT,
Gravity.CENTER);
this.addBoxView.setLayoutParams(addBoxLayoutParams);
this.addBoxView.getButton().setOnClickListener(this);
return view;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.floating_action_add_workout:
this.addBoxView((FrameLayout) v.getParent(), v);
break;
case R.id.overlay_layout:
removeAddBoxView((FrameLayout) v);
break;
case R.id.button:
this.addNewWorkout(this.addBoxView.getInputText());
break;
}
}
//Irrelevant code removed....
private void addBoxView(FrameLayout viewGroup, View v) {
this.addBoxStatus = true;
viewGroup.setClickable(true);
viewGroup.setOnClickListener(this);
viewGroup.setBackgroundColor(
getResources().getColor(R.color.cardview_shadow_start_color, null));
viewGroup.removeView(v);
viewGroup.addView(this.addBoxView);
this.addBoxView.requestInputFocus();
this.imm.showSoftInput(this.addBoxView.getInput(), InputMethodManager.SHOW_IMPLICIT);
}
private void removeAddBoxView(FrameLayout viewGroup) {
viewGroup.setClickable(false);
this.imm.hideSoftInputFromWindow(this.addBoxView.getInput().getWindowToken(), 0);
viewGroup.removeView(this.addBoxView);
viewGroup.setBackgroundColor(getResources().getColor(R.color.cardview_shadow_end_color, null));
viewGroup.addView(this.actionButton);
this.addBoxStatus = false;
}
}
Fragment_workouts_list layout:
<?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="#e1e1e1"
android:padding="0dp"
tools:context=".Activities.MainActivity.Fragments.Workouts.WorkoutsListFragment"
tools:layout_editor_absoluteY="81dp">
<android.support.v7.widget.RecyclerView
android:id="#+id/workoutsList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipChildren="false"
android:clipToPadding="false"
android:elevation="0dp"
android:scrollbars="vertical"
app:layout_constraintBottom_toTopOf="#+id/add_box_view"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</android.support.v7.widget.RecyclerView>
<FrameLayout
android:id="#+id/overlay_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="false"
android:outlineProvider="bounds">
<android.support.design.widget.FloatingActionButton
android:id="#+id/floating_action_add_workout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginBottom="40dp"
android:layout_marginEnd="40dp"
android:clickable="true"
android:src="#android:color/holo_blue_dark" />
</FrameLayout>
</FrameLayout>
MainActivity Layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
android:id="#+id/root_view"
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_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="#style/AppTheme.AppBar" />
<FrameLayout
android:id="#+id/main_layout"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#+id/navigation"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/my_toolbar">
</FrameLayout>
<android.support.design.widget.BottomNavigationView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="#color/colorPrimary"
android:foregroundGravity="bottom"
android:visibility="visible"
app:itemTextColor="#color/textColorWhite"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/my_navigation_items" />
</android.support.constraint.ConstraintLayout>

Activity is hidden by fragment, it is not useable

i have builded an app that works perfectly on android with api higer than 21. The problem is that this instruction of my code:
mFragmentTransaction.replace(R.id.content_frame, new TabFragment()).commit();
Works in different way on API less then 21.
On Api less then 21 the new fragment hide the previus activity, so that i can't click on my Floating Action Button.
Here are two images that explain in abetter way my problem.
API HIGER THAN 21
API LESS THAN 21
So my question is: How can i have the same result in API less then 21 that i have on API Higer then 21?
Here is the affected part of the Main Activity Code:
public class MainActivity extends AppCompatActivity {
public static AppDataBase appDataBase;
public static UserDataBase userDataBase;
static FragmentManager mFragmentManager;
static FragmentTransaction mFragmentTransaction;
private DrawerLayout myDrawerLayout;
final String TXT_MAINACTVT_USER_HAVE_NOT_ADDED_CONSOLE = "Add a console!";
TextView currentConsole;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appDataBase = new AppDataBase(this);
userDataBase = new UserDataBase(this);
myDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
currentConsole = (TextView) findViewById(R.id.txt_Mainactvt_currentConsole);
currentConsole.setText(TXT_MAINACTVT_USER_HAVE_NOT_ADDED_CONSOLE);
tabLayoutManagement();
floatingActionButtonManagement();
leftDrawerMenuManagement();
rigthDrawerMenuManagement();
populateMyConsole();
}
void tabLayoutManagement() {
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.content_frame, new TabFragment()).commit();
}
// Floating Action Button
private void floatingActionButtonManagement() {
FloatingActionButton fab_addGame = (FloatingActionButton)findViewById(R.id.fab_AddGame);
fab_addGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
The currentConsole TextView is used to show at the user wich console is selected.
We use it to have a strng that conteins the selected console.
Call the method that manage the click event of the FloatingActionButton. We pass the console name.
*/
String currentConsoleName = currentConsole.getText().toString();
floatingActionButtonClickEvent(currentConsoleName);
}
});
}
private void floatingActionButtonClickEvent(String currentConsoleName) {
/*
Check if user have added a console. If he did start a menu for adding games, else start an
error message
*/
if (!currentConsoleName.equals(TXT_MAINACTVT_USER_HAVE_NOT_ADDED_CONSOLE)) {
popUpViewAddGameBuild(currentConsoleName);
}
else
mySimpleAlertDialogMethod("Attention!", "Before you enter game, you must enter a console.", true, true);
}
private void popUpViewAddGameBuild(String currentConsoleName) {
/*
Build the view that show the menu for adding games.
*/
LayoutInflater inflater = this.getLayoutInflater();
View popupView = inflater.inflate(R.layout.popupview_addgame, null);
PopupWindow popupWindow = new PopupWindow(
popupView,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT);
popupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
popupWindow.setFocusable(true);
popupWindow.showAtLocation(popupView, 0, 0, 0);
}
Here is the TabLayout Class:
public class TabFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View x = inflater.inflate(R.layout.tab_layout, null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
public class MyAdapter extends FragmentPagerAdapter {
public int position;
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0 :
return new DesireFragment();
case 1 :
return new BuyedFragment();
case 2 :
return new StartedFragment();
case 3 :
return new FinishedFragment();
case 4 :
return new AllTrophiesFragment();
}
return null;
}
#Override
public int getCount() {
return 5;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "Desire";
case 1 :
return "Buyed";
case 2 :
return "Started";
case 3 :
return "Finished";
case 4 :
return "AllTrophies";
}
return null;
}
}
}
There is the layout of the MainActivity:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:layout_gravity="end"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:id="#+id/toolbar"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:navigationIcon="#drawable/ic_menu_white_24dp"
app:title="MyGames">
<Button
android:id="#+id/btnOpenRigthDrawer"
android:background="#drawable/ic_filter_list_white_24dp"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginRight="10dp"
android:layout_gravity="right" />
<Button
android:id="#+id/btnOpenOptions"
android:background="#drawable/ic_settings_white_24dp"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginRight="17dp"
android:layout_gravity="right" />
</android.support.v7.widget.Toolbar>
</RelativeLayout>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollIndicators="bottom">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:backgroundTint="#color/colorPrimary"
app:borderWidth="0dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="30dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/txt_Mainactvt_currentConsole"
android:layout_gravity="center_horizontal|top"
android:layout_marginTop="50dp"/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_AddGame"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="17dp"
android:layout_marginRight="17dp"
android:src="#drawable/ic_mode_edit_white_24dp"
android:layout_gravity="bottom|right"
android:background="#color/colorPrimary" />
</FrameLayout>
<include
layout="#layout/drawer_left"
android:id="#+id/layLeft"
android:layout_gravity="start"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"/>
<include
layout="#layout/drawer_rigth"
android:id="#+id/layRigth"
android:layout_gravity="end"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:scrollbars="vertical"
/>
</android.support.v4.widget.DrawerLayout>
And here is the layout code of the TabLayout:
<?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"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
app:tabGravity="fill"
app:tabMode="scrollable"
android:background="#color/colorPrimary"
app:tabIndicatorColor="#android:color/holo_orange_dark"
app:tabSelectedTextColor="#android:color/holo_orange_dark"
app:tabTextColor="#android:color/white"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
You replace the content of your FrameLayout with an Fragment. this leads to your strange result.
Add a Layout to your Framelayout instead and use it as your FragmentContainer:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:backgroundTint="#color/colorPrimary"
app:borderWidth="0dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/content_frame"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="30dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/txt_Mainactvt_currentConsole"
android:layout_gravity="center_horizontal|top"
android:layout_marginTop="50dp"/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_AddGame"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="17dp"
android:layout_marginRight="17dp"
android:src="#drawable/ic_mode_edit_white_24dp"
android:layout_gravity="bottom|right"
android:background="#color/colorPrimary" />
</FrameLayout>
Try to place your FrameLayout with this button to the end of layout

Change Layouts Dynamically in 1 Activity

I have the same request of this Post and I followed the FoamyGuy's Answer but I don't get the introLayout with the ImageView displaying.
I just want to show my introLayout first and then change it to my WebView.
here is my main.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">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/introLayout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:background="#color/white"
android:visibility="visible"
>
<ImageView android:layout_width="wrap_content"
android:contentDescription="splash screen"
android:id="#+id/splash"
android:src="#drawable/splash"
android:layout_height="wrap_content"
android:scaleType="centerInside"/>
</RelativeLayout>
<WebView
android:id="#+id/browser"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="invisible"
/>
</LinearLayout>
in MainActivity.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
RelativeLayout introLayout = (RelativeLayout) findViewById(R.id.introLayout);
introLayout.setVisibility(View.GONE);
webview = (WebView)findViewById(R.id.browser);
webview.setVisibility(1);
}
Help?
I don't know if it would make any difference but you could try :
webview.setVisibility (View.VISIBLE);
Instead of :
webview.setVisibility (1);
PS: With View.GONE you make the View not visible and with View.VISIBLE you make the View visible :).
Just because you did the opposite thing in your MainActivity then you discribed.
Your introLayout is set View.GONE, change to
introLayout.setVisibility(View.VISIBLE);
You need to make some logic in your code, when you will hide this "#+id/introLayout" and then show your WebView.
Ok, here is how would i do that if you dont need that layout after few seconds:
ActivityMain
public class Splash extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread timer = new Thread(){
public void run(){
try{
sleep(3000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
Intent startSpalsh = new Intent("com.yourpackagename.secondactivity");
startActivity(startSpalsh);
}
}
};
timer.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
finish();
}
}
splash.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/introLayout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:background="#color/white"
android:visibility="visible">
<ImageView
android:layout_width="wrap_content"
android:contentDescription="splash screen"
android:id="#+id/splash"
android:src="#drawable/splash"
android:layout_height="wrap_content"
android:scaleType="centerInside"/>
</RelativeLayout>
SecondActivity
public class SecondActivity extends AppCompatActivity {
WebView webView;
TextView txtChk;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
webview = (WebView)findViewById(R.id.browser);
}
second.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/browser"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="invisible" />
</LinearLayout>
First, change de ubication of intro. Set it below of WebView in your layout. WebView and intro don't need to set tag visibility. So... In your onCreate() apply this:
new Handler().postDelayed(new Runnable() { #Override public void run() { introLayout.setVisibility(View.GONE); } }, 2000);
2000 = 2 seconds. Change this like you want.
This code will be later that your initialize WebView and IntroLayout.
Change the LinearLayout by RelativeLayout in your layout how principal container.

Java/Android change text inside layout from a fragment

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

Categories