Android: Changing and limiting button click - android

having some trouble getting 2 buttons to work.
In the screenshot below, I'm making 2 buttons called NEXT & BACK. And these buttons allows the user to change it from Week 1 to Week 3. When they click NEXT and reach Week , I need the button to disable and not allow them to proceed further since its only a max of 3 weeks. Same thing goes for the BACK button and cycling thru and reaching Week 1. See below also for my code.
http://i.stack.imgur.com/fLazK.jpg
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.Image;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends FragmentActivity {
final String PREFS_NAME = "MyPrefs";
ViewPager viewPager;
String week1 = "1";
String week2 = "2";
String week3 = "3";
private int[] weekNumbers = {1, 2, 3};
int weekNumberCounter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Casting variables
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
//////// First startup screen after first time use
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if (settings.getBoolean("my_first_time", true)) {
Intent VirginBoot = new Intent(this, Begin_Program.class);
startActivity(VirginBoot);
// Record the fact that the app has been started at least once
settings.edit().putBoolean("my_first_time", false).apply();
}
}
public void settingsButton(View view) {
Intent i = new Intent(this, Settings.class);
startActivity(i);
}
public void NextWeek(View view) {
int weekCounter = 0;
TextView weekNumber = (TextView) findViewById(R.id.week_number_text);
ImageButton LastWeekButton = (ImageButton) findViewById(R.id.LastWeek);
ImageButton NextWeekButton = (ImageButton) findViewById(R.id.NextWeek);
switch (view.getId()) {
case R.id.NextWeek:
if (weekCounter < (weekNumbers.length) - 2) {
weekCounter++;
weekNumber.setText(week2);
if (weekCounter == (weekNumbers.length) - 1) {
weekNumber.setText(week3);
LastWeekButton.setClickable(true);
NextWeekButton.setClickable(false);
}
}
case R.id.LastWeek:
if (weekCounter > weekNumbers.length) {
weekCounter--;
weekNumber.setText(week2);
if (weekCounter == (weekNumbers.length) - 1) {
weekNumber.setText(week1);
NextWeekButton.setClickable(true);
LastWeekButton.setClickable(false);
}
}
break;
}
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
Fragment fragment = null;
if (arg0 == 0) {
fragment = new Day_1();
}
if (arg0 == 1) {
fragment = new Day_2();
}
if (arg0 == 2) {
fragment = new Day_3();
}
if (arg0 == 3) {
fragment = new Day_4();
}
return fragment;
}
#Override
public int getCount() {
return 4;
}
}
}
Maybe I'm looking in the wrong areas but I've tried the links below and they havent worked so far.
How to disable button click?
How to disable button as soon as its clicked
Click Limiting on <button>

First off, you should probably store your buttons as fields in your class instead of finding them each time your functions are called, finding them the first time in the activity onCreate() instead. Then, in the OnClick of your button, you can call setEnabled(false) on that button depending on whether the button should still be enabled.

Related

How to remove or hide the application button

I'm new to android studio and I'm trying to remove a button from my videos app
I have 4 buttons in my app Android : Recent,Featured,Popular,Random and Live.
I would like to delete the Live button, but I am not able to
If necessary I can take a screenshot of my android studio.
I don't necessarily need to remove the button if I have another way to just hide it, that would be a big help too
I followed my code:
If necessary I can take a screenshot of my android studio.
package com.app.materialvideo.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.duolingo.open.rtlviewpager.RtlViewPager;
import com.app.materialvideo.Config;
import com.app.materialvideo.R;
import com.app.materialvideo.utils.CustomTabLayout;
import com.app.materialvideo.utils.SharedPref;
import static com.app.materialvideo.utils.Constant.FILTER_LIVE;
import static com.app.materialvideo.utils.Constant.FILTER_video;
import static com.app.materialvideo.utils.Constant.ORDER_FEATURED;
import static com.app.materialvideo.utils.Constant.ORDER_LIVE;
import static com.app.materialvideo.utils.Constant.ORDER_POPULAR;
import static com.app.materialvideo.utils.Constant.ORDER_RANDOM;
import static com.app.materialvideo.utils.Constant.ORDER_RECENT;
public class FragmentTabLayout extends Fragment {
public RelativeLayout tab_background;
public CustomTabLayout smartTabLayout;
public ViewPager viewPager;
public RtlViewPager viewPagerRTL;
public int tab_count = 5;
SharedPref sharedPref;
View view;
public FragmentTabLayout() {
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (Config.ENABLE_RTL_MODE) {
view = inflater.inflate(R.layout.fragment_tab_layout_rtl, container, false);
} else {
view = inflater.inflate(R.layout.fragment_tab_layout, container, false);
}
sharedPref = new SharedPref(getActivity());
tab_background = view.findViewById(R.id.tab_background);
smartTabLayout = view.findViewById(R.id.tabs);
if (sharedPref.getIsDarkTheme()) {
tab_background.setBackgroundColor(getResources().getColor(R.color.colorToolbarDark));
smartTabLayout.setSelectedIndicatorColors(getResources().getColor(R.color.colorAccentDark));
} else {
tab_background.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
}
initViewPager();
return view;
}
public void initViewPager() {
if (Config.ENABLE_RTL_MODE) {
viewPagerRTL = view.findViewById(R.id.view_pager_rtl);
viewPagerRTL.setOffscreenPageLimit(tab_count);
viewPagerRTL.setAdapter(new ViewPagerAdapter(getChildFragmentManager(), tab_count));
smartTabLayout.post(() -> smartTabLayout.setViewPager(viewPagerRTL));
} else {
viewPager = view.findViewById(R.id.view_pager);
viewPager.setOffscreenPageLimit(tab_count);
viewPager.setAdapter(new ViewPagerAdapter(getChildFragmentManager(), tab_count));
smartTabLayout.post(() -> smartTabLayout.setViewPager(viewPager));
}
}
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
int noOfItems;
public ViewPagerAdapter(FragmentManager fm, int noOfItems) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
this.noOfItems = noOfItems;
}
#NonNull
#Override
public Fragment getItem(int position) {
if (position == 0) {
return Fragmentvideo.newInstance(ORDER_RECENT, FILTER_video);
} else if (position == 1) {
return Fragmentvideo.newInstance(ORDER_FEATURED, FILTER_video);
} else if (position == 2) {
return Fragmentvideo.newInstance(ORDER_POPULAR, FILTER_video);
} else if (position == 3) {
return Fragmentvideo.newInstance(ORDER_RANDOM, FILTER_video);
} {
return Fragmentvideo.newInstance(ORDER_LIVE, FILTER_LIVE);
}
}
#Override
public int getCount() {
return noOfItems;
}
#Override
public String getPageTitle(int position) {
if (position == 0) {
return getResources().getString(R.string.menu_recent);
} else if (position == 1) {
return getResources().getString(R.string.menu_featured);
} else if (position == 2) {
return getResources().getString(R.string.menu_popular);
} else if (position == 3) {
return getResources().getString(R.string.menu_random);
} {
return getResources().getString(R.string.menu_live);
}
}
}
}
From my understanding, you don't want to remove a classic button, but a Tab button used inside a TabLayout.
If you want to remove it , easiest way would be to remove the last condition in your if else statements that deal with displaying and handling this button.
From the code you posted should be
Here
{
return getResources().getString(R.string.menu_live);
}
and here, as i think these two deal with the "Live" button.
{
return Fragmentvideo.newInstance(ORDER_LIVE, FILTER_LIVE);
}
As well as reduce the value passed to the ViewPager Adapter "noOfItems" variable by 1. In your situation, I think the variable is "tabCount" and that should be set to 4 ( down from 5). I see it's used in many places and changing this should deal with all cases.
If hiding is also good, then this code should also work.
Just use it inside onCreateView(). The code is in Kotlin and works on a default TabLayout, but i am not sure if it will work as i see you use a custom one.
tabLayout?.getTabAt(4)?.view?.visibility = View.GONE
You need to pass the index of the tab you want to hide, so in your case, you have 5 tabs, so the index is 4.
If you know id of the button.
view.findViewById(R.id.btn_firs).setVisibility(View.GONE);

Passing a data from Dialog to Fragment in android

I'm currently working in my own project of dental application, i would like to ask if how to pass a certain data from a custom dialog and show or add it to the target fragment?
Appreciate for any help.
This is the Custom Dialog Screenshot:
CustomDialog.java
package com.bloxofcode.multipletabs;
import android.app.Activity;
import android.app.Dialog;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.bloxofcode.multipletabs.Tab1;
public class CustomDialog extends Dialog implements
View.OnClickListener {
public Activity c;
public CustomDialog d;
public Button yes, no;
ToggleButton btnGenderMale,btnGenderFemale;
Button btnCancel, btnAccept;
EditText eText;
public CustomDialog(Activity a) {
super(a);
// TODO Auto-generated constructor stub
this.c = a;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setBackgroundDrawableResource(android.R.drawable.dialog_holo_light_frame);
}
else{
getWindow().setBackgroundDrawableResource(android.R.drawable.alert_light_frame);
}
setContentView(R.layout.activity_dialog);
btnGenderFemale = (ToggleButton) findViewById(R.id.toggleButtonFemale);
btnGenderMale = (ToggleButton) findViewById(R.id.toggleButtonMale);
btnCancel = (Button) findViewById(R.id.btnCancel);
btnAccept = (Button) findViewById(R.id.btnAccept);
eText = (EditText) findViewById(R.id.editText);
btnGenderMale.setChecked(true);
btnGenderMale.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonMale, boolean b) {
// Toast.makeText(getApplicationContext(),
// String.valueOf(buttonMale.isChecked()), Toast.LENGTH_SHORT).show();
if(buttonMale.isChecked()){
btnGenderMale.setEnabled(false);
btnGenderFemale.setEnabled(true);
btnGenderFemale.setChecked(false);
}else{
}
}
});
btnGenderFemale.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonFemale, boolean b) {
// Toast.makeText(getApplicationContext(),
// String.valueOf(buttonFemale.isChecked()), Toast.LENGTH_SHORT).show();
if(buttonFemale.isChecked()){
btnGenderMale.setEnabled(true);
btnGenderFemale.setEnabled(false);
btnGenderMale.setChecked(false);
}else{
}
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
}
});
btnAccept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getContext(),"Sample",Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onClick(View v) {
dismiss();
}
}
How to achieve this Expected Result:
Tab1.java
package com.bloxofcode.multipletabs;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ListView;
import com.bloxofcode.multipletabs.database.DBOpenHelper;
import com.bloxofcode.multipletabs.database.NotesProvider;
/**
* A simple {#link Fragment} subclass.
*/
public class Tab1 extends Fragment {
private ImageButton imgButton;
private CustomDialog customDialog;
View v;
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v =inflater.inflate(R.layout.tab_1,container,false);
imgButton = (ImageButton) v.findViewById(R.id.imageButton);
//Creating ImageButton
imgButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Toast.makeText(getActivity(),"Hello Image Button!",Toast.LENGTH_LONG).show();
customDialog = new CustomDialog(getActivity());
customDialog.show();
}
});
press();
return v;
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void press() {
insertNote("Juan Dela Cruz");
Cursor cursor = getActivity().getContentResolver().query(NotesProvider.CONTENT_URI,
DBOpenHelper.ALL_COLUMNS, null, null, null, null);
String[] from = {DBOpenHelper.NOTE_TEXT};
int[] to = {android.R.id.text1};
CursorAdapter cursorAdapter = new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_1,cursor,from,to,0);
ListView list = (ListView) v.findViewById(android.R.id.list);
list.setAdapter(cursorAdapter);
}
private void insertNote(String noteText) {
ContentValues values = new ContentValues();
values.put(DBOpenHelper.NOTE_TEXT,noteText);
Uri noteUri =getActivity().getContentResolver().insert(NotesProvider.CONTENT_URI,values);
Log.d("MainActivity","Inserted note " + noteUri.getLastPathSegment());
}
}
ViewPagerAdapter.java
package com.bloxofcode.multipletabs;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class ViewPagerAdapter extends FragmentStatePagerAdapter{
CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
// Build a Constructor and assign the passed Values to appropriate values in the class
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
//This method return the fragment for the every position in the View Pager
#Override
public Fragment getItem(int position) {
if(position == 0) // if the position is 0 we are returning the First tab
{
Tab1 tab1 = new Tab1();
return tab1;
}
else if(position == 1)
{
Tab2 tab2 = new Tab2();
return tab2;
}
else // As we are having 3 tabs if the position is now 0 it must be 1 so we are returning second tab
{
Tab3 tab3 = new Tab3();
return tab3;
}
}
// This method return the titles for the Tabs in the Tab Strip
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
// This method return the Number of tabs for the tabs Strip
#Override
public int getCount() {
return NumbOfTabs;
}
}
TabsActivity.java
package com.bloxofcode.multipletabs;
import android.os.Build;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class TabsActivity extends AppCompatActivity {
// Declaring Your View and Variables
Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Patient","Appointment","Backup"};
int Numboftabs =3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabs);
// Creating The Toolbar and setting it as the Toolbar for the activity
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
//return ContextCompat.getColor(TabsActivity.this,R.color.tabsScrollColor);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return getResources().getColor(R.color.tabsScrollColor,TabsActivity.this.getTheme());
}else {
return getResources().getColor(R.color.tabsScrollColor);
}
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
If you'd like to keep things loosely coupled and structured, A fine rather alternative is to choose the EventBus . To see the usage see this Answer.
You can accomplish it using Interface.
YourInterface.java
public interface YourInterface{
void yourMethod(int data);
}
Use that Interface in your Dialog class:
public class CustomDialog extends Dialog implements
View.OnClickListener {
private YourInterface delegate;
....
public CustomDialog(Activity a) {
super(a);
// TODO Auto-generated constructor stub
this.c = a;
delegate = (YourInterface) a;
}
}
In your Activity that holds fragment implement interface:
public class YourActivity extends AppCompatActivity implements YourInterface {
....
#Override
public void yourMethod(int data) {
fragment.receiverMethod(data);
}
}
Tab1.java
public class Tab1 extends Fragment {
public void receiverMethod(int data) {
// do what you want with received data
}
}
Now to use that simply call delegate.yourMethod(data) to pass it to fragment
You can use Broadcast Receiver in your onDismiss like below in your Dialog
#Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
if (onDismissListener != null) {
Intent intent = new Intent("DialogDismiss");
LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
onDismissListener.onDismiss(dialog);
}
}
and in your Fragment you can receive the broadcast
// In your Fragment do below
BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Work Here
}
};
//In OnCreate
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mReceiver,
new IntentFilter("DialogDismiss"));
//onDestroy
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
If you get the view from the customDialog you can just access the fields normally with view.findViewById() from in your fragment class.
Put your data into budle as key-value pair and set bundle as an argument to fragment.
fragment.setArgument(bundle)
To get bundle in fragmen, call
Bundle bundle = getArgument() and get values from the bundle based on key.
You could return the String which was entered into the EditText by creating a setter and getter method within your Dialog class to return a String variable (e.g. editTextString) which you would assign a value to whenever the accept button is clicked.
Add your getter and setter methods to the Dialog class
private void setEditTextString() {
editTextString = eText.getText().toString()
}
public String getEditTextString() {
return editTextString;
}
Within your click listener for the accept button add the following line of code:
setEditTextString(eText.getText().toString());
Then all you need to do to return the value entered in the editText field in the Fragment class would be to call the public method within your Dialog class to return the string.
dialogClass.getEditTextValue()

How to read object which is used by a fragment

First of all, I hope my question is clear. If it isn't please comment i will try to make it better!.
i have a question related to putting a item in a arraylist. I am using the master/detail flow (a standard project option in android studio) as a bases for my app. I already modified it but below is de code from the original template to simplify my question. For my problem i think there are three activities involved. Main activity, detail activity, mysavedbooks and the fragment activity.
My Problem
In the detail activity there is a fab button. WHat i want to do is to save the current displayed item in a new arraylist called Saveditems in the activity mysavedbooks.
How can i read the item (which is currently displayed by the detailactivity which extends the fragment) and put this in a saveditems arraylist.
Greetings,
Matthijs
below is the main activity
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import matthijs.bookshelf.dummy.DummyContent;
import java.util.List;
/**
* An activity representing a list of books. This activity
* has different presentations for handset and tablet-size devices. On
* handsets, the activity presents a list of items, which when touched,
* lead to a {#link bookDetailActivity} representing
* item details. On tablets, the activity presents the list of items and
* item details side-by-side using two vertical panes.
*/
public class bookListActivity extends AppCompatActivity {
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
private boolean mTwoPane;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getTitle());
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
View recyclerView = findViewById(R.id.book_list);
assert recyclerView != null;
setupRecyclerView((RecyclerView) recyclerView);
if (findViewById(R.id.book_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-w900dp).
// If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
}
}
private void setupRecyclerView(#NonNull RecyclerView recyclerView) {
recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(DummyContent.ITEMS));
}
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<DummyContent.DummyItem> mValues;
public SimpleItemRecyclerViewAdapter(List<DummyContent.DummyItem> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.book_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mValues.get(position).content);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(bookDetailFragment.ARG_ITEM_ID, holder.mItem.id);
bookDetailFragment fragment = new bookDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.book_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, bookDetailActivity.class);
intent.putExtra(bookDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public DummyContent.DummyItem mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
}
below is the detail activity.
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
/**
* An activity representing a single book detail screen. This
* activity is only used narrow width devices. On tablet-size devices,
* item details are presented side-by-side with a list of items
* in a {#link bookListActivity}.
*/
public class bookDetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "saved book", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
// Show the Up button in the action bar.
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don't need to manually add it.
// For more information, see the Fragments API guide at:
//
// http://developer.android.com/guide/components/fragments.html
//
if (savedInstanceState == null) {
// Create the detail fragment and add it to the activity
// using a fragment transaction.
Bundle arguments = new Bundle();
arguments.putString(bookDetailFragment.ARG_ITEM_ID,
getIntent().getStringExtra(bookDetailFragment.ARG_ITEM_ID));
bookDetailFragment fragment = new bookDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.add(R.id.book_detail_container, fragment)
.commit();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpTo(this, new Intent(this, bookListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
below is the fragment
package matthijs.bookshelf;
import android.app.Activity;
import android.support.design.widget.CollapsingToolbarLayout;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import matthijs.bookshelf.dummy.DummyContent;
/**
* A fragment representing a single book detail screen.
* This fragment is either contained in a {#link bookListActivity}
* in two-pane mode (on tablets) or a {#link bookDetailActivity}
* on handsets.
*/
public class bookDetailFragment extends Fragment {
/**
* The fragment argument representing the item ID that this fragment
* represents.
*/
public static final String ARG_ITEM_ID = "item_id";
/**
* The dummy content this fragment is presenting.
*/
private DummyContent.DummyItem mItem;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public bookDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments().containsKey(ARG_ITEM_ID)) {
// Load the dummy content specified by the fragment
// arguments. In a real-world scenario, use a Loader
// to load content from a content provider.
mItem = DummyContent.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID));
Activity activity = this.getActivity();
CollapsingToolbarLayout appBarLayout = (CollapsingToolbarLayout) activity.findViewById(R.id.toolbar_layout);
if (appBarLayout != null) {
appBarLayout.setTitle(mItem.content);
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.book_detail, container, false);
// Show the dummy content as text in a TextView.
if (mItem != null) {
((TextView) rootView.findViewById(R.id.book_detail)).setText(mItem.details);
}
return rootView;
}
}
Mysavedbooks activity
package matthijs.tuinierv2;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Matthijs on 12-2-2016.
*/
public class Mysavedbooks {
public static final List<DummyContent.DummyItem> SavedItems= new ArrayList<DummyContent.DummyItem>();
}
I kind of solved to problem for now, except for the twopane mode. I need to look in the solution for the twopane mode further. I think it can be done in a better way but here is the solution.
Please comment if you have a better solution.
I added the String in ItemDetailActivity
public static String SAVED_ITEM_ID;
In the bookListActivity i added a line of code in this part:
` #Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mValues.get(position).content);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(bookDetailFragment.ARG_ITEM_ID, holder.mItem.id);
bookDetailFragment fragment = new bookDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.book_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, bookDetailActivity.class);
intent.putExtra(bookDetailFragment.ARG_ITEM_ID, holder.mItem.id);
//THE line of code I ADDED
itemDetailActivity.SAVED_ITEM_ID = holder.mItem.id;
context.startActivity(intent);
}
}
});
}`
Here is the code i added in the bookDetailActivity to retrieve the current book which is displayed in the itemdetailactivity en thereby the fragment.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fabdetail);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//code i added to retrieve the current item and save it in
int SAVED_ITEM_ID_INT = Integer.parseInt(SAVED_ITEM_ID);
ItemListActivity.PlantItem SAVED_ITEM = ItemListActivity.ITEMS.get(SAVED_ITEM_ID_INT);
Mysavedbooks.SavedItems.add(SAVED_ITEM);
Snackbar.make(view,"Book saved to My books", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
});

Android: Change Images On pressing Previous and NExt imageview

Android. i am a newbie I have 6 images. One image view, two buttons previous and next. Have written the program, but when executing, crashes. I have written the logic of how to change the images in image view, I have removed all the syntax errors. here is my Mainactivity.java code
package com.example.hm2_koppineedi;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
ImageView imageView;
Button previous,next;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
imageView= (ImageView)findViewById(R.id.imageView1);
previous = (Button)findViewById(R.id.button1);
previous.setOnClickListener((OnClickListener) this);
next = (Button)findViewById(R.id.button2);
next.setOnClickListener((OnClickListener) this);
}
public void onClick(View view)
{
int a=0;
switch (view.getId())
{
case R.id.button2:
if (a == 0)
{
imageView.setImageResource(R.drawable.hdimage);
a = 1;
}
else if (a == 1)
{
imageView.setImageResource(R.drawable.elephant);
a = 2;
}
else if (a == 2)
{
imageView.setImageResource(R.drawable.giraffe);
a = 3;
}
else if (a == 3)
{
imageView.setImageResource(R.drawable.horse);
a = 4;
}
else if (a == 4)
{
imageView.setImageResource(R.drawable.lion);
a = 5;
}
else if (a == 5)
{
imageView.setImageResource(R.drawable.tiger);
a = 6;
}
else if (a == 6)
break;
case R.id.button1:
a--;
button2.performClick();
next.performClick();
break;
}
}
}
Wrong code:
previous.setOnClickListener((OnClickListener) this);
next.setOnClickListener((OnClickListener) this);
Use this:
previous.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//...
}
);
next.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//...
}
);
I think you need to override the OnClick method, and make sure it is in your activity.
public class myActivity extends Activity {
...
#Override
public void onClick(View v) {
// Do something
}
...
}
You should not have to cast "this", but call...
setOnClickListener(this);
...from inside one of your activity methods (for instance : OnCreate), so that "this" be the activity. That way, all calls to "Click" in the context of your activity will be sent to your OnClick method.
You have lots of examples on this site to show that.

How Do I Pass The Package To RemoteView in Android?

Me Doing "edu.sju.BlackJack" Is not causing updates that are later called to occur.
I reference the layout correctly and the calls that are supposed to update it are correct, so what do I put in for the package name?
I should add that my package name according to the manifest is the above.
This is the code I have now which currently doesn't update the screen (or i'm guessing change the value correctly).
RemoteViews name = new RemoteViews("edu.sju.BlackJack", R.layout.play_screen);
If that's not it.. would it then be this code?
name.setTextViewText(R.id.Dealer_Total, "0");
Dealer_Total is the id for the TextView that I want to change.. however again the Change is not occurring.
Thanks in advance for any and all assistance.
Here is the whole of my code that i'm talking about, first Playscreen.java
package edu.sju.BlackJack;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import java.util.*;
public class PlayScreen extends Activity implements OnClickListener {
/** Called when the activity is first created. */
GameEngine Engine = new GameEngine();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play_screen);
TextView TextDealer = (TextView)findViewById(R.id.Dealer_Total);
Engine.setView(TextDealer);
//Set up click listeners for all the buttons
View hitButton = findViewById(R.id.hit_button);
hitButton.setOnClickListener(this);
View standButton = findViewById(R.id.stand_button);
standButton.setOnClickListener(this);
//new preplay button (ML 10/24/10)
View prePlayButton = findViewById(R.id.prePlay_button);
prePlayButton.setOnClickListener(this);
Thread thread = new Thread(Engine);
thread.start();
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.prePlay_button:
v.setVisibility(View.GONE);
System.out.println("Working?");
Engine.setGameStart(1);
break;
case R.id.hit_button:
Engine.gameHit(1);
break;
case R.id.stand_button:
Engine.gameStand(1);
break;
}
// More buttons go here (if any) ...
}
}
Now here's the GameEngine Thread
Not the Whole of it, just enough so you get the idea
package edu.sju.BlackJack;
import java.util.Random;
import android.widget.RemoteViews;
import android.widget.TextView;
public class GameEngine implements Runnable {
static int playerCount = 0; //keep record of which cards to change for player when hit is selected
static int dealerCount = 0; //keep record of which cards to change for dealer when dealer hits
static int win = 0; //keeps record of wins (JV 10/01/10)
static int lose = 0; //keeps record of loss (JV 10/01/10)
static int hit = 0; //let's engine know if hit button was selected (0 means it has not)
static int stand = 0; //let's engine know if stand button was selected (0 means it has not)
static int playerTotal = 0; //tells player's total (JV 10/01/10)
static int dealerTotal = 0; //tells dealer's total (JV 10/01/10)
static int playerTurn = 0; //activates buttons so that they do actions when clicked (as it's players turn)
static int startGame = 0; //starts the game when the start game button is pressed
TextView TextDealer;
RemoteViews name = new RemoteViews("edu.sju.BlackJack", R.layout.play_screen);
public void run() {
name.setTextViewText(R.id.Dealer_Total, "0");
//main();
}
public void setView(TextView a)
{
TextDealer = a;
}
public void setGameStart(int i)
{
startGame = i;
}
public void gameHit(int i)
{
if(playerTurn == 1)
hit = 1;
}
public void gameStand(int i)
{
if(playerTurn == 1)
stand = 1;
}
public void main()
{//Start Game
Deck mainDeck = new Deck();
fillDeck(mainDeck);
//TextView TextPlayer = (TextView)findViewById(R.id.Player_Total);
//TextDealer.setText("" + dealerTotal);
//TextPlayer.setText("" + playerTotal);
while(true)
{
if(startGame == 1)
{
if(mainDeck.getList().size() < 15){
mainDeck = emptyDeck();
fillDeck(mainDeck);
}
//RESET CARD VIEWS TO DEFAULT
//RESET DEALERCARD AND PLAYERCARD TOTALS TO 0
dealerTotal = 0;
playerTotal = 0;
playerCount = 0;
dealerCount = 0;
//playHand(mainDeck);
}
}
}
Whatever your problem is, I don't think it is what you think it is. If your layout is appearing in the app widget, then the package name is being handled properly. If the update (your setTextViewText() call) is not having an effect, then either R.layout.play_screen does not have R.id.Dealer_Total or you are not sending over a RemoteViews that contains the setTextViewText() instructions.

Categories

Resources