Can't swiping between fragments in viewpager with buttons - java

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);
}
}

Related

android shared element transition with fragments doesn't show exit animation

I have a main activity that handles the static elements, attached to the main activity there is a fragment, this fragment has a tablelayout with a viewpager2, each page shows a recycler view.
The shared element transition works well from FRAGMENT A(Tab_1) to FRAGMENT B(ElementDetails), but when I press the back button, the return shared element transition doesn't work.
TAb_1(Fragment A):
public class tab1_anime extends Fragment {
private RecyclerView recycler_view;
public static AFSGAdapter adapter;
private ArrayList<AddElement> a_list = new ArrayList<>();
private Context context;
public tab1_anime(){ };
#Override
public void onCreate(Bundle savedInstancesState) {
super.onCreate(savedInstancesState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstancesState) {
View view = inflater.inflate(R.layout.fragment_tab1_anime, container, false);
recycler_view = view.findViewById(R.id.recycler_view);
recycler_view.setHasFixedSize(true);
context = getActivity();
LinearLayoutManager layoutManager_anime_crucial = new GridLayoutManager(getContext(), 3, GridLayoutManager.VERTICAL, false);
recycler_view.setLayoutManager(layoutManager_anime_crucial);
recycler_view.setItemAnimator(new DefaultItemAnimator());
int spanCount = 3; // 3 columns
int spacing = 10; // 10 for my phone, 35 for the emulator
boolean includeEdge = true;
recycler_view.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing, includeEdge));
adapter = new AFSGAdapter(a_list, getContext(), this);
adapter.setDataSet(a_list);
recycler_view.setAdapter(adapter);
recycler_view.scheduleLayoutAnimation();
adapter.notifyDataSetChanged();
return view;
}
public void openShowElementFragment(int position, View view) {
AddElement element = a_list.get(position);
ShowElementFragment showElementFragment = new ShowElementFragment();
Bundle bundle = new Bundle();
bundle.putString("transitionName", "transition" + position);
bundle.putSerializable("element", element);
showElementFragment.setArguments(bundle);
((MainActivity) context).showFragmentWithTransition(this, showElementFragment, "showElementFragment", view, "transition" + position);
}
}
ShoeElementDetails(Fragment B):
public class ShowElementFragment extends Fragment {
private AddElement elemento;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_show_element, parent, false);
//showelement_background_image.setTransitionName("example_transition");
Bundle b = getArguments();
if (b != null) {
String transitionName = b.getString("transitionName");
elemento = (AddElement) b.getSerializable("element");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
showelement_image.setTransitionName(transitionName);
}
}
//postponeEnterTransition();
Glide.with(this)
.load(elemento.image_url)
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.skipMemoryCache(false)
.apply(RequestOptions.bitmapTransform(new BlurTransformation(10, 3)))
.into(showelement_background_image);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getActivity().getWindow().getSharedElementEnterTransition().setDuration(800);//.setInterpolator(new AccelerateInterpolator());
getActivity().getWindow().getSharedElementReturnTransition().setDuration(850);//.setInterpolator(new DecelerateInterpolator());
}
showelement_backarrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragmentHolder, new MainFragment())
.commit();
//startActivity(new Intent(ShowElementActivity.this, AnimeActivity.class));
}
});
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
postponeEnterTransition();
OneShotPreDrawListener.add(view, this::startPostponedEnterTransition);
super.onViewCreated(view, savedInstanceState);
}
}
Inside the adapter I handle the click of the element to start the transition:
inside adapter:
holder.itemView.setOnClickListener(new View.OnClickListener() {
#SuppressLint("ClickableViewAccessibility")
#Override
public void onClick(View v) {
fragment.openShowElementFragment(holder.getAdapterPosition(), v.findViewById(R.id.main_image));
}
});
the openShowElementFragment called is inside main activity:
public void showFragmentWithTransition(Fragment current, Fragment newFragment, String tag, View sharedView, String sharedElementName) {
FragmentManager fragmentManager = getSupportFragmentManager();
// check if the fragment is in back stack
boolean fragmentPopped = fragmentManager.popBackStackImmediate(tag, 0);
if (fragmentPopped) {
// fragment is pop from backStack
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
current.setSharedElementReturnTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
current.setExitTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
newFragment.setSharedElementEnterTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
newFragment.setEnterTransition(TransitionInflater.from(this).inflateTransition(android.R.transition.no_transition));
}
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragmentHolder, newFragment, tag);
fragmentTransaction.addToBackStack(tag);
fragmentTransaction.addSharedElement(sharedView, sharedElementName);
fragmentTransaction.commit();
}
}
It's my first time approaching with fragments.

Button click listener in a separate fragment not working?

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.

How setText in a Layout from a ViewPager

I try to set a Text in a Layout in a ViewPager, but if i do this there will be thrown a NullPointerException:
private ViewPager viewPager;
private ViewPagerAdapter viewPagerAdapter;
private LinearLayout dotsLayout;
private TextView[] dots;
private int[] layouts;
private Button btnNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_slider);
viewPager = (ViewPager) findViewById(R.id.view_pager);
dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
//btnSkip = (Button) findViewById(R.id.btn_skip);
btnNext = (Button) findViewById(R.id.btn_next);
layouts = new int[]{
R.layout.slide_header_bild_text,
R.layout.slide_header_bild_text_2,
R.layout.slide_01_03,
R.layout.slide_01_04,
R.layout.slide_01_05,
R.layout.slide_01_06,
R.layout.startquiz_layout};
//These two lines are the Problem
TextView t1 = (TextView) findViewByID(R.id.header_text);
t1.setText("Test")
// adding bottom dots
addBottomDots(0);
viewPagerAdapter = new ViewPagerAdapter();
viewPager.setAdapter(viewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
}
public void btnQuizStart(View v){
Intent intent = new Intent(this, Quiz.class);
this.startActivity(intent);
}
public void btnNextClick(View v)
{
// checking for last page
// if last page home screen will be launched
int current = getItem(1);
if (current < layouts.length) {
// move to next screen
viewPager.setCurrentItem(current);
} else {
launchHomeScreen();
}
}
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
addBottomDots(position);
// changing the next button text 'NEXT' / 'GOT IT'
if (position == layouts.length - 1) {
// last page. make button text to GOT IT
btnNext.setText(getString(R.string.start));
} else {
// still pages are left
btnNext.setText(getString(R.string.next));
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
private void addBottomDots(int currentPage) {
dots = new TextView[layouts.length];
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(getResources().getColor(R.color.inactive_dots));
dotsLayout.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(getResources().getColor(R.color.active_dots));
}
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
private void launchHomeScreen() {
startActivity(new Intent(this, MainActivity.class));
finish();
}
public class ViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public ViewPagerAdapter() {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(layouts[position], container, false);
container.addView(view);
return view;
}
#Override
public int getCount() {
return layouts.length;
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
I've got the ViewPager which contains seven Pages.
I think the Layout wont be found, so the TextView is Null. I also read that I have to configure the instantiateItem method and to add there the TextView and the setter. Anybody can help?
findViewByID(R.layout.header_text)
TaxtView can't be a layout.
oh this was also a failure but not which I searched for. I had the problem with the viewpager that i didn't got the layout and so the elements of the layout was null. I fixed the instantiateItem Method so any layout will be initiated specific:
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View one = layoutInflater.inflate(R.layout.slide_type_a, container, false);
WebView header_1_a = (WebView) one.findViewById(R.id.header_slide_type_a_1);
loadHTLMContentHeader(getString(R.string.Historie1_header),header_1_a);
ImageView image_1_a = (ImageView) one.findViewById(R.id.image_slide_type_a_1);
image_1_a.setImageResource(R.drawable.picture_kap01_01);
WebView text_1_a = (WebView) one.findViewById(R.id.text_slide_type_a_1);
loadHTLMContentText(getString(R.string.Historie1), text_1_a);
View two = layoutInflater.inflate(R.layout.slide_type_a, container, false);
View three = layoutInflater.inflate(R.layout.slide_type_a, container, false);
View four = layoutInflater.inflate(R.layout.slide_type_b, container, false);
View five = layoutInflater.inflate(R.layout.slide_type_b, container, false);
View six = layoutInflater.inflate(R.layout.slide_type_b, container, false);
View seven = layoutInflater.inflate(R.layout.slide_type_b, container, false);
View eight = layoutInflater.inflate(R.layout.startquiz_layout, container, false);
View viewarr[] = {one, two, three, four, five, six, seven, eight};
container.addView(viewarr[position]);
return viewarr[position];
}
So after initiate the layout, i can get the xml element and change the content of it.

How to refresh ListView after deleting element?

I have created a listview but when i delete a element, it doesn't refresh. I have tried
adapter.notifyDataSetChanged();
and
getListView().invalidateViews();
in mainactivity:
case R.id.ordini:
Ordini O = new Ordini();
android.app.FragmentManager fragmentManager0 = getFragmentManager();
android.app.FragmentTransaction fragmentTransaction0 = fragmentManager0
.beginTransaction();
fragmentTransaction0.replace(R.id.frame, O);
fragmentTransaction0.commit();
Ordini.java
public class Ordini extends ListFragment implements AdapterView.OnItemClickListener {
int ArraySize;
CustomAdapterOrdini adapter;
private List<RowItemOrdini> rowItems;
Button SendButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.ordini, null, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArraySize = MainActivity.ArrayProdotto.size();
SendButton = (Button) getActivity().findViewById(R.id.send_btn);
rowItems = new ArrayList<RowItemOrdini>();
for (int i = 0; i < ArraySize; i++) {
RowItemOrdini items = new RowItemOrdini(
MainActivity.ArrayProdotto.get(i),
R.drawable.ic_delete_black_24dp,
MainActivity.ArrayCode.get(i),
MainActivity.ArrayPrezzo.get(i),
MainActivity.ArrayColli.get(i),
MainActivity.ArrayQuantita.get(i));
rowItems.add(items);
}
adapter = new CustomAdapterOrdini(getActivity(), rowItems);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
SendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "invio ordine in corso... ", Toast.LENGTH_SHORT)
.show();
SendOrdine();
}
});
}
#Override
public void onResume(){
super.onResume();
adapter.notifyDataSetChanged();
getListView().invalidateViews();
}
CustomAdapterOrdini
public class CustomAdapterOrdini extends BaseAdapter {
Context context;
List<RowItemOrdini> rowItem;
ImageView Del;
TextView Colli, Prezzo, Quantita, Code, Product;
CustomAdapterOrdini(Context context, List<RowItemOrdini> rowItem) {
this.context = context;
this.rowItem = rowItem;
}
#Override
public int getCount() {
return rowItem.size();
}
#Override
public Object getItem(int position) {
return rowItem.get(position);
}
#Override
public long getItemId(int position) {
return rowItem.indexOf(getItem(position));
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
return false;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.list_ordini, null);
}
Code = (TextView) convertView.findViewById(R.id.prodcode);
Product = (TextView) convertView.findViewById(R.id.PRODOTTO);
Del = (ImageView) convertView.findViewById(R.id.del);
Colli = (TextView) convertView.findViewById(R.id.T1);
Prezzo = (TextView) convertView.findViewById(R.id.T2);
Quantita = (TextView) convertView.findViewById(R.id.T3);
Del.setFocusable(true);
Del.setClickable(true);
Del.setTag(convertView);
final RowItemOrdini row_pos = rowItem.get(position);
// setting the image resource and title
Del.setImageResource(R.drawable.ic_delete_black_24dp);
Product.setText(row_pos.getTitle());
Code.setText(row_pos.getCode());
Colli.setText(row_pos.getColli());
Prezzo.setText(row_pos.getPrezzo());
Quantita.setText(row_pos.getQuantita());
Del.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// HERE I WANT REFRESH MY LISTVIEW
MainActivity.ArrayQuantita.remove(0);
MainActivity.ArrayCode.remove(0);
MainActivity.ArrayProdotto.remove(0);
MainActivity.ArrayColli.remove(0);
MainActivity.ArrayPrezzo.remove(0);
CustomAdapter.ShowDialog("Elemento eliminato con successo!", context);
}
});
return convertView;
}
Can someone help me with listview refresh?
I want refresh my listview in CustomAdapterOrdini or in onResume in Ordini.java.
public void onClick(View v) {
// HERE I WANT REFRESH MY LISTVIEW
There is a simple way?
Thank you so much!
You have declare ArrayProdotto in your MainActivity and you are display your data from rowItem in CustomAdapterOrdini. You have to remove your data from both list and call notifyDataSetChanged();
Like as below code.
Del.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// HERE I WANT REFRESH MY LISTVIEW
MainActivity.ArrayProdotto.remove(position); //Delete from main source
rowItem.remove(position) // Delete from adapter
CustomAdapter.ShowDialog("Elemento eliminato con successo!", context);
notifyDataSetChanged(); // Refresh Adapter
}
});
1). Remove your item from adapter:
adapter.remove(adapter.getItem(position));
2). Call adapter.notifyDataSetChanged();
You should call notifyDataSetChanged() every time when you deleting item from adapter. Not only in onResume.
Note, that you should remove item from adapter, to change ListView items, not from storage(ArrayList, SQLite, or else).

Add Item to ListView

I'm trying to add items at runtime to ListView placed on Tab.
But when I do so, I get an error. There are 3 tabs and I'm not using ListFragments, because I have different content in all tabs
my code below
SwipeTabFragment.java
public class SwipeTabFragment extends Fragment {
private String tab;
private int color;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
tab = bundle.getString("tab");
color = bundle.getInt("color");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.bookshelf, null);
TextView tv = (TextView) view.findViewById(R.id.textView);
tv.setText(tab);
view.setBackgroundResource(color);
return view;
}
}
TabPagerAdapter.java
public class TabPagerAdapter extends FragmentPagerAdapter {
public TabPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
Bundle bundle = new Bundle();
String tab = "";
int colorResId = 0;
SwipeTabFragment swipeTabFragment = new SwipeTabFragment();
switch (index) {
case 0:
tab = "BookShelf";
bundle.putString("tab",tab);
swipeTabFragment.setArguments(bundle);
return swipeTabFragment;
// break;
case 1:
tab = "Now Listening";
colorResId = R.color.color2;
BookFragment bookFragment = new BookFragment();
return bookFragment;
//break;
case 2:
tab = "Library";
colorResId = R.color.color3;
TabLibrary tabLibrary = new TabLibrary();
return tabLibrary;
break;
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
TabLibrary.java
public class TabLibrary extends Fragment {
final String LOG_TAG = "myLogs";
ListView lvLibList;
ImageButton btAddItem;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.library, parent, false);
ListView lvLibList = (ListView)v.findViewById(R.id.lvLibList);
ImageButton btn = (ImageButton)v.findViewById(R.id.btAddItem);
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText edit = (EditText)v.findViewById(R.id.eAddItem);
list.add(edit.getText().toString());
edit.setText("");
adapter.notifyDataSetChanged();
}
};
btn.setOnClickListener(listener);
lvLibList.setAdapter(adapter);
return v;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
#Gurusharan S is right, the problem is about the names of your variables. To avoid confusions I'd suggest to change your code to this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.library, parent, false); //Change the name from v to view
ListView lvLibList = (ListView)view.findViewById(R.id.lvLibList);
ImageButton btn = (ImageButton)view.findViewById(R.id.btAddItem);
EditText edit = (EditText)view.findViewById(R.id.eAddItem); //Initialize the EditText outside of the click method
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
list.add(edit.getText().toString());
edit.setText("");
adapter.notifyDataSetChanged();
}
};
btn.setOnClickListener(listener);
lvLibList.setAdapter(adapter);
return view;
}
And in the future I'd advice to give your variables more meaningful names, sometimes it takes you a little more coding but it is worth it.
Posting my comment as answer, as I'm pretty sure that is the issue:
The variable edit seems to be null. That is because when you call v.findViewById, you are actually calling it on the view that was clicked and NOT the fragment's view.
So you got two options:
Change the name of the fragment's view. eg. View v1 = inflater.inflate(R.layout.library, parent, false); and then change the line to v1.findViewById
Change the name of the argument of onClick. eg. public void onClick(View v1) {.
Hope that helps.

Categories