EDIT: after running the same code in the MainActivity the public void handleDialogClose(DialogInterface dialog) worked and everything got updated. so now the main problem is why its not running in other fragment?
The only difference I see is that on MainActivity the code is running in protected void onCreate(Bundle savedInstanceState)
While on Assignment fragment its running in public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
My task list is not getting updated after adding a new task or updating an existing task unless I go from one fragment to another and then come back, but the delete task function does work and removes the task from the list without going to the other fragments.
Note: it did worked when the code was in MainActivity
I tried to log the public void handleDialogClose(DialogInterface dialog)
but it didn't worked, so I assume maybe that's why...
Here is the code from my fragment:
public class AssignmentFragment extends Fragment implements DialogCloseListener {
public static Context context;
private FragmentAssignmentBinding binding;
private FloatingActionButton fab;
private RecyclerView tasksRecyclerView;
private ToDoAdapter tasksAdapter;
private List<ToDoModel> taskList;
private DatabaseHandler db;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
binding = FragmentAssignmentBinding.inflate(inflater, container, false);
View root = binding.getRoot();
AssignmentFragment.context = getContext();
db = new DatabaseHandler(getContext());
db.openDatabase();
taskList = new ArrayList<>();
tasksRecyclerView = root.findViewById(R.id.tasksRecyclerView);
tasksRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
tasksAdapter = new ToDoAdapter(db,this, null);
tasksRecyclerView.setAdapter(tasksAdapter);
taskList = db.getAllTasks();
Collections.reverse(taskList);
tasksAdapter.setTasks(taskList);
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new RecyclerItemTouchHelper(tasksAdapter));
itemTouchHelper.attachToRecyclerView(tasksRecyclerView);
fab = root.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddNewTask.newInstance().show(getChildFragmentManager(), AddNewTask.TAG);
}
});
return root;
}
#Override
public void handleDialogClose(DialogInterface dialog){
taskList = db.getAllTasks();
Collections.reverse(taskList);
tasksAdapter.setTasks(taskList);
tasksAdapter.notifyDataSetChanged();
}
#Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
}
Here is the code for Adding a new task:
Here I did tried to log the public void onDismiss(DialogInterface dialog) but its also not responding.
public class AddNewTask extends BottomSheetDialogFragment {
public static final String TAG = "ActionBottomDialog";
private EditText newTaskText;
private Button newTaskSaveButton;
private DatabaseHandler db;
public static AddNewTask newInstance(){
return new AddNewTask();
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setStyle(STYLE_NORMAL, R.style.DialogStyle);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view =inflater.inflate(R.layout.new_task, container, false);
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
newTaskText = getView().findViewById(R.id.newTaskText);
newTaskSaveButton = getView().findViewById(R.id.newTaskButton);
boolean isUpdate = false;
final Bundle bundle = getArguments();
if(bundle != null){
isUpdate = true;
String task = bundle.getString("task");
newTaskText.setText(task);
if(task.length()>0) {
newTaskSaveButton.setTextColor(ContextCompat.getColor(getContext(), android.R.color.holo_blue_dark));
}
}
db = new DatabaseHandler(getActivity());
db.openDatabase();
newTaskText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence s, int i, int i1, int i2) {
if(s.toString().equals("")){
newTaskSaveButton.setEnabled(false);
newTaskSaveButton.setTextColor(Color.GRAY);
}
else{
newTaskSaveButton.setEnabled(true);
newTaskSaveButton.setTextColor(ContextCompat.getColor(getContext(), android.R.color.holo_blue_dark));
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
final boolean finalIsUpdate = isUpdate;
newTaskSaveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = newTaskText.getText().toString();
if(finalIsUpdate){
db.updateTask(bundle.getInt("id"), text);
}
else{
ToDoModel task = new ToDoModel();
task.setTask(text);
task.setStatus(0);
db.insertTask(task);
}
dismiss();
}
});
}
#Override
public void onDismiss(DialogInterface dialog){
Activity activity = getActivity();
if(activity instanceof DialogCloseListener){
((DialogCloseListener)activity).handleDialogClose(dialog);
}
}
}
When you add a new task, you should write the following code immediately after;
tasksAdapter.notifyDataSetChanged();
This code refreshes the database.
Related
I have an issue with my BottomSheetDialogFragment whereby I can cancel it with a touch outside or a back click but if I close the app and re-open it then those that I have canceled reappear.
I have tried adding cancelled on touch outside in the onCreateView but this hasn't helped as:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.new_item, container, false);
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
getDialog().setCancelable(true);
getDialog().setCanceledOnTouchOutside(true);
return view;
}
Any ideas appreciated! I have a feeling it is something to do with the dismiss but I'm not sure.
The full code is:
public class AddNewItem extends BottomSheetDialogFragment {
public static final String TAG = "ActionBottomDialog";
private EditText newItemText;
private Button newItemSaveButton;
private DatabaseHandler db;
public static AddNewItem newInstance(){
return new AddNewItem();
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setStyle(STYLE_NORMAL, R.style.DialogStyle);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.new_item, container, false);
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
getDialog().setCancelable(true);
getDialog().setCanceledOnTouchOutside(true);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
newItemText = getView().findViewById(R.id.newItemText);
newItemSaveButton = getView().findViewById(R.id.newItemButton);
db = new DatabaseHandler(getActivity());
db.openDatabase();
// changes whether updating a task or not
boolean isUpdate = false;
final Bundle bundle = getArguments();
if(bundle != null){
isUpdate = true;
String item = bundle.getString("item");
newItemText.setText(item);
if(item.length()>0){
newItemSaveButton.setTextColor(ContextCompat.getColor(getContext(), R.color.colorPrimary));
}
}
newItemText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence s, int i, int i1, int i2) {
if (s.toString().equals("")) {
newItemSaveButton.setEnabled(false);
newItemSaveButton.setTextColor(Color.GRAY);
}
else{
newItemSaveButton.setEnabled(true);
newItemSaveButton.setTextColor(ContextCompat.getColor(getContext(), R.color.colorPrimary));
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
final boolean finalIsUpdate = isUpdate;
newItemSaveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
String text = newItemText.getText().toString();
if(finalIsUpdate){
db.updateItem(bundle.getInt("id"), text);
}
else{
ShoppingModel item = new ShoppingModel();
item.setItem(text);
item.setStatus(0);
db.insertItem(item);
}
dismiss();
}
});
}
#Override
public void onDismiss(DialogInterface dialog){
Activity activity = getActivity();
if(activity instanceof DialogCloseListener){
((DialogCloseListener)activity).handleDialogClose(dialog);
}
}
}
If you want to prevent the BottomSheetDialogFragment from being re-shown after the app has been closed and re-opened, you will need to handle the saved instance state in your onCreateView method and check whether the fragment has previously been canceled. If it has, you can simply return null from the onCreateView method to prevent the fragment from being shown again.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
if (savedInstanceState != null && savedInstanceState.getBoolean("is_cancelled")) {
return null;
}
View view = inflater.inflate(R.layout.new_item, container, false);
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
getDialog().setCancelable(true);
getDialog().setCanceledOnTouchOutside(true);
return view;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("is_cancelled", true);
}
This was resolved by overriding the onCancel:
#Override
public void onCancel(DialogInterface dialog) {
super.onCancel(dialog);
dismiss();
}
From: Detect back button but don't dismiss dialogfragment
And by adding an on click listener in onViewCreated for touch outside:
View touchOutsideView = getDialog()
.getWindow()
.getDecorView()
.findViewById(com.google.android.material.R.id.touch_outside);
touchOutsideView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
}
});
I am trying to add a button clicker listener in my fragment but it doesn't seem to work.
My main fragment is created to show tabs of two other fragments. Now, this tabs fragment has a button in the toolbar to filter content. This filter button's listener and method are in my two other fragments. The issue is, when clicking on the button, it does nothing.
Tabs Fragment:
public class LibraryFragment extends Fragment implements ViewPager.OnPageChangeListener {
private View view;
private SectionsPagerAdapterLib PageAdapter;
public ViewPager viewPager;
private ImageView filterBtn;
private LibraryFragment.OnItemClickListener mOnItemClickListener;
public interface OnItemClickListener {
void onItemClick(View view);
}
public void setOnItemClickListener(LibraryFragment.OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.view = inflater.inflate(R.layout.fragment_library_tabs, container, false);
TabLayout tabLayout = view.findViewById(R.id.fav_list_tabs);
filterBtn = view.findViewById(R.id.filterBtn);
viewPager = view.findViewById(R.id.fav_list_tabs_container);
filterBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(v);
}
}
});
PageAdapter = new SectionsPagerAdapterLib(getFragmentManager(), getActivity());
viewPager.setAdapter(PageAdapter);
viewPager.setOffscreenPageLimit(2);
viewPager.addOnPageChangeListener(this);
tabLayout.setupWithViewPager(viewPager);
getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
getActivity().getWindow().setStatusBarColor(getActivity().getResources().getColor(R.color.mWindowColorHeaders));
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Fragment fragment = PageAdapter.getFragment(position);
if (fragment != null) {
fragment.onResume();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
}
Fragment which is supposed to work when the button is clicked:
public class ContentFragment extends Fragment implements LibraryFragment.OnItemClickListener {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_data, null);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// find my views, etc
}
#Override
public void onItemClick(View view) {
//populate filter list
if (Constants.genreList != null){
list.add(0, "All Filters");
for (int i = 0; i < Constants.list.size(); i++) {
list.add((i + 1), Constants.list.get(i).getName());
}
}
final String[] listArray = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
listArray[i] = list.get(i);
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Select Filter");
builder.setItems(genreArray, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// ((TextView) v).setText(genreArray[i]);
selected_list.setText(listArray[i]);
if (i == 0) {
getData(1);
}
dialogInterface.dismiss();
}
});
builder.show();
}
}
Any help will be appreciated.
try this in a fragment
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{ //change fragment_video to where your button is located//
final View v2 = inflater.inflate(R.layout.fragment_video,container,false);
//start stream Button
Button startButton = (Button)v2.findViewById(R.id.buttonStart);
startButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//what your button is going to do
}
});
return v2;
}
As fragments are handled by Activity ,Fragments are still not depend on each other and can be used in one or two pane mode. Activity should handle listeners of both fragments.
I am not able to bind recyclerview with adapter using BottomSheetDialog
Here is my MainActivity
public class MainActivity extends AppCompatActivity {
BottomAppBar bottomAppBar;
FloatingActionButton floatingActionButton;
ImageView emptyView;
private RecyclerView recyclerView;
private List<AppModel> appModelResult = new ArrayList<>();
private AppAdapter appAdapter;
private RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
emptyView = findViewById(R.id.empty_view);
bottomAppBar = findViewById(R.id.bottom_app_bar);
setSupportActionBar(bottomAppBar);
floatingActionButton =findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddAppDialog addAppDialog = new AddAppDialog();
addAppDialog.show(getSupportFragmentManager(),"AddBottomSheet");
}
});
bottomAppBar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BottomSheetDialog bottomSheet = new BottomSheetDialog();
bottomSheet.show(getSupportFragmentManager(), "BottomSheet");
}
});
//RecyclerView Binding
recyclerView = findViewById(R.id.app_list);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
appAdapter = new AppAdapter(appModelResult);
recyclerView.setAdapter(appAdapter);
appAdapter.setItems(appModelResult);
if(appAdapter.getItemCount() == 0){
recyclerView.setVisibility(View.GONE);
emptyView.setVisibility(View.VISIBLE);
}else{
recyclerView.setVisibility(View.VISIBLE);
emptyView.setVisibility(View.GONE);
}
}}
And here is my BottomSheetDialog, where i input 2 EditText and a Spinner.Taping on Save Button should display written data on the main screen, however there is nothing on a display.
public class AddAppDialog extends BottomSheetDialog implements AdapterView.OnItemSelectedListener {
static TextInputEditText appUrl;
TextInputEditText appDesc;
MaterialButton saveButton;
Spinner spinnerCategory;
AppModel appModel = new AppModel();
List<AppModel> appModelResult = new ArrayList<>();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_bottomsheet_add,container,false);
appUrl = v.findViewById(R.id.app_url);
appDesc = v.findViewById(R.id.app_desc);
saveButton = v.findViewById(R.id.save_button);
spinnerCategory = v.findViewById(R.id.spinner_category);
List<String> categories = new ArrayList<String>();
categories.add(0,"Choose category");
categories.add("Education");
categories.add("Entertainment");
categories.add("Games");
categories.add("Health");
categories.add("Personalization");
categories.add("Social");
categories.add("Tools");
ArrayAdapter<CharSequence> adapter = new ArrayAdapter(getActivity().getApplicationContext(),android.R.layout.simple_spinner_item,categories);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCategory.setAdapter(adapter);
spinnerCategory.setOnItemSelectedListener(this);
appUrl.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) { }
#Override
public void afterTextChanged(Editable s) {
new Parse().execute();
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(appUrl.getText().toString().trim().length() != 0) {
appModel.setAppDesc(appDesc.getText().toString());
appModelResult.add(0,new AppModel(Parse.eImage,Parse.eName,appModel.getAppCategory(),appModel.getAppDesc()));
System.out.println(appModelResult.get(0).getImage());
System.out.println(appModelResult.get(0).getAppText());
System.out.println(appModelResult.get(0).getAppCategory());
System.out.println(appModelResult.get(0).getAppDesc());
dismiss();
}else{
appUrl.setError("URL is required :)");
}
}
});
return v;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(parent.getItemAtPosition(position).equals("Choose category")){
}else{
String selectedCategory = parent.getItemAtPosition(position).toString();
appModel.setAppCategory(selectedCategory);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}}
Finally, my Adapter for RecyclerView looks like that:
public class AppAdapter extends RecyclerView.Adapter<AppAdapter.AppViewHolder> {
private List<AppModel> mAppModelList;
public AppAdapter(List<AppModel> appModelList) {
mAppModelList = appModelList;
}
public static class AppViewHolder extends RecyclerView.ViewHolder{
public ImageView appImage;
public TextView appText,appCategory,appDesc;
public AppViewHolder(#NonNull View itemView) {
super(itemView);
appImage = itemView.findViewById(R.id.app_image_list);
appText = itemView.findViewById(R.id.app_text_list);
appCategory = itemView.findViewById(R.id.app_category_list);
appDesc = itemView.findViewById(R.id.app_desc_list);
}
}
public void setItems(List<AppModel> items){
mAppModelList.addAll(items);
notifyDataSetChanged();
}
public void clearItems(){
mAppModelList.clear();
notifyDataSetChanged();
}
#NonNull
#Override
public AppViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_list,parent,false);
AppViewHolder appViewHolder = new AppViewHolder(v);
return appViewHolder;
}
#Override
public void onBindViewHolder(#NonNull AppViewHolder holder, int position) {
AppModel appModel = mAppModelList.get(position);
holder.appText.setText(appModel.getAppText());
holder.appCategory.setText(appModel.getAppCategory());
holder.appDesc.setText(appModel.getAppDesc());
Picasso.get().load(appModel.getImage()).into(holder.appImage);
}
#Override
public int getItemCount() {
return mAppModelList.size();
}}
I think that XML files are OK,therefore i have not pasted it here, and the only problem is regarding to binding process.
Solved it adding RecyclerView in Fragment and refreshing list via detach & attach
getActivity().getSupportFragmentManager().beginTransaction().detach(getFragmentManager().findFragmentById(R.id.recycler_fragment)).commitNowAllowingStateLoss();
getActivity().getSupportFragmentManager().beginTransaction().attach(new RecyclerFragment()).commitAllowingStateLoss();
Attention!
In order reload fragment use only dynamic fragments.
I'm using a Spinner in a Fragment. When the activity is created, the spinner doesn't show anything. It has no item when I click on the spinner, but the items are shown correctly.
When I select on the item nothing happens even though I call a Toast message.
P.S. The items come from an ArrayList of String from a database.
This is the code of the fragment:
public class RegStudentFragment extends Fragment {
private Spinner uniSpinner;
private RegistrationStudent activity;
private ArrayList<String> listaUni;
private int pos;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.regs_frag, container, false);
uniSpinner=(Spinner) view.findViewById(R.id.spinnerUni);
System.out.println("fvfebeer");
manageUSpinner();
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = (RegistrationStudent) activity;
}
#Override
public void onActivityCreated(Bundle savedInstancestate) {
super.onActivityCreated(savedInstancestate);
listaUni = new ArrayList<String>();
new RequestFtp().setParameters(activity, "univer.php", "spinnerUni", RegStudentFragment.this).execute();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity().getApplicationContext(), android.R.layout.simple_spinner_item, getListaUni());
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
uniSpinner.setAdapter(adapter);
uniSpinner.setPrompt("Seleziona tra le seguenti:");
}
private void manageUSpinner() {
uniSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(activity.getApplicationContext(),"you selected ",Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(activity.getApplicationContext(),"No select ",Toast.LENGTH_SHORT).show();
}
});
System.out.println("vvsvsvsvsvs");
}
public void numeroel(ArrayList<ObjDb> result) {
ObjDb res= result.get(0);
String str=res.get("num");
int num=Integer.parseInt(str);
//numUni=new String[num];
}
public void arrayU(ArrayList<ObjDb> result){
int i=0;
while(i<result.size()) {
ObjDb res = result.get(i);
String str=res.get("nome");
listaUni.add(str);
i++;
}
}
public ArrayList<String> getListaUni(){
return listaUni;
}
}
I would change fragment in the viewpager using a button in every fragment. So in the fragment in position 0 i have a button and onClick i'll change in second fragment (position 1) and so on. Actually i'm using this code in the fragment at position 0:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.open_welcome_fragment_layout, container,
false);
final WelcomeViewPager pagerV = new WelcomeViewPager();
Button nextBtnOpen = (Button)view.findViewById(R.id.button_next_open);
nextBtnOpen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((WelcomeViewPager)getActivity()).setCurrentItem(1, true);
}
});
return view;
}
position 1:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.firstwelcomefrg, container, false);
final WelcomeViewPager pagerV = new WelcomeViewPager();
Button nextBtn = (Button)view.findViewById(R.id.button_next_one);
nextBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((WelcomeViewPager)getActivity()).setCurrentItem(2, true);
}
});
return view;
}
position 2:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.secondwelcomefrg, container,
false);
final WelcomeViewPager pagerV = new WelcomeViewPager();
Button nextBtnTwo = (Button)view.findViewById(R.id.button_next_two);
nextBtnTwo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((WelcomeViewPager)getActivity()).setCurrentItem(3, true);
}
});
return view;
}
and in my ViewPager Activity i created this method:
public void setCurrentItem (int item, boolean smoothScroll) {
mViewPager.setCurrentItem(item, smoothScroll);
}
unfortunatelly not works. I can change from first to second fragment but every fragment returns to second.. Seems that the only one position accepted is the first one. In this case:
((WelcomeViewPager)getActivity()).setCurrentItem(1, true);
why this behaviour?
I think what you are trying to do is to have tabs and each tab to help switch between views. You should use actionBar tabs for this, not buttons.
This should help. It is a pretty detailed tutorial.
Do you want Button ? I use for similary problem solving with listener. Example of code below. Maybe help.
PagerActivity.java
import com.example.zzztest2.MyPagerAdapter.OnPagerItemSelected;
public class PagerActivity extends Activity implements OnPagerItemSelected {
ViewPager viewPager;
ArrayList<Bitmap> bitmapArray=null;
ArrayList<String> textArray=null;
ArrayList<String> urlArray=null;
int pagexi;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reklamapager);
viewPager = (ViewPager) findViewById(R.id.view_pager);
//setting adapter
new readAsync().execute();
}//end oncreate
//switch page
public void pagerItemSelected(int newposition) {
viewPager.setCurrentItem(newposition);
}
Setting my adapter in onpostexecute Async
protected void onPostExecute(String file_url) {
MyPagerAdapter adapter = new MyPagerAdapter(PagerActivity.this, textArray, urlArray, bitmapArray, PagerActivity.this );
viewPager.setAdapter(adapter);
//start position
int pagexi = 2;
viewPager.setCurrentItem(pagexi);
}
MyPagerAdapte.java
public class MyPagerAdapter extends PagerAdapter {
Context context;
OnPagerItemSelected mListener;
ArrayList<String> textArray;
ArrayList<String> urlArray;
ArrayList<Bitmap> bitmapArray;
ImageView imageView;
TextView textreklama1;
Button btnSwitchPage;
public Activity activity;
String firmax;
String adresarx;
MyPagerAdapter(Context context, ArrayList<String> textArray, ArrayList<String> urlArray, ArrayList<Bitmap> bitmapArray, OnPagerItemSelected listener){
this.context=context;
this.textArray=textArray;
this.urlArray=urlArray;
this.bitmapArray=bitmapArray;
this.mListener = listener;
}
#Override
public int getCount() {
return textArray.size();
}
public Object instantiateItem(ViewGroup collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.reklamator_new, null);
String indexx = textArray.get(position).toString();
String delims2 = "[;]+";
String[] riadokxxx = indexx.split(delims2);
String ucex = riadokxxx[0].trim();
String dokx = riadokxxx[1].trim();
EditText inputUce = (EditText) view.findViewById(R.id.inputUce);
inputUce.setText(ucex);
EditText inputDok = (EditText) view.findViewById(R.id.inputDok);
inputDok.setText(dokx);
btnSwitchPage = (Button) view.findViewById(R.id.btnSwitchPage);
btnSwitchPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//here set new position
int xxx=1;
mListener.pagerItemSelected(xxx);
}
});
((ViewGroup) collection).addView(view, 0);
return view;
}
#Override
public void destroyItem(ViewGroup arg0, int arg1, Object arg2) {
((ViewGroup) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
//new position
public interface OnPagerItemSelected {
void pagerItemSelected(int xxx);
}
}