Same button (with action) on multiple layouts - java

I'm making an android app and i want to put a settings button on every layout in the app. When i press the settings button, a custom dialog pops up and i can access the app settings.
The problem i'm having is that i want to refer to 1 method in some class (doesn't matter to me which one). I'm already using the include in my XML of my layouts like this:
<include android:id="#+id/settingsButton"
layout="#layout/settingsbuttonlayout"/>
The settingsbuttonlayout.xml file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/root_vg">
<ImageButton
android:layout_width="50dp"
android:layout_height="50dp" app:srcCompat="#drawable/settingsicon"
android:id="#+id/settings_dialog"
android:cropToPadding="true"
android:adjustViewBounds="false" android:scaleType="fitCenter"
app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent"
app:layout_constraintHorizontal_bias="0.133"
app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintVertical_bias="0.123"
android:clickable="true"
android:focusable="true"
android:background="#drawable/customdialog" android:onClick= "showSettings"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
You can see that there is an onclick defined in this layout. However (for as far as i know) this means i need the same "showSettings" method in every layout class. How can i work around this so i should only write the "showSettings" method once and can refer to it?
This is the showSettings method:
public void showSettings(View v){
Dialog dialog = new Dialog(this, R.style.DialogStyle);
dialog.setContentView(R.layout.settings_dialog);
dialog.getWindow().setBackgroundDrawableResource(R.drawable.dialogbackground);
Button btnClose = dialog.findViewById(R.id.close_settings);
btnClose.setOnClickListener(view -> dialog.dismiss());
dialog.show();}
PS: I'm pretty new into making apps and GUI's. I didn't learn it yet in school and i'm just figuring out everything myself so sorry if this is some straightforward or stupid question :)

you can remove the onClick attribute from your setttings_dialog which calls the showSettings, next create a Utility.java file in which you can make your function as static
public static void showSettings(View v){
Dialog dialog = new Dialog(this, R.style.DialogStyle);
dialog.setContentView(R.layout.settings_dialog);
dialog.getWindow().setBackgroundDrawableResource(R.drawable.dialogbackground);
Button btnClose = dialog.findViewById(R.id.close_settings);
btnClose.setOnClickListener(view -> dialog.dismiss());
dialog.show();}
now in whichever class you want to call this method just write
Button settingsButton = (Button) findViewById(R.id.settingsButton);
settingsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Utility.showSettings(v);
}
});

After searching some more I found the following:
From whichever class i wanted to open the dialog i have to write this:
SettingsDialog.showSettings(this);
In my SettingsDialog class i have the following:
public class SettingsDialog {
static void showSettings(Context context) {
Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.settings_dialog);
Dialog.getWindow().setBackgroundDrawableResource(R.drawable.dialogbackground);
}
dialog.show();}
}

Related

The button of a Android project simply does not work [duplicate]

I am developing a small project of test, and I wrote the following code.
I already created in the xml file, a button with id called "registerBtn".
I erased the imports of this source code to shorten space of this source code.
In the java file, I created a variable called mRegisterBtn, in the type of Button.
Inside the method called onCreate(Bundle savedInstanceState) the mRegisterBtn receives the method called findViewById(R.id.registerBtn);
However, in the mRegisterBtn.setOnClickListener, the part of new View.OnClickListener appears in gray color, and it is not working when trying to test this code.
This image shows what I really mean. Please, perceive that the the part of new View.OnClickListener appears in gray color. It means a error. But trying to compile, this code runs, but the button simply does not work.
Can anyone know how to fix this error, please?
public class Register2 extends AppCompatActivity {
Button mRegisterBtn;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register2);
mRegisterBtn = findViewById(R.id.registerBtn);
mRegisterBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Testing", Toast.LENGTH_LONG).show();
}
});
}
}```
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#007FFF"
tools:context=".Register">
<Button
android:id="#+id/registerBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#color/white"
android:text="Register"
android:textColor="#color/black"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.499" />
</androidx.constraintlayout.widget.ConstraintLayout>
Try using the Activity itself as the Context.
If you want a log, then make one
If you want the gray to go away, use a lambda
Log.d("REGISTER", "Setting listener");
mRegisterBtn.setOnClickListener(view -> {
Log.d("REGISTER", "Clicked!");
Toast.makeText(Register2.this, "Testing", Toast.LENGTH_LONG).show();
});

How to make fixed Bottom dialog

I want to make a bottom dialog which will display a text I provide and I can hide and show it whenever I want. This dialog will be shown in all activities. For example, if the app is not connected to the server right now I will show this bottom dialog saying "No connection" and this dialog will be displayed in any activity which is on the screen. How to make this dialog, I tried to make it in XML but I needed to write its show/hide methods in every activity which is a tedious work.
Here is an image which shows the bottom dialog which I am trying to make.
Create a custom dialog box that is easy to show on all activities. A dialog box can be customized as the style in your picture.
Here is an example, requestFeature() must be called before adding content, Other settings need to be after setContentView().
public class YOUR_DIALOG extends Dialog {
private String mText;
public YOUR_DIALOG(Context context, String text) {
super(context);
requestWindowFeature(Window.FEATURE_NO_TITLE);
mText = text;
}
#Override
public void onStart() {
super.onStart();
Window dialogWindow = getWindow();
dialogWindow.getAttributes().width = android.widget.ListPopupWindow.MATCH_PARENT;
dialogWindow.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
dialogWindow.setBackgroundDrawable(new ColorDrawable(0xffff7320));
dialogWindow.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
}
// Everything else remains the same, as is the case with the normal dialog box.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_dialog_layout);
textview = findViewById(...);
textview.setText(mText);
}
}
And the layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textview"
android:textAppearance="#android:style/TextAppearance.Material.Medium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:padding="10dp"
android:drawablePadding="10dp"
android:drawableLeft="#mipmap/ic_launcher"
android:textStyle="bold"
android:textColor="#fff"/>
</LinearLayout>
In your activity
new YOUR_DIALOG(this,"Dialog").show();

How to use a ScrollView?

This is suppose to be a scroll view with all the content added from the Java code when response is received from the API.
The problem is that I can't find a way to display the information like this in a ScrollView. I tried using an ImageButton but I couldn't get the content in it then I tried using a Button but still couldn't achieve the desired effect please can someone suggest a way I could do this.
private Button makeButton(String targetName, final String i, LinearLayout.LayoutParams buttonLayoutParams) {
Button in = new Button(this);
in.setBackground(getResources().getDrawable(R.drawable.rectangle14));
in.setText(targetName);
in.setWidth(360);
in.setHeight(72);
in.setLayoutParams(buttonLayoutParams);
in.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent = new Intent(HomeActivity.this,XSavingDetailsActivity.class);
myIntent.putExtra("i" ,i);
HomeActivity.this.startActivity(myIntent);
}
});
return in;
}
You should use a RecyclerView .Each and every component within the RecyclerView is a CardView . Also you should learn about Material Design.
Apart from the above some useful links:
https://developer.android.com/guide/topics/ui/layout/cardview.html
https://www.androidhive.info/2016/01/android-working-with-recycler-view/
https://medium.com/#nileshsingh/android-cardview-101-everything-you-should-know-5bbf1c873f5a
Just make the top-level layout a ScrollView:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="1">
<!-- everything else -->
</TableLayout>

Questions regarding custom dialog

Im having trouble regarding dialogs, so Ive been re-reading the android docs several times over, and am still unsure about the following things and would really appreciate if anyone can answer my questions...
Before i ask my questions ill show my code...
CustomDialog (Straight copy from android dev. site)
public class FireMissilesDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().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_createlocation, null))
.setTitle(R.string.dialog_createlocationtitle)
// Add action buttons
.setPositiveButton(R.string.create, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
FireMissilesDialogFragment.this.getDialog().cancel();
}
});
return builder.create();
}
}`
and here is the layout for the dialog(dialog_createlocation.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:id="#+id/EditTextName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"
android:hint="#string/name"
android:maxLines="1"/>
<EditText
android:id="#+id/EditTextAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="16dp"
android:fontFamily="sans-serif"
android:hint="#string/address"
android:maxLines="2"/>
Questions:/n
In my main activity, I want to get the text from the two EditText in the dialog. Although Ive seen some SO questions about this but im so overwelmed and cant seem to understand the answers./n
2.Is it necessary for me to create this dialog in its own class?-can i just create it in my main activity(- without creating an inner class)?/n
3.Im confused with why to create a custom dialog, it has to extend a fragment-why not just an activity?/n
4.I create an instance of the above dialog in my main activity (which is not a fragment) and i got some issues doing this:
public void showNoticeDialog() {
// Create an instance of the dialog fragment and show it
DialogFragment dialog = new FireMissilesDialogFragment();
dialog.show(getSupportFragmentManager(), "NoticeDialogFragment");
}
Thanks!
In my main activity, I want to get the text from the two EditText in
the dialog. Although Ive seen some SO questions about this but im so
overwelmed and cant seem to understand the answers.
EditText editTextName = dialog.getDialog().findViewById(R.id.EditTextName);
String name = editTextName.getText().toString();
Is it necessary for me to create this dialog in its own class?-can i just create it in my main activity(- without creating an inner
class)?
Yes, you can. AlertDialog just give you already present structure for your dialog. But to make your own just use Dialog Class.
3.Im confused with why to create a custom dialog, it has to extend a fragment-why not just an activity?
Its not necessary to use only Fragment for Dialog. as per second answer.
4.I create an instance of the above dialog in my main activity (which is not a fragment) and i got some issues doing this:
Post stacktrace or error log for this.

How to create the view in android?

Can someone tell me how should i create the above view here via xml or java coding in android?
This is what i have tried so far... But the view just seems to look too plain without any pictures by the side of each string as shown in the above link? What should i do to get the sort of more professional view?
final String [] items = new String []{"Details", "Delete File"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("File Options");
builder.setItems(items, new OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
if(arg1 == 0)
{
startActivity(new Intent(getApplicationContext(), DialogBox.class));
}
else
{
deleteFile();
}
}
});
builder.create().show();
You can check this code
This to show the dialog and code for each button,as we do in onCreate.
private void showRules() {
final Dialog ruleDialog = new Dialog(this);
ruleDialog.setContentView(R.layout.ruledialog);
Button cancelbtn = (Button)ruleDialog.findViewById(R.id.cancelbtn);
//cancelbtn.setOnClickListener(this);
cancelbtn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
ruleDialog.dismiss();
}
});
ruleDialog.setCancelable(true);
ruleDialog.show();
//dialog.setTitle("How");
}
This the xml that I have use for it,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/dialogHead"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="#string/dialogHead"
android:paddingBottom="20px"
android:layout_alignParentTop="true"
/>
<Button
android:id="#+id/cancelbtn"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:background="#drawable/ic_cancel"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:paddingRight="3px"
android:paddingTop="3px"
/>
<ScrollView
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_below="#id/dialogHead"
>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/dialogBody"
/>
</ScrollView>
</RelativeLayout>
I hope this will help you.
see here: http://developer.android.com/guide/topics/ui/dialogs.html#CustomDialog you can create your own layout and define what ever you'd like. as for professionalism - thats in the eye of the beholder.
Edit:
so don't use your string array to set your text.
create a layout that has a TextView ImageView TextView. use the layout inflator to inflate the view. find the 1st textview and setText("Details") (if you didn't do it statically in the xml)
find the second textview and setText("Delete") (if you didn't do it statically in the xml)
find the image and setImageResource (if you didn't do it statically in the xml)
set the builders view to your layout.
oh and maybe add some buttons with onclick listeners to do your stuff. or use an alertdialogbuilder.

Categories

Resources