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.
Related
I have implemented an onclicklistener on a button to open Gallery when I click the button in the app nothing happens
Code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_statusfragment,container,false);
imageView = view.findViewById(R.id.imageView);
button = (Button)view.findViewById(R.id.button2);
textView = view.findViewById(R.id.textView);
view.findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(),"Upload screenshot",Toast.LENGTH_LONG).show();
if(ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
requestPermissions(
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
2000);
}else {
Toast.makeText(getActivity(), "Choose Screenshot", Toast.LENGTH_LONG).show();
imageView.setVisibility(View.VISIBLE);
button.setVisibility(View.VISIBLE);
textView.setVisibility(View.VISIBLE);
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(intent,1000);
}
}
}
});
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_statusfragment, container, false);
}
it also does not display the Toast message
Instead of return inflater.inflate(R.layout.fragment_statusfragment, container, false);
do return view;
Very first try to do all the UI work in onViewCreated() method of Fragment.
Here you are not returning the initialized view above in the last and use button variable to implement click listener.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_statusfragment,container,false);
imageView = view.findViewById(R.id.imageView);
button = (Button)view.findViewById(R.id.button2);
textView = view.findViewById(R.id.textView);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(),"Upload screenshot",Toast.LENGTH_LONG).show();
if(ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
requestPermissions(
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
2000);
}else {
Toast.makeText(getActivity(), "Choose Screenshot", Toast.LENGTH_LONG).show();
imageView.setVisibility(View.VISIBLE);
button.setVisibility(View.VISIBLE);
textView.setVisibility(View.VISIBLE);
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(intent,1000);
}
}
}
});
// Inflate the layout for this fragment
return view;
}
You are already initializing the inflater.inflate(R.layout.fragment_statusfragment, container, false); at the beginning and assigning it to View view, so just return view; at the end.
I am not able to change layout when clicking on the button. Actually, I always use this code:
#Override
public void onClick(View view) {
if (view == imageButtonOrders) {
startActivity(new Intent(this, Order.class)); }
Now, I want to use this function in my ListView. But when I use it I am getting an error. How can I fix it?
SwipeListAdapterP.java
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.product_items, null);
TextView pk = (TextView) convertView.findViewById(R.id.pk);
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView point = (TextView) convertView.findViewById(R.id.point);
ImageButton imageButtonDelete = (ImageButton) convertView.findViewById(R.id.imageButtonDelete);
ImageButton imageButtonUpdate = (ImageButton) convertView.findViewById(R.id.imageButtonUpdate);
ProductItems m = productList.get(position);
pk.setText(String.valueOf(m.getPk()));
name.setText(String.valueOf(m.getName()));
point.setText(String.valueOf(m.getPoint()));
imageButtonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(this, Order.class));
}});
You need your parent activity context to start Activity from your Adapter class.
instead of:
startActivity(new Intent(this, Order.class));
use:
activity.startActivity(new Intent(activity, Order.class));
where activity is the Activity context your are passing to your Adapter class
try OnClick this way
//cast imageButtonOrders by findViewById()
#Override
public void onClick(View view) {
if (view.getId() == imageButtonOrders) {
startActivity(new Intent(this, Order.class));
}
in Adapter You need to Initialize Context with Activity reference and pass that Context on Intent
imageButtonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(`Context`, Order.class));
}});
I am trying to implement a spinner that is in a popup. When one selects an item and clicks the button it will display according to the selected item in the spinner.
String[]Company={"Cash","M-Pesa","Voucher","Credit-Card"};
Below is the popup containing the spinner
private void callPopup() {
LayoutInflater layoutInflater=(LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView=layoutInflater.inflate(R.layout.popup1,null);
//final PopupWindow popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
final PopupWindow popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, true);
popupWindow.setTouchable(true);
popupWindow.setFocusable(true);
popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
final Spinner popupSpinner=(Spinner)popupView.findViewById(R.id.spinner);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(StartWatchActivity.this,android.R.layout.simple_spinner_dropdown_item, Company);
popupSpinner.setAdapter(adapter);
Name =(EditText)popupView.findViewById(R.id.edtimageName);
Name.setText(String.valueOf(amount));
final Spinner spnLocale;
spnLocale=(Spinner)findViewById(R.id.spinner);
//int iCurrentSelection=spnLocale.getSelectedItemPosition();
// TextView txtView = (TextView)popupView.findViewById(R.id.txtView);
// txtView.setText("Total Cars Packed:\t" +amount +" Cars");
((Button) popupView.findViewById(R.id.saveBtn)).setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void onClick(View v) {
spnLocale.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (!(spnLocale.getSelectedItem().toString().trim().equals("Company"))) {
if (spnLocale.getSelectedItem().toString().trim().equals("Cash")) {
Toast.makeText(StartWatchActivity.this, "Amount Paid :\t" + Name.getText().toString(), Toast.LENGTH_LONG).show();
} else if (spnLocale.getSelectedItem().toString().trim().equals("M-pesa")) {
Toast.makeText(StartWatchActivity.this, "Amount Paid :\t" + Name.getText().toString(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// Toast.makeText(getBaseContext(), "Amount paid", Toast.LENGTH_SHORT).show();
// Toast.makeText(getApplicationContext(), Name.getText().toString(), Toast.LENGTH_LONG).show();
popupWindow.dismiss();
}
});
((Button)popupView.findViewById(R.id.cancelbutton)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
popupWindow.dismiss();
}
});
popupWindow.showAsDropDown(saveBtn, 50,-30);
}
Don't mind the commented codes
try this code:
String name= null;
if(popupSpinner != null && popupSpinner.getSelectedItem() !=null ) {
name = (String)popupSpinner.getSelectedItem();
//get the name of current selected item..
} else {
//nothing is selected
}
Use below code to add spinner in popup and get it selected item as toast.
private void openSpinnerpopup() {
//inflate the layout
LayoutInflater li = LayoutInflater.from(MainActivity.this);
View promptsView = li.inflate(R.layout.my_dialog_layout, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
//set the inflated layout in the dialog.
alertDialogBuilder.setView(promptsView);
// create alert dialog
alertDialog = alertDialogBuilder.create();
final Spinner mSpinner = (Spinner) promptsView
.findViewById(R.id.spinner);
// reference UI elements from my_dialog_layout in similar fashion
mSpinner.setOnItemSelectedListener(new OnSpinnerItemClicked());
// show it
alertDialog.show();
alertDialog.setCancelable(true);
}
//for spinneritemclick.
public class OnSpinnerItemClicked implements AdapterView.OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
Toast.makeText(parent.getContext(), "Selected : " +
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
btn.setText(parent.getSelectedItem().toString());
}
#Override
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
call it on buttonclick:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//open spinner as dialog
openSpinnerpopup();
}
});
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;
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)