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)
Related
I know there are similar questions but I couldn't find an answer to solve my problem.
I have a DialogUpdateEmail which I want to be opened from ProfileFragment. In the dialog I want to enter my new email and send it to my ProfileFragment in order to change it also in the database.
ProfileFragment.java :
import androidx.fragment.app.Fragment;
public class ProfileFragment extends Fragment implements SendInputEmail {
public static final int PROFILE_FRAGMENT = 1;
private static final String TAG = "ProfileFragment";
private TextView TVHello, TVUsernameMessage, TVusernameinfo, TVemailinfo, TVbirthdate;
public void sendInput(String input) {
Log.d(TAG, "sendInput: found incoming input: " + input);
TVemailinfo.setText(input);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_profile, container, false);
Button Bsignout = (Button) v.findViewById(R.id.signoutbutton);
Button Beditusername = (Button) v.findViewById(R.id.editusernamebutton);
Button Beditemail = (Button) v.findViewById(R.id.editemailbutton);
Beditemail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: opening email dialog");
DialogUpdateEmail dialog = new DialogUpdateEmail();
dialog.setTargetFragment(ProfileFragment.this,PROFILE_FRAGMENT);
dialog.show(getActivity().getFragmentManager(), "DialogUpdateEmail");
}
});
return v;
}
DialogUpdateEmail.java :
public class DialogUpdateEmail extends DialogFragment implements SendInputEmail {
private static final String TAG = "DialogUpdateEmail";
SendInputEmail mHost = (SendInputEmail)getTargetFragment();
public View onCreateView(final LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.popup, container, false);
EditText UpdateEmail = (EditText) view.findViewById(R.id.emailinfoupdate);
Button Beditemail = (Button) view.findViewById(R.id.updatesavebutton);
Button Bcancelemail = (Button) view.findViewById(R.id.updatecancelbutton);
Beditemail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: capturing input.");
String input = UpdateEmail.getText().toString();
Log.d(TAG, "input : "+input);
mHost.sendInput(input);
getDialog().dismiss();
}
});
return view ;
}
public void onAttach(Context context) {
super.onAttach(context);
try{
mHost = (SendInputEmail) getTargetFragment();
}catch (ClassCastException e){
Log.e(TAG, "onAttach: ClassCastException : " + e.getMessage() );
}
}
#Override
public void sendInput(String input) {
}
}
SendInputEmail Interface :
public interface SendInputEmail {
void sendInput(String input);
}
My problem is that I have an error when I try to use setTargetFragment in ProfileFragment. It says that Profile Fragment is not a Fragment, I really don't know why.
From doc in here :
public class DialogUpdateEmail extends DialogFragment {
private DialogEditListener listener;
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = requireActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
View view = inflater.inflate(R.layout.popup, null);
builder.setView(view);
EditText UpdateEmail = (EditText) view.findViewById(R.id.emailinfoupdate);
Button Beditemail = (Button) view.findViewById(R.id.updatesavebutton);
Button Bcancelemail = (Button) view.findViewById(R.id.updatecancelbutton);
Beditemail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
listener.onDialogEditClick(UpdateEmail.getText().toString());
DialogUpdateEmail.this.getDialog().dismiss();
}
}
});
Bcancelemail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogUpdateEmail.this.getDialog().cancel();
}
});
return builder.create();
}
public interface DialogEditListener {
void onDialogEditClick(String email);
}
public void setListener(DialogEditListener listener) {
this.listener = listener;
}
}
We send the email from the dialog to the fragment using the observer/listener pattern.
And in your ProfileFragment just implement DialogEditListener and subscribe it to listen for click button in the dialog like so:
public class ProfileFragment extends Fragment
implements SendInputEmail, DialogUpdateEmail.DialogEditListener {
public static final int PROFILE_FRAGMENT = 1;
private static final String TAG = "ProfileFragment";
private TextView TVHello, TVUsernameMessage, TVusernameinfo, TVemailinfo, TVbirthdate;
public void sendInput(String input) {
Log.d(TAG, "sendInput: found incoming input: " + input);
TVemailinfo.setText(input);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_profile, container, false);
Button Bsignout = (Button) v.findViewById(R.id.signoutbutton);
Button Beditusername = (Button) v.findViewById(R.id.editusernamebutton);
Button Beditemail = (Button) v.findViewById(R.id.editemailbutton);
Beditemail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: opening email dialog");
//show your dialog
DialogUpdateEmail dialogUpdateEmail = new DialogUpdateEmail();
dialogUpdateEmail.setListener(ProfileFragment.this);
dialogUpdateEmail.show(getActivity().getSupportFragmentManager(), "DialogUpdateEmail");
}
});
return v;
}
#Override
public void onDialogEditClick(String email) {
//use your email here
Toast.makeText(getContext(), "My email: " + email, Toast.LENGTH_SHORT).show();
}
}
I'm trying to implent the next code in Android Studio and it does not work.
I want to pass from a Fragment (GalleryFragment) to an Activity (postropa) with a button.
I have linked the botton with the function (BotonPulsado) and I don't know what is wrong (In the design view).
Design View
Code:
import (...)
public class GalleryFragment extends Fragment {
private GalleryViewModel galleryViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
galleryViewModel =
ViewModelProviders.of(this).get(GalleryViewModel.class);
View root = inflater.inflate(R.layout.fragment_gallery, container, false);
final TextView textView = root.findViewById(R.id.text_gallery);
galleryViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
return root;
}
public void BotonPulsado(View view) {
Intent intent = new Intent(getContext(), postropa.class);
startActivity(intent);
}
}
You should create Button variаble as a class field.
private GalleryViewModel galleryViewModel;
Button button; <<-------
After that you need to define it in method onCreateView()
button = (Button) findViewById(R.id.button2);
And set onClickListener() on this button to handle the call.
There you must call the method that starts the activity.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BotonPulsado();
}
});
Your final code:
import (...)
public class GalleryFragment extends Fragment {
private GalleryViewModel galleryViewModel;
Button button;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
galleryViewModel =
ViewModelProviders.of(this).get(GalleryViewModel.class);
View root = inflater.inflate(R.layout.fragment_gallery, container, false);
final TextView textView = root.findViewById(R.id.text_gallery);
galleryViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
button = (Button) findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BotonPulsado();
}
});
return root;
}
public void BotonPulsado() {
Intent intent = new Intent(getContext(), postropa.class);
startActivity(intent);
}
}
I am trying to pass information from my alert dialog to my second fragment (I am using tabbed activity layout).
I want to pass information from alert dialog to fragment when I click on my ImageView, but my app keep crashing until I implement my interface inside MainActivity.java. My main mission here is to open alert dialog which contains several buttons. When I click first button I want to print "Test br 3" but it does not work inside my Fragment, it only works inside my MainActivity.java where method prints "Test br 2".
My Main Activity
public class MainActivity extends AppCompatActivity implements ExercisesAlertDialog.DataTransfer {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
#Override
public void ApplyData() {
System.out.println("Test br 2");
}
My Fragment
public class Frag2 extends Fragment implements ExercisesAlertDialog.DataTransfer {
ImageView plusbtn;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag2, container, false);
plusbtn = (ImageView) v.findViewById(R.id.plusbtn);
plusbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ExercisesDialog();
}
});
return v;
}
public void ExercisesDialog()
{
ExercisesAlertDialog exercisesAlertDialog = new ExercisesAlertDialog();
exercisesAlertDialog.show(getFragmentManager(), "Exercises Dialog");
}
#Override
public void ApplyData() {
System.out.println("Test br 3");
}
My Alert Dialog
public class ExercisesAlertDialog extends AppCompatDialogFragment {
ImageButton one, two;
private DataTransfer listener;
public int first;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.workout_custom_menu, null);
builder.setView(v);
builder.setTitle("Choose your Workout");
builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dismiss();
}
});
one = (ImageButton) v.findViewById(R.id.first);
two = (ImageButton) v.findViewById(R.id.second);
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
first = 1;
if(first ==1)
{
listener.ApplyData();
}
}
});
return builder.create();
}
public interface DataTransfer
{
void ApplyData();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
listener = (DataTransfer) context;
}
catch (ClassCastException e)
{
throw new ClassCastException(toString() + "Must implement DataTransfer");
}
}
}
I changed getChildFragmentManager() instead of getFragmentManager() in the show() call. Second thing is onAttach() to listener = (DataTransfer) getParentFragment(); instead of context.
My java Project have 4 fragment.
One of the fragment is a chat room, it will require user to input name in a popup-alertDialog when page is called.
Here is the bug. When I put the chatroom to Tab 4, Tab 3 will wrongly display the alertDialog when it(Tab3) was clicked.
When I put the chatroom to Tab 2, Tab 1 and Tab 3 will also have the same problem.
It is tricky to me, I have no idea where the bug come from.
Here is my chatroom.java
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.tab_match_chatroom, container, false);
add_room = (Button) v.findViewById(R.id.btn_add_room);
room_name = (EditText) v.findViewById(R.id.room_name_edittext);
listView = (ListView) v.findViewById(R.id.listView);
listView.setAdapter(arrayAdapter);
add_room.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Map<String, Object> map = new HashMap<String, Object>();
map.put(room_name.getText().toString(), "");
root.updateChildren(map);
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getActivity().getApplicationContext(), TabInChatRoom.class);
intent.putExtra("room_name", ((TextView) view).getText().toString());
intent.putExtra("user_name", name);
startActivity(intent);
}
});
return v;
}
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
arrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list_of_rooms);
request_user_name();
root.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Set<String> set = new HashSet<String>();
Iterator i = dataSnapshot.getChildren().iterator();
while (i.hasNext()) {
set.add(((DataSnapshot) i.next()).getKey());
}
list_of_rooms.clear();
list_of_rooms.addAll(set);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void request_user_name() {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Enter name:");
final EditText input_field = new EditText(getActivity());
builder.setView(input_field);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
name = input_field.getText().toString();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
request_user_name();
}
});
builder.show();
}
You are showing the popup when the 4th fragment is created (inside onCreate method)
How is it working?
There are multiple related things triggering the issue.
1- ViewPager has offset page limit and default value is 1 (3 Tabs at once). You can change this value. That means, your viewPager only creates 1 from left side, 1 from right side of your current page. Others will be destroyed and recreated when you select fragment in the range limit.
2- When ViewPager has more fragment than is offsetPageLimit, it will not create further ranged Fragments For example: If you have 4 Fragments, first fragment and the 2nd one will be created at start, 4th one will be created when you selected 3rd or 4th tabs.
3- When you select the 3rd or 4th tabs, you are recreating the 4th fragment and it calls onCreate method and afterwards it calls the request_user_name() eventually. And your popup shows up.
First, you can change the viewPagers offsetPage limit by 4 for convenience.
viewPager.setOffscreenPageLimit(4);
Secondly, you need to call request_user_name() method when the Tab 4 clicked, not the 4th fragment created.
You can use OnPageChangeListener like below:
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if(position == 3){
//that means 4th tab
//show the popup
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
More Info:
Link 1
Link 2
i have one edittext and button.first time my edittext.settext is 1.now i try to check if edidtext.gettext().toString.equels some values do somethink
public class StradaMenuResultReadMore extends Fragment {
public static ImageView buy_btn;
private EditText price_counter;
int av;
private String counterString;
#SuppressLint("UseValueOf")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.strada_menu_result_loadmore,
container, false);
buy_btn = (ImageView) rootView.findViewById(R.id.strada_buy_btn);
price_counter = (EditText) rootView
.findViewById(R.id.strada_price_counter);
price_counter.setText("1");
counterString = price_counter.getText().toString();
av = Integer.parseInt(counterString);
buy_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (counterString.equals("1")) {
Toast.makeText(getActivity(), "one", Toast.LENGTH_SHORT)
.show();
} else
{
Toast.makeText(getActivity(), "two", Toast.LENGTH_SHORT)
.show();
}
}
});
return rootView;
}
at the moment my code working complitly,but if i change edittext input value and then click button,then my code not working
how i can solve my problem?
In your onClick you need to get the value from the EditText, since counterString still contains the old value "1":
buy_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
counterString = price_counter.getText().toString();
....
counterString = price_counter.getText().toString();
Put this line inside onClick
Since oncreateView() is called between onCreate(Bundle) and onActivityCreated(Bundle), it's called only once and your string is that you are using to compare always remains 1. Hence the issue.
Change this :
buy_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
counterString = price_counter.getText().toString();
if (counterString.equals("1")) {
Toast.makeText(getActivity(), "one", Toast.LENGTH_SHORT)
.show();
} else{
Toast.makeText(getActivity(), "two", Toast.LENGTH_SHORT)
.show();
}
}
});