Android - Cannot resize AlertDialog - java

I am trying to resize an AlertDialog, which I have done before, but cannot remember how I did it. Below is the code Ive used, but it just inst working. Is anyone able to point out what I am doing wrong.
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder
.setMessage(R.string.checkout_journey_selector_popup_title)
.setPositiveButton(R.string.checkout_journey_selector_popup_paylater_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
CheckoutHelper.startReservationJourney(getActivity(),
collectibleItems);
}
})
.setNegativeButton(R.string.checkout_journey_selector_popup_paynow_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
CheckoutHelper.startPrepayCollectionJourney(getActivity(),
collectibleItems);
}
}).create().show();
Dialog alert = alertDialogBuilder.create();
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(alert.getWindow().getAttributes());
lp.height = 100;
lp.width = 50;
alert.getWindow().setAttributes(lp);
Thanks in advance

You should replace this
Dialog alert = alertDialogBuilder.create();
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(alert.getWindow().getAttributes());
lp.height = 100;
lp.width = 50;
alert.getWindow().setAttributes(lp);
With
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(alertDialogBuilder.getWindow().getAttributes());
lp.height = 100;
lp.width = 50;
alertDialogBuilder.getWindow().setAttributes(lp);
Or try this
alertDialog.getWindow().setLayout(600, 400); after alertDialog.show();
Try first and give me feedback

do like this
alert.getWindow().setLayout(width, height);
//then show it
alert.show();
instead of alert.getWindow().setAttributes(lp);

Related

cannot resolve method 'getwindow()' in Activity

am trying to add this this line in my Activity builder.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
but I find find this error Cannot resolve method'getwindow'
as am trying to add my code like this
NewGuestCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(TabsActivity.this);
builder.setTitle("Insert Table Name");
// Set up the input
final EditText input = new EditText(TabsActivity.this);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(input, InputMethodManager.SHOW_IMPLICIT);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_CLASS_TEXT);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final String Table_Name = input.getText().toString();
AlertDialog.Builder builder = new AlertDialog.Builder(TabsActivity.this);
builder.setTitle("Insert number of Covers");
// Set up the input
final EditText input2 = new EditText(TabsActivity.this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_CLASS_NUMBER);
builder.setView(input2);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String Cover_check = input2.getText().toString();
TablesFragment.Check_Items = ConnectionClass.Ret_dt("Select * From ChecksItems Where Check_ID = 0");
if (!TablesFragment.Check_Items.containsKey("Change_Temp")) {
if (TablesFragment.Check_Items.size() > 0) {
ArrayList<Object> Valrows = new ArrayList<Object>();
if (TablesFragment.Check_Items.get("Item_ID").size() > 0) {
for (int i = 0; i < TablesFragment.Check_Items.get("Item_ID").size(); i++) {
Valrows.add("");
}
}
TablesFragment.Check_Items.put("Change_Temp", Valrows);
}
}
if (Integer.parseInt(Cover_check) > 0) {
String st = ConnectionClass.Ret_Col("Select Max (CheckSerail) AS Ser From Checks_V where Officer = 0 AND OutLet_ID = " + ConnectionClass.OutletID + " And Rest_ID_Active = " + ConnectionClass.Rest_ID);
if (st.trim() == "")
st = "0";
int Check_Serial = Integer.parseInt(st) + 1;
long Check_ID = Long.parseLong(ConnectionClass.SelectNewIDCheck());
st = "insert into Checks .......
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
builder.show();
as I need from this method that when the alert dialog start the keyboard starts automatically that I don't need to touch the edit text to show the key board
sorry if any thing is not clear and sorry for my bad english
I hope this case could be solved
by the way activity looks
public class TabsActivity extends AppCompatActivity {
There is a similar question on StackOverflow. You need to call getWindow() on the Dialog Class.
call getWindow() by giving any views reference.ex
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

How can I pass data from a programmatically created button to another class?

I'm currently working on developing an Android app, in which I have an Activity where the user can see all of their current streaks (which were created programmatically with data accessed from Android's SQLite database).
I'm trying to then pass this data when clicked into another activity which displays an individual streak from the list of all streaks. I would need to pass all 4 pieces of information (streak name, streak category, date started, and days kept), and I'm honestly not quite sure where to start. Below is what I have so far, and while I'm not getting errors - this is currently passing either null, 0 or simply nothing to EnlargedActivity.java.
I currently have most of my code in EnlargedActivity's onResume() method, since whenever a new button is clicked, new data has to be passed in - although I'm not sure if that's the best way to do this, I'm still pretty new to Android programming. Thanks!
AllStreaks.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_streaks);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
prefs = getSharedPreferences("carter.streakly", Context.MODE_PRIVATE);
editor = prefs.edit();
db = new DatabaseHelper(this);
mTableLayout = (TableLayout) findViewById(R.id.all_streak_table);
Cursor res = db.getAllData();
if(res.getCount() ==0) {
//show message
showMessage("Error", "Nothing found");
return;
}
idList = new ArrayList<>();
streakList = new ArrayList<>();
categoryList = new ArrayList<>();
dateStartedList = new ArrayList<>();
daysKeptList = new ArrayList<>();
buttonList = new ArrayList<>();
int counter = 0;
//StringBuffer buffer = new StringBuffer();
while (res.moveToNext()){
idList.add(res.getString(0));
//buffer.append("STREAKNAME :"+ res.getString(1)+"\n");
//buffer.append("STREAKCATEGORY :"+res.getString(2)+"\n");
//buffer.append("DATESTARTED :"+res.getString(3)+"\n");;
daysKeptList.add(res.getString(4));
streakList.add(res.getString(1));
counter++;
}
LinearLayout.LayoutParams btnParams = new LinearLayout.LayoutParams(200, 200);
btnParams.setMargins(200, 30, 80, 30);
LinearLayout.LayoutParams tvParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ActionBar.LayoutParams.WRAP_CONTENT);
tvParams.setMargins(100, 0, 0, 0);
i = 0;
while (i < counter){
if(i%2==0){
mTableRow = new TableRow(this);
mTableLayout.addView(mTableRow);
}
ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
mTableRow.addView(ll);
btn = new Button(this);
btn.setText(daysKeptList.get(i));
btn.setId(i);
btn.setBackground(getResources().getDrawable(R.drawable.round_button));
btn.setLayoutParams(btnParams);
buttonList.add(btn);
ll.addView(btn);
tv = new TextView(this);
tv.setText(streakList.get(i));
tv.setId(i);
tv.setGravity(Gravity.CENTER | Gravity.BOTTOM);
tv.setTextSize(20);
tv.setLayoutParams(tvParams);
ll.addView(tv);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(AllStreaks.this, EnlargedActivity.class);
intent.putExtra("enlargeName", streakList.get(i-1));
startActivity(intent);
}
});
i++;
}
}
public void showMessage(String title, String message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
}
EnlargedActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enlarged);
prefs = getSharedPreferences("carter.streakly", Context.MODE_PRIVATE);
editor = prefs.edit();
Toast.makeText(EnlargedActivity.this, streakIconName, Toast.LENGTH_LONG).show();
}
public void onResume(){
super.onResume();
db = new DatabaseHelper(this);
res = db.getAllData();
if(res.getCount() ==0) {
//show message
showMessage("Error", "Nothing found");
return;
}
idList = new ArrayList<>();
streakList = new ArrayList<>();
categoryList = new ArrayList<>();
dateStartedList = new ArrayList<>();
daysKeptList = new ArrayList<>();
streakIcon = (TextView)findViewById(R.id.activity_enlarge_icon);
streakIcon.setGravity(Gravity.CENTER);
streakIcon.setTextSize(30);
counter = 0;
while (res.moveToNext()){
idList.add(res.getString(0));
streakList.add(res.getString(1));
categoryList.add(res.getString(2));
dateStartedList.add(res.getString(3));
daysKeptList.add(res.getString(4));
if (streakList.get(counter) == getIntent().getStringExtra("enlargeName")){
streakIconName = streakList.get(counter);
daysKept = Integer.parseInt(daysKeptList.get(counter));
streakIcon.setText(streakIconName + "\n" + daysKept);
}
counter++;
}
}
public void onPause(){
super.onPause();
counter = 0;
idList.clear();
streakList.clear();
categoryList.clear();
dateStartedList.clear();
daysKeptList.clear();
}
public void showMessage(String title, String message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
}

Can't set width of AlertDialog

I'm trying to set width of AlertDialog with the following code :
final View view = inflater.inflate(R.layout.action_bar_main, null);
view.findViewById(R.id.friends_bar).setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(MessagesPanel.this).setTitle(
"Messages").setAdapter(messagesAdapter,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Log.d("Button Clicked",
msgs_array.get(which)
.getTitle());
}
});
AlertDialog dialog = builder.create();
WindowManager.LayoutParams dialogLocation = dialog.getWindow().getAttributes();
dialogLocation.gravity = Gravity.TOP | Gravity.LEFT;
dialogLocation.x = (int) view.findViewById(R.id.friends_bar).getX();
dialogLocation.y = (int) view.findViewById(R.id.friends_bar).getY() + 40;
dialogLocation.width = 100;
dialog.getWindow().setLayout(50, 250);
dialog.show();
};
});
but it didn't work.. Note: x and y works fine.
I also tried :
dialog.getWindow().setAttributes(dialogLocation);
Thanks :)

How do I get the height of the screen in Android?

How can I get the available height of the screen in Android? I need to the height minus the status bar / menu bar or any other decorations that might be on screen and I need it to work for all devices. Also, I need to know this in the onCreate function. I know this question has been asked before but I have already tried their solutions and none of them work. Here are some of the things I have tried:
This does not take into account the status bar / menu bar:
Display display = getWindowManager().getDefaultDisplay();
screenWidth = display.getWidth();
screenHeight = display.getHeight();
Neither does this:
Point size = new Point();
getWindowManager().getDefaultDisplay().getSize(size);
screenWidth = size.x;
screenHeight = size.y;
Nor this:
Point size = new Point();
getWindowManager().getDefaultDisplay().getRealSize(size);
screenWidth = size.x;
screenHeight = size.y;
This does not work:
Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
// since SDK_INT = 1;
screenWidth = metrics.widthPixels;
screenHeight = metrics.heightPixels;
try
{
// used when 17 > SDK_INT >= 14; includes window decorations (statusbar bar/menu bar)
screenWidth = (Integer) Display.class.getMethod("getRawWidth").invoke(display);
screenHeight = (Integer) Display.class.getMethod("getRawHeight").invoke(display);
}
catch (Exception ignored)
{
// Do nothing
}
try
{
// used when SDK_INT >= 17; includes window decorations (statusbar bar/menu bar)
Point realSize = new Point();
Display.class.getMethod("getRealSize", Point.class).invoke(display, realSize);
screenWidth = realSize.x;
screenHeight = realSize.y;
}
catch (Exception ignored)
{
// Do nothing
}
I then used the following code to subtract the height of the status bar and menu bar from the screen height:
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0)
result = getResources().getDimensionPixelSize(resourceId);
screenHeight -= result;
result = 0;
if (screenHeight >= screenWidth)
resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android");
else
resourceId = getResources().getIdentifier("navigation_bar_height_landscape", "dimen", "android");
if (resourceId > 0)
result = getResources().getDimensionPixelSize(resourceId);
screenHeight -= result;
On API 17 it gives it correctly calculates the height of the status bar and menu bar in portrait but not in landscape. On API 10, it returns 0. I need it to work ideally on all devices or minimum API 10.
Have you tried doing your height calculations in onWindowFocusChanged of the Activity class? This eliminates API troubles by calculating what you really want, not messing with menu bars etc.
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
View content = getWindow().findViewById(Window.ID_ANDROID_CONTENT);
screenHeight=content.getHeight();
}
Here is how I managed to get the correct screen dimensions for all devices:
public class MainActivity extends Activity
{
static int ScreenWidth;
static int ScreenHeight;
static int ScreenWidthLandscape;
static int ScreenHeightLandscape;
private RelativeLayout layout;
private RelativeLayout.LayoutParams params;
private View top;
private View bottom;
#SuppressWarnings("deprecation")
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
layout = new RelativeLayout(this);
top = new View(this);
bottom = new View(this);
RelativeLayout.LayoutParams viewParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1);
viewParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
top.setLayoutParams(viewParams);
viewParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1);
viewParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
bottom.setLayoutParams(viewParams);
layout.addView(top);
layout.addView(bottom);
setContentView(layout);
final Intent intent = new Intent(this, myPackage.learnSpanishVerbs.Start.class);
final View view = getWindow().getDecorView().getRootView();
ViewTreeObserver vto = view.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener()
{
#Override
public void onGlobalLayout()
{
int topLoc[] = new int[2];
top.getLocationOnScreen(topLoc);
int BottomLoc[] = new int[2];
bottom.getLocationOnScreen(BottomLoc);
boolean portrait = getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE;
if (portrait)
{
ScreenWidth = top.getWidth();
ScreenHeight = BottomLoc[1] - topLoc[1];
}
else
{
ScreenWidthLandscape = top.getWidth();
ScreenHeightLandscape = BottomLoc[1] - topLoc[1];
}
if (Build.VERSION.SDK_INT < 16)
view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
else
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
startActivity(intent);
finish();
}
});
}
}
The best solution I have managed to come up with is this:
Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
screenWidth = metrics.widthPixels;
screenHeight = metrics.heightPixels;
TypedValue tv = new TypedValue();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
screenHeight -= TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0)
screenHeight -= getResources().getDimensionPixelSize(resourceId);
I have tested it on API 7 - 17. Unfortunately, on API 13 there is extra space at bottom both horizontally and vertically and on API 10, 8, and 7 there is not enough space at the bottom both horizontally and vertically. (I have not tested on obsolete APIs).

How can I unsquash the buttons within my alertDialog?

I know I could solve this with a header but I'd rather not have one. Is there anyway to access the properties of the cancel button?
My code and an image of the AlertView is below.
for(int i = 0; i < 10; i++)
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
if(view.getId() == (getResources().getIdentifier("imageButton" + (i+1), "id", "en.deco.android.livehud")))
{
//alert.setTitle("Notes");
// Sets an EditText view to get user input
final EditText input = new EditText(this);
input.setText(table.seats[i].getPlayer().getNotes());
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
for(int i = 0; i < 10; i++)
{
if(view.getId() == (getResources().getIdentifier("imageButton" + (i+1), "id", "en.deco.android.livehud")))
{
table.seats[i].getPlayer().setNotes(input.getText().toString());
}
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
return true;
}
}
I'd reckon you'd need to set your EditText to a defined width, or fill_parent/match_parent.
setMinimumWidth() does the job. The code above it is simply to generate display pixels rather than pixels.
DisplayMetrics metrics = getResources().getDisplayMetrics();
float dp = 250f;
int pixels = (int) (metrics.density * dp + 0.5f);
input.setMinimumWidth(pixels);
you can just set a view for your negative button, like this:
alert.setNegativeButton(R.id.cancelButton, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Some action to be done when clicked..
}
});
and you can create a layout with a button as a root like this:
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/cancelButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel">
</Button>
where you will set the width of the button normally to wrap_content
Edit: there is also a AlertDialog.Builder setNegativeButton (int textId, DialogInterface.OnClickListener listener)

Categories