Android viewpager call setcurrentitem without onPageSelected - java

I have a viewPager with images and text in my android app, my target is to create a runnable to let this view pager scroll automatically, and my other target is when user click on one item in this viewpager i need to go to another activity.
This is my runnable:
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == NUM_PAGES - 1) {
currentPage = -1;
}
pager.setCurrentItem(currentPage++,true);
pager.setScrollBarFadeDuration(R.styleable.CirclePageIndicator_fillColor);
pager.setScrollDurationFactor(4);
mIndicator.setCurrentItem(currentPage++);
}
};
swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, 1000, 3000);
the problem is that every time the runnable call "SetCurrentItem()" the onpageselected function is called and then the activity is opened. So how can i prevent the onpageselected to be called when calling setCurrentItem every 3 seconds?
pager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
Picture current = (Picture)pageAdapter.getItem(arg0);
Article a = getArticleById(current.getArticleId(), p);
Bundle bundle=new Bundle();
Intent intent = new Intent();
intent.setClass(HomePageActivity.this,DetailActivity.class);
//.getString(tag)));
bundle.putParcelable("article", a);
bundle.putParcelableArrayList("pic", a.getPic());
intent.putExtras(bundle);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
currentPage=arg0;
//mIndicator.setCurrentItem(arg0);
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});

You should add a click listener to your ViewPager items inside of your adapter. onPageSelected method doesn't listen click events.
In instantiateItem method of your ViewPager adapter, do this:
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rootView = inflater.inflate(R.layout.your_layout, null);
rootView.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//do the click thing
}
});
container.addView(rootView);
return rootView;

Related

How to write Button.setOnClickListener in ViewPager

I have three pages in one ViewPager and I create a button on the Page1.
When I click that button,I can go the other activity.
I want to use Button setOnClickListener in ViewPager.
My app can run,but that button is not working.
Here is ViewPager activity file.
public class ScheduleActivity extends AppCompatActivity {
private View view1, view2, view3;
private List<View> viewList;
private ViewPager viewPager;
private List<String> titleList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule);
viewPager = (ViewPager) findViewById(R.id.viewpager);
PagerTitleStrip pagerTitleStrip = (PagerTitleStrip) findViewById(R.id.pager_title);
pagerTitleStrip.setTextSize(TypedValue.COMPLEX_UNIT_PX,70);
pagerTitleStrip.setTextColor(Color.WHITE);
pagerTitleStrip.setBackgroundColor(Color.BLUE);
pagerTitleStrip.setGravity(17);
pagerTitleStrip.getChildAt(0).setVisibility(View.GONE);
pagerTitleStrip.getChildAt(2).setVisibility(View.GONE);
LayoutInflater inflater = getLayoutInflater();
view1 = inflater.inflate(R.layout.activity_day__schedule, null);
view2 = inflater.inflate(R.layout.activity_week__schedule, null);
view3 = inflater.inflate(R.layout.activity_missing__date, null);
viewList = new ArrayList<View>();
viewList.add(view1);
viewList.add(view2);
viewList.add(view3);
titleList = new ArrayList<String>();
titleList.add("Page1");
titleList.add("Page2");
titleList.add("Page3");
PagerAdapter pagerAdapter = new PagerAdapter() {
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
// TODO Auto-generated method stub
return arg0 == viewList.get((int)
Integer.parseInt(arg1.toString()));
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return viewList.size();
}
#Override
public void destroyItem(ViewGroup container, int position,
Object object) {
// TODO Auto-generated method stub
container.removeView(viewList.get(position));
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
// TODO Auto-generated method stub
container.addView(viewList.get(position));
return position;
}
#Override
public CharSequence getPageTitle(int position) {
// TODO Auto-generated method stub
return titleList.get(position);
}
};
viewPager.setAdapter(pagerAdapter);
}
And here is button onclicklistener file...
public class Day_Schedule extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_day__schedule);
Button more_button = (Button) findViewById(R.id.more_button);
more_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Day_Schedule.this,
MaintainActivity.class);
startActivity(intent);
}
});
}
}
what can I do on these file? How to correct them?
you have to set the button listener inside the view pager adapter view and class code
try to organize your code to be more readable
https://github.com/android10/Android-CleanArchitecture

Remove element from listview (swipe or click)

I'm trying to create a dynamic listview. I can add an item but i can't remove it right now. The code actually it's very simple and every guide i saw are too much complicated for me and my code. I want something simple to add in my MainActivity to remove the item selceted. I don't care in which way, swipe like gmail or by click or any other way.. I just want i simple way to remove an element of the list. This is the Activity
public class MainActivity extends Activity {
private EditText etInput;
private Button btnAdd;
private ListView lvItem;
private ArrayList<String> itemArrey;
private ArrayAdapter<String> itemAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setUpView();
}
private void setUpView() {
// TODO Auto-generated method stub
etInput = (EditText)this.findViewById(R.id.editText_input);
btnAdd = (Button)this.findViewById(R.id.addbtn);
lvItem = (ListView)this.findViewById(R.id.listView_items);
itemArrey = new ArrayList<String>();
itemArrey.clear();
itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,itemArrey);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addItemList();
}
});
etInput.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_ENTER) {
addItemList();
}
return true;
}
});
}
protected void addItemList() {
if (isInputValid(etInput)) {
itemArrey.add(0,etInput.getText().toString());
etInput.setText("");
itemAdapter.notifyDataSetChanged();
}
}
protected boolean isInputValid(EditText etInput2) {
// TODO Auto-generatd method stub
if (etInput2.getText().toString().trim().length()<1) {
etInput2.setError("Insert a value");
return false;
} else {
return true;
}
}
}
Is it possible insert some part of code to remove an item inside my activity code? Thanks
try this, While ListView item long ClickListener you can do it
lvItem.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View v,
int position, long id) {
// TODO Auto-generated method stub
AlertDialog.Builder adb = new AlertDialog.Builder(
YourActivity.this);
adb.setTitle("Are you sure want to delete this item");
adb.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
itemArrey.remove(position);
itemAdapter.notifyDataSetChanged();
}
});
adb.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
adb.show();
return false;
}
});
This should help you.
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long id) {
itemArrey.remove(position);
itemAdapter.notifyDataSetChanged();
return true;
}
});
Put this method in your onCreate:
lvItem .setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,int position, long id) {
itemArrey.remove(position);
itemAdapter.notifyDataSetChanged();
});
}
Of course it is possible.
ArrayList.html#remove
Or if you don't know the index just iterate through the list.
Calling remove in foreach loop in Java
Do this way..
lvItem.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long id) {
itemArrey.remove(position);
itemAdapter.notifyDataSetChanged();
return true;
}
});
To delete item from list just do one thing, get onLongClickListener of listView.
Then open the context menu which has two options
Delete
Cancel
When user picks first item delete it from list. Then call listadapter notify datasetChanged method.
Use this library, I used this and it works very fine, if you prefer Swipe try this:
https://github.com/47deg/android-swipelistview
Try below code:
single click:
listview .setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,int position, long id) {
showDialog(int position);
});
}
public void showDialog(int position){
AlertDialog alertDialog;
AlertDialog.Builder builder = new AlertDialog.Builder(BaseActivity.this);
alertDialog = builder.create();
alertDialog.setOnDismissListener(new myOnDismissListener());
alertDialog.setTitle(TITLE OF DIALOG);
alertDialog.setMessage(MESSAGE YOU WANT TO SHOW IN DIALOG);
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
YOUR ARRAY.remove(position);
YOUR ADAPTER.notifyDataSetChanged();
}
});
alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alertDialog.show();
}

OnItemClickListener is not being called

I have an ItemClickListener in a gridview. But my itemclicklistener is not being called. There is no activity on item click of the gridview
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
vi = inflater.inflate(R.layout.home, container, false);
Button startdialog = (Button) vi.findViewById(R.id.btnCreateDialog);
startdialog.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent startdialog = new Intent(getActivity(),
start_dialog.class);
startActivity(startdialog);
}
});
Button iv = (Button) vi.findViewById(R.id.btnMoreDialog);
iv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu homepopup = new PopupMenu(getActivity(), v);
MenuInflater inflater = homepopup.getMenuInflater();
inflater.inflate(R.menu.moredialog, homepopup.getMenu());
homepopup.show();
}
});
PremiumgridView = (StaggeredGridView) vi
.findViewById(R.id.premiumstaggeredGridView);
new Dialogs().execute(urls);
return vi;
}
private class Dialogs extends AsyncTask<String[], Void, String[]> {
#Override
protected String[] doInBackground(String[]... params) {
return params[0];
}
protected void onPostExecute(String[] result) {
int premiummargin = getResources().getDimensionPixelSize(
R.dimen.margin);
PremiumgridView.setItemMargin(premiummargin);
PremiumgridView.setPadding(premiummargin, 0, premiummargin, 0);
final StaggeredAdapter premiumadapter = new StaggeredAdapter(
vi.getContext(), R.id.photoimageview, result,
R.layout.row_staggered_demo);
PremiumgridView.setAdapter(premiumadapter);
premiumadapter.notifyDataSetChanged();
premiumadapter.onClick(vi);
PremiumgridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(StaggeredGridView parent, View view,
int position, long id) {
String item = premiumadapter.getItem(position).toString();
Toast.makeText(getActivity(), premiumadapter.getItem(position), Toast.LENGTH_SHORT).show();
// Toast.makeText(getActivity(), "You have chose: "+ item, Toast.LENGTH_LONG).show();
}});
}
#Override
protected void onPreExecute() {
}
}
Anyone please?
Thanks,
Solved the problem by removing the button from the xml. Clickable item cannot have another clickable item inside it. Reference OnItemClickListener Not Triggered on Android GridView
Does it crash? If yes, always provide us with the Stacktrace/Logcat.
As far as I know, it´s impossible to directly change the interface from within any Thread other than the UI-Thread - you could either try Handler or use this.
EDIT: OnPostExecute is actually called on the UI-Thread, so this is not a solution for this problem. (see here)

how to assign different activities to each item of the spinner?

I have a page which consist of a spinner and a submit button. What I want to achieve is when user selects an item in the list and click on submit, it should take him to an other layout having a webview. Each item in the spinner should open different .html page in the layout.
What I have now is the item is being selected from the spinner, but I'm not sure how to perform onclick listener to it...
code for main activity is here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.beef);
addListenerOnButton();
addListenerOnSpinnerItemSelection();
}
public void addListenerOnSpinnerItemSelection(){
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
//get the selected dropdown list value
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
btnSubmit = (ImageButton) findViewById(R.id.imageButton1);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*Nothing as of now*/
//I need to call the ID of the selected item from the spinner here and start new activity
}
});
}
}
code of CustomOnItemSelectedListener is here
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
if (arg2 == 0) // First item selected
{
//Here I need to give an id for the .html file
}
else if (arg2 == 1) // Second
{
//Here I need to give an id for the .html file
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String selItem = arg0.get(arg2); // String representation of the selected item
if (arg2 == 0) // First item selected
{
}
else if (arg2 == 1) // Second
{
}
// etc
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}

android-Button's clickevent of listView using BaseAdapter

I am using Listview With custom Adapter which contain imageview,textview and 3 button (insert,update,delete)requirement is that custom adapter is call every time inside BROADCAST receiver until intentfilter matched and i also set onclicklistener of button in getView method of base adapter.
The problem is that only the last row of listview button is only clickable..But i want all the button of all row must clickable.
Can anybody give me suggestion or any idea how I can proceed for that problem.
public View getView(final int position, View view, ViewGroup parent) {
// TODO Auto-generated method stub
pos=position;
if(view==null)
{
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view=inflater.inflate(R.layout.device_name, parent, false);
}
TextView text_view=(TextView)view.findViewById(R.id.textview_deviceName);
ImageView image_view=(ImageView)view.findViewById(R.id.imageView1);
text_view.setText(strDeviceName[position]);
if(strMajorDevice[position].equalsIgnoreCase("phone"))
{
image_view.setImageResource(int_image[0]);
}
else
{
image_view.setImageResource(int_image[1]);
}
btnAdd=(Button)view.findViewById(R.id.btn_add);
btnUpdate=(Button)view.findViewById(R.id.btn_update);
btnDelete=(Button)view.findViewById(R.id.btn_delete);
btnAdd.setOnClickListener(this);
btnUpdate.setOnClickListener(this);
btnDelete.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==btnAdd)
{
Toast.makeText(context, "ADD", Toast.LENGTH_LONG).show();
Intent intent = new Intent(context,MaterDeviceFormActivity.class);
intent.putExtra("button","add");
intent.putExtra("device_address", strDviceAddess[pos]);
context.startActivity(intent);
}
else if(v==btnUpdate)
{
Toast.makeText(context, "UPDATE", Toast.LENGTH_LONG).show();
Intent intent = new Intent(context,MaterDeviceFormActivity.class);
intent.putExtra("button","update");
intent.putExtra("device_address", strDviceAddess[pos]);
context.startActivity(intent);
}
else if(v==btnDelete)
{
Toast.makeText(context, "DELETE", Toast.LENGTH_LONG).show();
Intent intent = new Intent(context,MaterDeviceFormActivity.class);
intent.putExtra("button","delete");
intent.putExtra("device_address", strDviceAddess[pos]);
context.startActivity(intent);
}
}
private Context context;
public ListViewAdapter(Context context, String[] dateValues,String[] creditAmountValues,String[] closingBalanceValues,String[] currentAmountValues)
{
super(context, R.layout.transactionlayout, dateValues);
this.context = context;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.transactionlayout, parent, false);
((Button)rowView.findViewById(R.id.transactions_historyButtonID)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, ""+position, 4000).show();
}
});
return rowView;
}
get the use of row view using inflater. this is working. let me know if u have any doubts.
set the tag for each view in get view method by setTag()
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = context.getLayoutInflater();
convertView = inflater.inflate(.....);
}
ur_view= (views) convertView.findViewById(R.id.....);
ur_view.setTag(position);
ur_view.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//do something
}
});
It will work
- In think you have not Registered all the Buttons with the OnClickListener Interface.
Try this, may be it will solve your problem.
btnAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Integer index = (Integer) arg0.getTag();
Toast.makeText(context, "ADD", Toast.LENGTH_LONG).show();
Intent intent = new Intent(context,MaterDeviceFormActivity.class);
intent.putExtra("button","add");
intent.putExtra("device_address", strDviceAddess[index]);
context.startActivity(intent);
}
});
btnUpdate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Integer index = (Integer) arg0.getTag();
Toast.makeText(context, "UPDATE", Toast.LENGTH_LONG).show();
Intent intent = new Intent(context,MaterDeviceFormActivity.class);
intent.putExtra("button","update");
intent.putExtra("device_address", strDviceAddess[index]);
context.startActivity(intent);
}
});
btnDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Integer index = (Integer) arg0.getTag();
Toast.makeText(context, "DELETE", Toast.LENGTH_LONG).show();
Intent intent = new Intent(context,MaterDeviceFormActivity.class);
intent.putExtra("button","delete");
intent.putExtra("device_address", strDviceAddess[index]);
context.startActivity(intent);
}
});
You can use the button listener inside the the adapter but the only item to register it will be the last item drawn (ie the one immediately off the list). You need to tell the button listener which item it has been clicked on. In my case I just passed in the position and used that to load any associated info needed to manipulate the list item.

Categories