I set the view to a layout with scrollview and linearlayout, and set a button added in the title to add new row in the linearlayout, but new row does not appear, any tips? I plan to use this DialogFragment as a BLE search, is this a good way to solve it?
public class BLE_Devices_Fragment extends DialogFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout to use as dialog or embedded fragment
return inflater.inflate(R.layout.fragment_ble_devices, container, false);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
LinearLayout layout = inflater.inflate(R.layout.fragment_ble_devices, null).findViewById(R.id.deviceList);
View titleView = inflater.inflate(R.layout.bluetoothscan_title, null, false);
ImageButton syncBLEButton = titleView.findViewById(R.id.syncBLEButton);
syncBLEButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
layout.addView(new Button(layout.getContext()));
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.setCustomTitle(inflater.inflate(R.layout.bluetoothscan_title, null)).create();
builder.setView(inflater.inflate(R.layout.fragment_ble_devices, null));
// Create the AlertDialog object and return it
return builder.create();
}
}
Replace
builder.setView(inflater.inflate(R.layout.fragment_ble_devices, null));
with
builder.setView(layout);
Solved: had to set the views instead, not create new ones.
Related
I am new to android studio and Java. I have create custom dialog box with input textbox. I want to pass data from custom dialog to fragment layout. How can I achieve that ?
I saw this post but didn't get it. Please help me out !
Passing a data from Dialog to Fragment in android
Edited
Here's my code >>
public class IncomeFragment extends Fragment{
TextView title, textRsTotal;
Dialog dialog;
int total = 0;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
title = view.findViewById(R.id.totalIncomeTitle);
Button button = view.findViewById(R.id.addIncomeBtn);
textRsTotal = view.findViewById(R.id.totalExpenseTitle);
dialog = new Dialog(getActivity());
if (getActivity() != null) {
if (!CheckInternet.isNetworkAvailable(getActivity())) {
//show no internet connection !
}
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.setContentView(R.layout.income_custom_dialog);
dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
RadioGroup radioGroup = dialog.findViewById(R.id.radioGroup);
Button buttonAdd = dialog.findViewById(R.id.addBtn);
TextInputEditText editText = dialog.findViewById(R.id.editText);
radioGroup.clearCheck();
radioGroup.animate();
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
RadioButton radioButton = (RadioButton) radioGroup.findViewById(checkedId);
}
});
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int selectedId = radioGroup.getCheckedRadioButtonId();
if (selectedId == -1) {
Toast.makeText(getActivity(), "Please select your income type", Toast.LENGTH_SHORT).show();
} else {
RadioButton radioButton = (RadioButton) radioGroup.findViewById(selectedId);
String getIncome = editText.getText().toString();
Toast.makeText(getActivity(), radioButton.getText() + " is selected & total is Rs."+ total, Toast.LENGTH_SHORT).show();
}
}
});
dialog.show();
}
});
super.onViewCreated(view, savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_income, container, false);
// Inflate the layout for this fragment
return view;
}
}
Ok, try this :
public class IncomeFragment extends Fragment {
TextView title, textRsTotal;
Dialog dialog;
int total = 0;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
title = view.findViewById(R.id.totalIncomeTitle);
Button button = view.findViewById(R.id.addIncomeBtn);
textRsTotal = view.findViewById(R.id.totalExpenseTitle);
dialog = new Dialog(getActivity());
if (getActivity() != null) {
if (!CheckInternet.isNetworkAvailable(getActivity())) {
//show no internet connection !
}
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog(new MyCallback() {
#Override
public void setText(String text) {
textRsTotal.setText(text);
}
});
}
});
super.onViewCreated(view, savedInstanceState);
}
private void showDialog(MyCallback myCallback) {
dialog.setContentView(R.layout.income_custom_dialog);
dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
RadioGroup radioGroup = dialog.findViewById(R.id.radioGroup);
Button buttonAdd = dialog.findViewById(R.id.addBtn);
TextInputEditText editText = dialog.findViewById(R.id.editText);
radioGroup.clearCheck();
radioGroup.animate();
radioGroup.setOnCheckedChangeListener((radioGroup1, checkedId) -> {
RadioButton radioButton = (RadioButton) radioGroup1.findViewById(checkedId);
});
buttonAdd.setOnClickListener(view1 -> {
int selectedId = radioGroup.getCheckedRadioButtonId();
if (selectedId == -1) {
Toast.makeText(getActivity(), "Please select your income type", Toast.LENGTH_SHORT).show();
} else {
RadioButton radioButton = (RadioButton) radioGroup.findViewById(selectedId);
String getIncome = editText.getText().toString();
myCallback.setText(getIncome);
Toast.makeText(getActivity(), radioButton.getText() + " is selected & total is Rs." + total, Toast.LENGTH_SHORT).show();
}
});
dialog.show();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_income, container, false);
return view;
}
public interface MyCallback {
void setText(String text);
}
}
There are more than one method to achieve that, the one mentioned in the url you provided is suggesting to use a simple callback to forward event and data back to the calling fragment. So the pieces you are needing are all there:
Write a callback interface: public interface Callback1{ public void onInteraction(String thingToCommunicateBack); }
In your fragment: and while building the instance of your dialog, pass an instance you've built of Callback1 to that dialog like this Callback1 mCallback = new Callback1() { public void onInteraction(String thingToCommunicateBack) { /*TODO receive data, handle and update layout*/ }; (the whole fragment could be that instance using the keyword this if you decide to implement the interface there instead, like this
class Fragment1 extends Fragment implements Callback1 and implement its method within fragment's class after the keyword override)
In your Dialog class: when the interaction (click) that should trigger the event and send data back happens, invoke callback's method like this: mCallback1.onInteraction("text from your EditText to pass")
Now, you passed some data from custom dialog back to a fragment.
Hello I want to move to another activity from my fragment. I ve tried almost every solution which I found, but after I press button my app is instantly closed. I am new in java, and i guess i need some help.
public class GalleryFragment extends Fragment {
private GalleryViewModel galleryViewModel;
Intent intent;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_gallery, container, false);
intent = new Intent(GalleryFragment.this.getActivity(), HomeFragment.class);
final Button btn = (Button) rootView.findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(intent);
}
});
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(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
I'm assuming from this line:
intent = new Intent(GalleryFragment.this.getActivity(), HomeFragment.class);
That you're trying to launch a Fragment, not an Activity. In order to transition to another Fragment, replace your Intent with:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getFragmentManager()
.beginTransaction()
.replace(...) //Or add, depends on your use case
.commit();
}
});
I've been struggling for few days on this issue. My project is having 4 fragments which share the same floating button. I have managed to reference the fragments in order to allow the floating button to access each, however although I'm shifting between each fragment, it showing the position of the first one only. here's my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setNavigationViewListener();
//set the drawer layout and navigation view
mDrawerLayout = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
//set item selected persist highlight
menuItem.setChecked(true);
//close drawer
mDrawerLayout.closeDrawers();
//set action as per the item selected
return true;
}
});
//create an adapter that knows where each fragment is
final LocationFragmentAdapter adapter = new LocationFragmentAdapter(this, getSupportFragmentManager());
mViewPager = findViewById(R.id.viewPager);
mViewPager.setAdapter(adapter);
adapter.getItem(position);
//set the function for the floating button to add a new item
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(LOG_TAG, "the current fragment " + adapter.getPageTitle(position));
if(position == 0) {
Intent intent = new Intent(MainActivity.this, EditorActivity.class);
startActivity(intent);
}
else if (position == 1) {
Intent intent = new Intent(MainActivity.this, RecipeEditor.class);
startActivity(intent);
}
}
});
}
this is my fragmentAdapter
public class LocationFragmentAdapter extends FragmentPagerAdapter {
final int count = 4;
private int [] tabTitle = {R.string.inventory_platform, R.string.product_platform, R.string.customer_platform, R.string.order_platform};
private Context mContext;
public LocationFragmentAdapter(Context context, FragmentManager fm){
super(fm);
mContext = context;
}
#Override
public Fragment getItem(int position) {
if(position == 0) {
return new InventoryFragment();
}else if(position == 1) {
return new RecipeFragment();
}else if(position == 2) {
return new CustomerFragment();
}else {
return new OrderFragment();
}
}
thats my InventoryFragment
#Override
public void onActivityCreated(Bundle savedInstanceState){
getActivity().getSupportLoaderManager().initLoader(STOCK_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState){
final View rootView = inflater.inflate(R.layout.activity_main, container, false);
//set empty activity
ListView listView = rootView.findViewById(R.id.display_view);
View emptyView = rootView.findViewById(R.id.empty_view);
listView.setEmptyView(emptyView);
//create a new cursor adapter
mCursorAdapter = new PlatformCursorAdapter(getActivity(),null);
listView.setAdapter(mCursorAdapter);
//create onClick listener to inflate the editor view
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//create new intent to opend the editor
Intent intent = new Intent(getActivity(), EditorActivity.class);
//create Uri to pass the contents of the item selected to the edit view
Uri currentItem = ContentUris.withAppendedId(StoreEntry.CONTENT_URI, id);
intent.setData(currentItem);
startActivity(intent);
}
});
getLoaderManager().initLoader(STOCK_LOADER, null, this);
return rootView;
}
and my RecipeFragment
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
getActivity().getSupportLoaderManager().initLoader(RECIPE_lOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState){
final View rootView = inflater.inflate(R.layout.activity_main, container, false);
//set empty activity
ListView listView = rootView.findViewById(R.id.display_view);
View emptyView = rootView.findViewById(R.id.empty_view);
listView.setEmptyView(emptyView);
//create a new cursor adapter
mCursorAdapter = new RecipeCursorAdapter(getActivity(),null);
listView.setAdapter(mCursorAdapter);
//create onClick listener to inflate the editor view
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//create new intent to opened the editor
Intent intent = new Intent(getActivity(), EditorActivity.class);
//create Uri to pass the contents of the item selected to the edit view
Uri currentItem = ContentUris.withAppendedId(RecipeEntry.CONTENT_URI, id);
intent.setData(currentItem);
startActivity(intent);
}
});
return rootView;
}
I haven't created the last two fragments yet. Please let me know if you can find the error.
The log message is always showing the Inventory Fragment
You will have to update the position every time a page is selected using a pager listener
mPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int arg0) { }
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
#Override
public void onPageSelected(int position) {
this.position = position
}
});
I have custom DialogFragment which called from another fragment:
final CustomCalendarDialogFragment newFragment = new CustomCalendarDialogFragment("CHOOSE_WEEK");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (newFragment.isAdded()){
newFragment.getDialog().show();
} else {
newFragment.show(getFragmentManager(), "CUSTOM_CALENDAR");
}
}
});
In CustomCalendarDialogFragment when pressed "OK":
getDialog().hide();
After pressed on "OK" DialogFragment is hide, but when I unlock screen DialogFragment is displayed.
How to eliminate it?
You can track the state of showing/hiding the dialog in the tag attribute of the fragment view.
Initially set it as true (equivalent to shown) in onCreateView()
#Nullable
#org.jetbrains.annotations.Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable #org.jetbrains.annotations.Nullable ViewGroup container, #Nullable #org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.bottom_sheet, container, false);
view.setTag(true);
return view
}
And whenever you show/hide it set it to true/false:
final CustomCalendarDialogFragment newFragment = new CustomCalendarDialogFragment("CHOOSE_WEEK");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (newFragment.isAdded()){
newFragment.getDialog().show();
} else {
newFragment.show(getFragmentManager(), "CUSTOM_CALENDAR");
newFragment.requireView().setTag(true);
}
}
});
And set newFragment.requireView().setTag(false); when you call getDialog().hide();
And when the app goes to the background, check that tag on onResume() to see if you want to keep the dialog shown or hide it:
#Override
protected void onResume() {
super.onResume();
Object tag = newFragment.requireView().getTag();
if (tag instanceof Boolean){
if ((!(boolean)tag))
newFragment.getDialog().hide();
}
}
Whenever I debug the application it crashes when I click the button that pops up the dialog.
What should I do to make that dialog work?
public class Actionbar_BtnHandler extends Activity {
Context context;
public Actionbar_BtnHandler (Context context)
{
this.context=context;
}
public void btn_handler (Button btn_mic,Button btn_post)
{
btn_mic.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context,"MICROPHONE",Toast.LENGTH_LONG).show();
}
});
btn_post.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// Get the layout inflater
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog_signin, null))
// Add action buttons
.setPositiveButton("Post", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// sign in the user ...
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.create();
}
});
}
}
Thanks in advance...
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
is inaccurate... The cast seems to fail
Try :
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// Get the layout inflater
LayoutInflater inflater = Actionbar_BtnHandler.this.getLayoutInflater();
Try this write your AlertDialog code using Handler..
btn_post.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Handler handler = new Handler();
handler.post(MessagealertDisplay);
}
});
}
Runnable MessagealertDisplay = new Runnable() {
#Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// Get the layout inflater
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog_signin, null))
// Add action buttons
.setPositiveButton("Post", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// sign in the user ...
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.create();
}
};
i used
Actionbar_BtnHandler btns = new Actionbar_BtnHandle(Class.this);
btns.btn_handler(btn_post, btn_mic);
instead of
Actionbar_BtnHandler btns = new Actionbar_BtnHandler(getApplicationContext);
btns.btn_handler(btn_post, btn_mic);
and it worked