Make AlertDialog Custom - android

I am using this code to display Alert Dialog
holder.tv1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder nointernetconnection = new AlertDialog.Builder(
temp);
nointernetconnection
.setIcon(R.drawable.ic_launcher)
.setTitle(list.get(position).getAS_name())
.setMessage(list.get(position).getDesc_art())
.setCancelable(true)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg,
int arg1) {
}
});
AlertDialog a = nointernetconnection.create();
a.show();
Message body is converted into scrollView automatically in case the text is more but Title text has not been viewed completely nor the title space is scrollable.
So, I want to expand the Title area & also want to make it scrollable & for this i don't wanna use custom Dialog, i want to only implement it by AlertDialog.

You can use the .setCustomTitle method of the AlertDialog.Builder class, to specify a custom layout file for the title element of the dialog .(As this is still using the AlertDialog class and not a custom (or subclassed) dialog, I think it's a worthy answer). Like so:
AlertDialog.Builder alert = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View view=inflater.inflate(R.layout.titlebar, null);
alert.setCustomTitle(view);
Android docs reference .setCustomTitle(View customTitleView)
Or you could just make the title font a smaller size, but depending on how much content there is, it may become pointless even having the title there, if it's too small to read.

This example is some what a typical hack... You don't need a custom View also...
private void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.ic_launcher);
final String title = "This is a Big Title. This is a Big Title. This is a Big Title. This is a Big Title. This is a Big Title. This is a Big Title. ";
builder.setTitle(title);
builder.setMessage("This is a Message. This is a Message. This is a Message. This is a Message.");
builder.setCancelable(false);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
AlertDialog alertDialog = (AlertDialog) dialog;
ViewGroup viewGroup = (ViewGroup) alertDialog.getWindow()
.getDecorView();
TextView textView = findTextViewWithTitle(viewGroup, title);
if (textView != null) {
textView.setEllipsize(null);
textView.setMaxHeight((int) (80 * alertDialog.getContext().getResources().getDisplayMetrics().density));
textView.setMovementMethod(new ScrollingMovementMethod());
}
}
});
alertDialog.show();
}
private TextView findTextViewWithTitle(ViewGroup viewGroup, String title) {
for (int i = 0, N = viewGroup.getChildCount(); i < N; i++) {
View child = viewGroup.getChildAt(i);
if (child instanceof TextView) {
TextView textView = (TextView) child;
if (textView.getText().equals(title)) {
return textView;
}
} else if (child instanceof ViewGroup) {
ViewGroup vGroup = (ViewGroup) child;
return findTextViewWithTitle(vGroup, title);
}
}
return null;
}

If you really do not want to use a custom title view, you can make the dialog title multiline:
TextView title = (TextView) dialog.findViewById(android.R.id.title);
title.setSingleLine(false);
If you would like to have a scrolling title, or use a custom title, Then you only (good) option would be to use a custom alertdialog title. It's not very hard to apply:
AlertDialog.Builder builder = new AlertDialog.Builder(context);
TextView textView = new TextView(context);
textView.setText("your very long title here");
builder.setCustomTitle(textView);

Here is my customdialogclass. It has several constructors in function of what you want to display: buttons, progress, nothing more than a title and a message... Customizing the layout you will be able to have a longer title or not. You could even insert one custom textview that adopts its font size to the space avaible for it. Hope it helps.
public class CustomDialogClass extends Dialog implements android.view.View.OnClickListener {
public Activity c;
public Dialog d;
public Button yes, no;
private int showButtons;
private String tit, msg, yesT, noT;
private boolean custom=false, all= false, progresss=false, spinner=false, indeterminateputted=false, indet=false;
private TextView title, subtit;
private ProgressBar progressBar, progressBar2;
private int max;
private int progress;
public OnPositiveDialogButtonClicked positive;
public CustomDialogClass(Activity a) {
super(a);
this.c = a;
this.custom = false;
}
public CustomDialogClass(Activity a, int botones) {
super(a);
this.c = a;
this.showButtons = botones;
this.custom = false;
}
public CustomDialogClass(Activity a, int botones, String tit, String message) {
super(a);
this.custom = true;
this.c = a;
this.showButtons = botones;
this.tit = tit;
this.msg = message;
}
public CustomDialogClass(Activity a, String tit, String message, String yes, String no) {
super(a);
this.custom = true;
this.c = a;
this.tit = tit;
this.msg = message;
this.yesT = yes;
this.noT = no;
this.all = true;
}
public CustomDialogClass(Activity a, String tit, String message, int max, int progress) {
super(a);
this.progresss = true;
this.tit = tit;
this.msg = message;
this.max = max;
this.progress = progress;
}
public CustomDialogClass(Activity a, String tit, String message, int max, int progress, boolean spinner) {
super(a);
this.tit = tit;
this.msg = message;
this.max = max;
this.progress = progress;
this.spinner = true;
}
public CustomDialogClass(Activity a, String tit, String message, boolean indet) {
super(a);
this.progresss = true;
this.indeterminateputted = true;
this.indet = indet;
this.tit = tit;
this.msg = message;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dialog_view);
yes = (Button) findViewById(R.id.btn_yes);
no = (Button) findViewById(R.id.btn_no);
title = (TextView) findViewById(R.id.txt_dia);
subtit = (TextView) findViewById(R.id.messageDialog);
progressBar = (ProgressBar) findViewById(R.id.dialogProgress);
progressBar2 = (ProgressBar) findViewById(R.id.dialogProgress2);
if(this.indeterminateputted) this.progressBar.setIndeterminate(indet);
yes.setOnClickListener(this);
no.setOnClickListener(this);
if(tit!=null && tit.length()>0) title.setText(tit);
if(msg!=null && msg.length()>0) subtit.setText(msg);
if(yesT!=null && yesT.length()>0) yes.setText(yesT);
if(noT!=null && noT.length()>0) no.setText(noT);
if(showButtons==0) {
yes.setVisibility(View.GONE);
no.setVisibility(View.GONE);
}
if(spinner) {
subtit.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
progressBar2.setVisibility(View.VISIBLE);
yes.setVisibility(View.GONE);
no.setVisibility(View.GONE);
}
if(progresss) {
subtit.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.VISIBLE);
yes.setVisibility(View.GONE);
no.setVisibility(View.GONE);
progressBar.setMax(max);
progressBar.setProgress(0);
}
if(all) {
subtit.setVisibility(View.VISIBLE);
yes.setVisibility(View.VISIBLE);
no.setVisibility(View.VISIBLE);
}
else if(custom){
subtit.setVisibility(View.VISIBLE);
yes.setVisibility(View.GONE);
no.setVisibility(View.GONE);
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_yes:
positive.onPositive(true);
break;
case R.id.btn_no:
positive.onPositive(false);
dismiss();
break;
default:
break;
}
dismiss();
}
public void setButtonListener(OnPositiveDialogButtonClicked listener) {
positive = listener;
}
public void setProgress(int progress) {
if(progressBar!=null) {
this.progress = progress;
progressBar.setProgress(progress);
}
}
public void setMessage(String msg) {
if(subtit!=null) subtit.setText(msg);
}
public void setTitle(String titleee) {
if(title!=null) title.setText(titleee);
}
public int getProgress() {
return this.progress;
}
public int getMax() {
return this.max;
}
public void setIndeterminate(boolean indet) {
this.progresss = true;
this.indeterminateputted = true;
this.indet = indet;
}
}
the interface for the buttons:
public interface OnPositiveDialogButtonClicked {
public void onPositive(boolean clickedYes);
}
the layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#color/white" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/gradientbackground"
android:orientation="horizontal" >
<TextView
android:id="#+id/txt_dia"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:layout_marginLeft="10dp"
android:textColor="#android:color/white"
android:textSize="16sp"
android:textStyle="bold"
>
</TextView>
</LinearLayout>
<TextView
android:id="#+id/messageDialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center"
android:layout_margin="10dp"
android:textColor="#color/black"
android:textSize="13sp"
android:visibility="gone"
android:textStyle="bold" >
</TextView>
<ProgressBar
style="#android:style/Widget.ProgressBar.Horizontal"
android:id="#+id/dialogProgress"
android:layout_margin="10dp"
android:visibility="gone"
android:layout_gravity="center"
android:layout_width="250dp"
android:layout_height="4dp"
/>
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:id="#+id/dialogProgress2"
android:visibility="gone"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="45dp"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="5dp"
android:background="#color/white"
android:orientation="horizontal" >
<Button
android:id="#+id/btn_yes"
android:layout_width="100dp"
android:layout_height="45dp"
android:background="#android:color/white"
android:clickable="true"
android:text="Yes"
android:textSize="13sp"
android:textColor="#5DBCD2"
android:textStyle="bold" />
<Button
android:id="#+id/btn_no"
android:layout_width="100dp"
android:layout_height="45dp"
android:layout_marginLeft="5dp"
android:background="#android:color/white"
android:clickable="true"
android:text="No"
android:textSize="13sp"
android:textColor="#5DBCD2"
android:textStyle="bold" />
</LinearLayout>

You have 2 options-
You could create a custom dialog view and show ur content. Here is an example
final Dialog dialog1 = new Dialog(CatchTheCatActivity.this);
dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog1.setContentView(R.layout.custom_alert);
Button ok = (Button) dialog1.findViewById(R.id.button1);
TextView title = (TextView) dialog1.findViewById(R.id.textview1);
TextView content = (TextView) dialog1.findViewById(R.id.textview2);
title.setText("your long title")
content.setText("your long content");
ok.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
dialog1.dismiss();
}
});
dialog1.show();
where R.layout.custom_alert is UI You want to show (in your case 2 textview with a button at the bottom). Ref
Use popupwindow. Here is an example

You can import a layout completely in a dialog, if you want u can set a title to dialog or put a text field in layout acting as title.
LayoutInflater factory = LayoutInflater.from(context);
final View textEntryView = factory.inflate(your_layout_id, null);
Builder builder = new Builder(context);
builder.setTitle(title);//Optional can be added in layout
mAlertDialog = builder.create();
mAlertDialog.setCancelable(false);
mAlertDialog.setView(textEntryView, 10, 10, 10, 10);

*You can do custom alert dialog by creating custom layout.
*create a custom XML file in re/layout folder
*you can design it in your way.
*in you activity class you have to write in on create method
i home this will be useful for you.
Dialog d = new Dialog(MainActivity.this);
d.setcontentview(R.layout.custom);
//For example you have one edit text and button than you can make it by declaring
EditText ed = (EditText)d.findViewById(R.id.ed1);
Button b = (Button)d.finviewById(R.id.b1);
Button b = (Button)d.finviewById(R.id.b1);
//you can on click listner on button like
b.setOnClickListner(new .....);
Alert alert = d.create();
d.show();

Related

Visibility of RelativeLayout change on scrolling Gridview

I am loading some elements (textview/imageview) in a gridview from a database, using an adapter and a content layout with these elements and 4 buttons. What im trying to do is to hide these 4 buttons with a relative layout when the user click on one of them. In my xml I've set the visibility of the relative layout by default to GONE. I change the visibility state to VISIBLE programmatically.
It works fine. When I click on one button, a dialog is shown, the OK button of this dialog change the relative layout visibility to VISIBLE (as shown in my code). The problem is every time I scroll the gridview, the visibility disappear.
Please what am I doing wrong ?
xml (gridview model)
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="2dp">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/layout_grid"
android:background="#drawable/title_back"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<TextView
android:layout_below="#+id/criteria_pic"
android:id="#+id/criteria_text"
android:textColor="#000"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="List of criteria"
android:textAlignment="center"
android:textSize="12dp"
android:textStyle="bold"/>
<ImageView
android:id="#+id/criteria_pic"
android:layout_width="80dp"
android:layout_height="80dp"
android:foregroundGravity="center"
android:src="#mipmap/ic_launcher"
android:layout_margin="4dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="#+id/rank_layout"
android:layout_margin="2dp"
android:gravity="center"
android:orientation="horizontal"
android:layout_below="#+id/criteria_text"
android:layout_centerHorizontal="true">
<ImageButton
android:layout_width="30dp"
android:layout_height="30dp"
android:id="#+id/btn1"
android:clickable="true"
android:background="#fff"
android:layout_marginRight="4dp"
android:foregroundGravity="center"
android:src="#drawable/rank_btn1"
android:scaleType="fitCenter"
android:layout_below="#+id/criteria_text"
android:layout_centerHorizontal="true" />
<ImageButton
android:layout_width="30dp"
android:layout_height="30dp"
android:id="#+id/btn2"
android:background="#fff"
android:layout_marginRight="4dp"
android:foregroundGravity="center"
android:src="#drawable/rank_btn2"
android:scaleType="fitCenter"
android:layout_below="#+id/criteria_text"
android:layout_centerHorizontal="true" />
<ImageButton
android:layout_width="30dp"
android:layout_height="30dp"
android:id="#+id/btn3"
android:background="#fff"
android:layout_marginRight="4dp"
android:foregroundGravity="center"
android:src="#drawable/rank_btn4"
android:scaleType="fitCenter"
android:layout_below="#+id/criteria_text"
android:layout_centerHorizontal="true" />
<ImageButton
android:layout_width="30dp"
android:layout_height="30dp"
android:id="#+id/btn4"
android:background="#fff"
android:layout_marginRight="4dp"
android:foregroundGravity="center"
android:src="#drawable/rank_btn5"
android:scaleType="fitCenter"
android:layout_below="#+id/criteria_text"
android:layout_centerHorizontal="true" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
android:background="#android:color/holo_green_light"
android:focusable="true"
android:focusableInTouchMode="true"
android:id="#+id/check_view"
android:layout_alignBottom="#+id/rank_layout"
android:layout_alignTop="#+id/rank_layout">
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:foregroundGravity="top|right"
app:srcCompat="#drawable/check_ok"
android:id="#+id/check_image"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
</RelativeLayout>
Adapter
public class GridviewAdapter extends BaseAdapter {
Context c;
RelativeLayout RL;
ArrayList<criteria> Critere;
LayoutInflater inflater;
boolean clicked1=false;
boolean clicked2=false;
boolean clicked3=false;
boolean clicked4=false;
private int count = 0;
public GridviewAdapter(Context c, ArrayList<criteria> critere) {
this.c = c;
Critere = critere;
inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return Critere.size();
}
#Override
public Object getItem(int position) {
return Critere.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v;
LayoutInflater inflater = (LayoutInflater) c.getSystemService( c.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.gridview_model, parent,false);
TextView nameTxt = v.findViewById(R.id.criteria_text);
ImageView image = v.findViewById(R.id.criteria_pic);
final RelativeLayout checked = v.findViewById(R.id.check_view);
final LinearLayout ranked = v.findViewById(R.id.rank_layout);
final String name = Critere.get(position).getName();
criteria cr = Critere.get(position);
nameTxt.setText(cr.getName());
PicassoClient.downloadImage(c, cr.getImageurl(),image);
final ImageButton btn1 = v.findViewById(R.id.btn1);
final ImageButton btn2 = v.findViewById(R.id.btn2);
final ImageButton btn3 = v.findViewById(R.id.btn3);
final ImageButton btn4 = v.findViewById(R.id.btn4);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
clicked1=true;
// inflate alert dialog xml
LayoutInflater li = LayoutInflater.from(c);
View dialogView = li.inflate(R.layout.custom_dialog_rank, null);
AlertDialog.Builder dialog = new AlertDialog.Builder(c);
dialog.setView(dialogView);
dialog.setIcon(R.drawable.btn_press_rank1);
dialog.setCancelable(false);
dialog.setTitle(R.string.crit1);
dialog.setMessage("The " + name + " was very unsatisfiying");
final EditText userInput = (EditText) dialogView
.findViewById(R.id.comment_field);
dialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
checked.setVisibility(View.VISIBLE);
ranked.setVisibility(View.INVISIBLE);
}
})
.setNegativeButton(R.string.annuler, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
checked.setVisibility(View.GONE);
ranked.setVisibility(View.VISIBLE);
}
});
final AlertDialog alert = dialog.create();
alert.show();
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clicked2=true;
// inflate alert dialog xml
LayoutInflater li = LayoutInflater.from(c);
View dialogView = li.inflate(R.layout.custom_dialog_rank, null);
AlertDialog.Builder dialog = new AlertDialog.Builder(c);
dialog.setIcon(R.drawable.btn_press_rank2);
dialog.setView(dialogView);
dialog.setCancelable(false);
dialog.setTitle(R.string.crit2);
dialog.setMessage("The " + name + " was unsatisfiying");
final EditText userInput = (EditText) dialogView
.findViewById(R.id.comment_field);
dialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
checked.setVisibility(View.VISIBLE);
ranked.setVisibility(View.INVISIBLE);
}
})
.setNegativeButton(R.string.annuler, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// alert.cancel();
checked.setVisibility(View.INVISIBLE);
ranked.setVisibility(View.VISIBLE);
}
});
final AlertDialog alert = dialog.create();
alert.show();
}
});
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clicked3=true;
// inflate alert dialog xml
LayoutInflater li = LayoutInflater.from(c);
View dialogView = li.inflate(R.layout.custom_dialog_rank, null);
AlertDialog.Builder dialog = new AlertDialog.Builder(c);
dialog.setIcon(R.drawable.btn_press_rank4);
dialog.setView(dialogView);
dialog.setCancelable(false);
dialog.setTitle(R.string.crit3);
dialog.setMessage("The " + name + " was satisfiying");
final EditText userInput = (EditText) dialogView
.findViewById(R.id.comment_field);
dialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
checked.setVisibility(View.VISIBLE);
ranked.setVisibility(View.INVISIBLE);
}
})
.setNegativeButton(R.string.annuler, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// alert.cancel();
checked.setVisibility(View.INVISIBLE);
ranked.setVisibility(View.VISIBLE);
}
});
final AlertDialog alert = dialog.create();
alert.show();
}
});
btn4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clicked4=true;
// inflate alert dialog xml
LayoutInflater li = LayoutInflater.from(c);
View dialogView = li.inflate(R.layout.custom_dialog_rank, null);
AlertDialog.Builder dialog = new AlertDialog.Builder(c);
dialog.setIcon(R.drawable.btn_press_rank5);
dialog.setView(dialogView);
dialog.setCancelable(false);
dialog.setTitle(R.string.crit4);
dialog.setMessage("The " + name + " was very satisfiying");
final EditText userInput = (EditText) dialogView
.findViewById(R.id.comment_field);
dialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
checked.setVisibility(View.VISIBLE);
ranked.setVisibility(View.INVISIBLE);
}
})
.setNegativeButton(R.string.annuler, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// alert.cancel();
checked.setVisibility(View.INVISIBLE);
ranked.setVisibility(View.VISIBLE);
}
});
final AlertDialog alert = dialog.create();
alert.show();
}
});
return v;
}}
Main Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_criteria);
new CriteriaActivity.FetchCountTask().execute();
final GridView gv = (GridView) findViewById(R.id.gv);
toolbar = (Toolbar) findViewById(R.id.toolbar3);
setSupportActionBar(toolbar);
// get the references of buttons
btnSelectDate=(Button)findViewById(R.id.buttonSelectDate);
btnSelectTime=(Button)findViewById(R.id.buttonSelectTime);
// Set ClickListener on btnSelectDate
btnSelectDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Show the DatePickerDialog
showDialog(DATE_DIALOG_ID);
}
});
// Set ClickListener on btnSelectTime
btnSelectTime.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// startFeedTime();
// Show the TimePickerDialog
showDialog(TIME_DIALOG_ID);
}
});
new Downloader_review(CriteriaActivity.this, urlAddress, gv).execute();
}
// Register DatePickerDialog listener
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
// the callback received when the user "sets" the Date in the DatePickerDialog
public void onDateSet(DatePicker view, int yearSelected,
int monthOfYear, int dayOfMonth) {
year = yearSelected;
month = monthOfYear + 1;
day = dayOfMonth;
// Set the Selected Date in Select date Button
btnSelectDate.setText("Date selected : "+day+"/"+month+"/"+year);
}
};
// Register TimePickerDialog listener
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
// the callback received when the user "sets" the TimePickerDialog in the dialog
public void onTimeSet(TimePicker view, int hourOfDay, int min) {
hour = hourOfDay;
minute = min;
// Set the Selected Date in Select date Button
btnSelectTime.setText("Time selected : "+hour+":"+minute);
}
};
// Method automatically gets Called when you call showDialog() method
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
// create a new DatePickerDialog with values you want to show
date = true;
DatePickerDialog dialog = new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
dialog.getDatePicker().setMaxDate(System.currentTimeMillis());
return dialog;
// return new DatePickerDialog(this,
// mDateSetListener,
// mYear, mMonth, mDay);
// create a new TimePickerDialog with values you want to show
case TIME_DIALOG_ID:
time = true;
return new TimePickerDialog(this,
mTimeSetListener, mHour, mMinute, false);
}
return null;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
// Get the notifications MenuItem and
// its LayerDrawable (layer-list)
MenuItem item = menu.findItem(R.id.action_notifications);
LayerDrawable icon = (LayerDrawable) item.getIcon();
// BitmapDrawable iconBitmap = (BitmapDrawable) item.getIcon();
// LayerDrawable icon = new LayerDrawable(new Drawable [] { iconBitmap });
// Update LayerDrawable's BadgeDrawable
Utils.setBadgeCount(this, icon, mNotificationsCount);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_notifications) {
// TODO: display unread notifications.
return true;
}
return super.onOptionsItemSelected(item);
}
/*
Updates the count of notifications in the ActionBar.
*/
private void updateNotificationsBadge(int count) {
mNotificationsCount = count;
// force the ActionBar to relayout its MenuItems.
// onCreateOptionsMenu(Menu) will be called again.
invalidateOptionsMenu();
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
/*
Sample AsyncTask to fetch the notifications count
*/
class FetchCountTask extends AsyncTask<Void, Void, Integer> {
#Override
protected Integer doInBackground(Void... params) {
// example count. This is where you'd
// query your data store for the actual count.
return 5;
}
#Override
public void onPostExecute(Integer count) {
updateNotificationsBadge(count);
}
}
Try RecyclerView instead of GridView. You can get same grid effect by using StaggeredGridLayoutManager . Also you will have more control on each item

How do I replace my popupmenu code with ListPopupWindow?

Currently , I am programatically creating a popupmenu which displays a list of floors and a title. However, changing the background color of just the title and adding a close button to title is turning out to be a nightmare.
I want to replace this popupmenu with a list popup window so I can add an XML file with background attribute for the title with a black color as the background and a close button on the right and white background for items in the menu. Is there a way I can achieve this with list popup window? Here's my code for that:
private void floorMenu(ImageView btnFloorMenu){
MapData data = new MapDao(MyPlugin.mapId);
final List<Floor> flList = dao.getFloors();
// set popupMenu
final PopupMenu floorsPm = new PopupMenu(MapViewActivity.this,btnFloorMenu);
MenuItem titleItem = floorsPm.getMenu().add(Menu.NONE, Menu.NONE, Menu.NONE, "Floors");
int i = 1;
for(Floor fl : flList)
{
floorsPm.getMenu().add(Menu.NONE, i,i, fl.getName());
if(i>3)
break;
i++;
}
// add popup listener
floorsPm.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
// onClick
#Override
public boolean onMenuItemClick(MenuItem item){
// get floorname
int flOrder = item.getOrder();
if(flOrder == Menu.NONE )
return true;
flOrder--;
final String floorId = flList.get(flOrder).getMapId();
// set camera to floor
runOnUiThread(new Runnable() {
#Override
public void run() {
floorsPm.dismiss();
mapFragment.getMapManager().setCameraLayer(floorId, false);
Log.d(TAG, "post cameraLayer set");
changedSteps = true;
pauseNav();
}
});
return true;
}
});
floorsPm.show();
}
Here is my example to create show a ListPopupWindow
First, create layout item_list_popup_window for each item of ListPopupWindow
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#e4e4e4"
android:paddingTop="1dp"
android:orientation="horizontal">
<TextView
android:id="#+id/text_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1" />
<Button
android:id="#+id/button_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete" />
</LinearLayout>
Second, create an Adapter for your ListPopupWindow like
public class ListPopupWindowAdapter extends BaseAdapter{
private Activity mActivity;
private List<String> mDataSource = new ArrayList<>();
private LayoutInflater layoutInflater;
private OnClickDeleteButtonListener clickDeleteButtonListener;
ListPopupWindowAdapter(Activity activity, List<String> dataSource, #NonNull OnClickDeleteButtonListener clickDeleteButtonListener){
this.mActivity = activity;
this.mDataSource = dataSource;
layoutInflater = mActivity.getLayoutInflater();
this.clickDeleteButtonListener = clickDeleteButtonListener;
}
#Override
public int getCount() {
return mDataSource.size();
}
#Override
public String getItem(int position) {
return mDataSource.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.item_list_popup_window, null);
holder.tvTitle = (TextView) convertView.findViewById(R.id.text_title);
holder.btnDelete = (Button) convertView.findViewById(R.id.button_delete);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
// bind data
holder.tvTitle.setText(getItem(position));
holder.btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickDeleteButtonListener.onClickDeleteButton(position);
}
});
return convertView;
}
public class ViewHolder{
private TextView tvTitle;
private Button btnDelete;
}
// interface to return callback to activity
public interface OnClickDeleteButtonListener{
void onClickDeleteButton(int position);
}
}
Third, You create a function for create and show ListPopupWindow
private void showListPopupWindow(View anchorView) {
final ListPopupWindow listPopupWindow = new ListPopupWindow(this);
listPopupWindow.setWidth(600);
List<String> sampleData = new ArrayList<>();
sampleData.add("A");
sampleData.add("B");
sampleData.add("CCCCCCCCCCCCCC");
sampleData.add("D");
sampleData.add("EEEEEEEEE");
listPopupWindow.setAnchorView(anchorView);
ListPopupWindowAdapter listPopupWindowAdapter = new ListPopupWindowAdapter(this, sampleData, new ListPopupWindowAdapter.OnClickDeleteButtonListener() {
#Override
public void onClickDeleteButton(int position) {
Toast.makeText(MainActivity.this, "Click delete " + position, Toast.LENGTH_SHORT).show();
listPopupWindow.dismiss();
}
});
listPopupWindow.setAdapter(listPopupWindowAdapter);
listPopupWindow.show();
}
Finally, you can show the ListPopupWindow by
showListPopupWindow(v);
for example, if you want to show it when click button
anyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showListPopupWindow(v);
}
});
Full Demo is here
Please Try this code, Maybe you wont like this
private void floorMenu(ImageView btnFloorMenu){
final Dialog customDialog = new Dialog(this);
customDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
customDialog.setContentView(R.layout.item_dialog_coustom_design);
TextView clickItem = (TextView)customDialog.findViewById(R.id.item_click);
TextView clickItem1 = (TextView)customDialog.findViewById(R.id.item_click1);
TextView clickItem2 = (TextView)customDialog.findViewById(R.id.item_click2);
Button btnClose = (Button)customDialog.findViewById(R.id.btn_close);
clickItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
// wright your Button Action
}
});
clickItem1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
// wright your Button Action
}
});
clickItem2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
// wright your Button Action
}
});
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
}
});
customDialog.show();
}
Create Linearlayout layout_width="280dp" layout_height="wrap_content"
android:orientation="vertical" file name item_dialog_coustom_design.xml then put this code
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Your Title"
android:background="#000"
android:textColor="#fff"
android:padding="12dp"
android:textSize="20sp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="1dp"
android:background="#fff"
android:padding="10dp"
android:text="Your Item"
android:id="#+id/item_click"
android:textSize="16sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="1dp"
android:background="#fff"
android:padding="10dp"
android:text="Your Item"
android:id="#+id/item_click1"
android:textSize="16sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="1dp"
android:background="#fff"
android:padding="10dp"
android:text="Your Item"
android:id="#+id/item_click2"
android:textSize="16sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp"
android:background="#fff"
android:gravity="right">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_close"
android:text="Close"/>
</LinearLayout>

AlertDialog with ImageView and TextView

I want to make an AlertDialog with ImageView and TextView.
I wrote this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<ImageView
android:id="#+id/imgCustomToast"
android:layout_width="170dp"
android:layout_height="220dp"
android:background="#drawable/ycp"
android:gravity="center_horizontal"
android:layout_gravity="center"
android:layout_marginRight="10dp" />
<TextView
android:id="#+id/txtCustomToast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="C#"
android:gravity="center_horizontal"
android:layout_gravity="center"
android:textSize="20sp"/>
</LinearLayout>
MainActivity:
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
Button button = FindViewById<Button>(Resource.Id.MyButton);
button.Click += delegate
{
AlertDialog.Builder alertadd = new AlertDialog.Builder(this);
LayoutInflater factory = LayoutInflater.From(this);
View view = factory.Inflate(Resource.Layout.sample, null);
alertadd.SetView(view);
alertadd.SetPositiveButton("To Close", (senderAlert, args) =>
{
Toast.MakeText(this, "Closed", ToastLength.Short).Show();
});
alertadd.Show();
};
}
}
I want to change size, font and text of the textview with in MainActivity:
TextView textView = FindViewById<TextView>(Resource.Id.txtCustomToast);
string str = "sample text";
textView.Text = str;
Typeface typeP = Typeface.CreateFromAsset(this.Assets, "fonts/BLOTUS.TTF");
textView.SetTypeface(typeP, TypefaceStyle.Normal);
textView.SetTextSize(Android.Util.ComplexUnitType.Sp, 18);
But I see this error:
System.NullReferenceException
How can I change size, font and text of the textview programmatically?
You are doing wrong way you can access the TextView below way,
Change this line
TextView textView = FindViewById<TextView>(Resource.Id.txtCustomToast);
to this
TextView textView = view.FindViewById<TextView>(Resource.Id.txtCustomToast);
You need to find your view using instance of Alert Dialog like below.
TextView textView = view.FindViewById<TextView>(Resource.Id.txtCustomToast);
View view = factory.Inflate(Resource.Layout.sample, null);
TextView textView = view.findViewById<TextView>(Resource.Id.txtCustomToast);
string str = "sample text";
textView.setText(str);
Call this method,That display an AlertDialog with ImageView and TextView
private void showDialog(Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Title");
builder.setMessage("Message");
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
ImageView imageView = new ImageView(context);
TextView textView = new TextView(context);
linearLayout.addView(imageView);
linearLayout.addView(textView);
builder.setCancelable(false);
builder.setView(linearLayout);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//ok
}
});
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// negative button logic
}
});
AlertDialog dialog = builder.create();
// display dialog
dialog.show();
}

In Custom action bar if we hide any icon that space need to used by other icons or text view in action bar

In my app I am using custom action bar. In that action bar I have 4 icons and 1 textview. For action bar I am using linear layout.
I have 4 activities in my app, each activity will have different action bar. If I open 1st activity one icon will set visibility gone. Every one of these activities will have different icons.
Question: My requirement is when icon is disable that space need to used by textview. I try everything but always space will end of the action bar I don't want that space.
Here is my code.
MainActivity.class:-
public class MainActivity extends AppCompatActivity {
ImageView Image1,Image2,Image3,Image4;
TextView title;
Button btn1,btn2,btn3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
/*Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
*/
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setCustomView(R.layout.custom_actionbar);
View view = getSupportActionBar().getCustomView();
Image1=(ImageView)findViewById(R.id.cst_ok);
Image2=(ImageView)findViewById(R.id.cst_del);
Image3=(ImageView)findViewById(R.id.cst_edt);
Image4=(ImageView)findViewById(R.id.cst_srh);
title=(TextView)findViewById(R.id.cst_txt);
Image1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showdailog();
}
});
btn1=(Button)findViewById(R.id.btn1);
btn2=(Button)findViewById(R.id.btn2);
btn3=(Button)findViewById(R.id.btn3);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1=new Intent(MainActivity.this,first_activity.class);
startActivity(intent1);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent2=new Intent(MainActivity.this,second_activity.class);
startActivity(intent2);
}
});
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent3=new Intent(MainActivity.this,third_activity.class);
startActivity(intent3);
}
});
private void showdailog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.custom_dialog, null);
dialogBuilder.setView(dialogView);
final EditText edt = (EditText) dialogView.findViewById(R.id.edit1);
dialogBuilder.setTitle("Custom dialog");
dialogBuilder.setMessage("Enter text below");
dialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// et1.setText(edt.getText());
title.setText(edt.getText());
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//pass
}
});
AlertDialog b = dialogBuilder.create();
b.show();
}
}
FirstActivity.class:-
public class first_activity extends AppCompatActivity {
ImageView Image1,Image2,Image3,Image4;
TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment1);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setCustomView(R.layout.custom_actionbar);
View view = getSupportActionBar().getCustomView();
Image1=(ImageView)view.findViewById(R.id.cst_ok);
Image2=(ImageView)view.findViewById(R.id.cst_del);
Image3=(ImageView)view.findViewById(R.id.cst_edt);
Image4=(ImageView)view.findViewById(R.id.cst_srh);
title=(TextView)view.findViewById(R.id.cst_txt);
Image1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showdailog();
}
});
Image3.setVisibility(View.GONE);
}
private void showdailog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.custom_dialog, null);
dialogBuilder.setView(dialogView);
final EditText edt = (EditText) dialogView.findViewById(R.id.edit1);
dialogBuilder.setTitle("Custom dialog");
dialogBuilder.setMessage("Enter text below");
dialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// et1.setText(edt.getText());
title.setText(edt.getText());
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//pass
}
});
AlertDialog b = dialogBuilder.create();
b.show();
}
}
SecondActivity.class:-
public class second_activity extends AppCompatActivity {
ImageView Image1,Image2,Image3,Image4;
TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment3);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setCustomView(R.layout.custom_actionbar);
View view = getSupportActionBar().getCustomView();
Image1=(ImageView)view.findViewById(R.id.cst_ok);
Image2=(ImageView)view.findViewById(R.id.cst_del);
Image3=(ImageView)view.findViewById(R.id.cst_edt);
Image4=(ImageView)view.findViewById(R.id.cst_srh);
title=(TextView)view.findViewById(R.id.cst_txt);
Image1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showdailog();
}
});
Image4.setVisibility(View.GONE);
}
private void showdailog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.custom_dialog, null);
dialogBuilder.setView(dialogView);
final EditText edt = (EditText) dialogView.findViewById(R.id.edit1);
dialogBuilder.setTitle("Custom dialog");
dialogBuilder.setMessage("Enter text below");
dialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// et1.setText(edt.getText());
title.setText(edt.getText());
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//pass
}
});
AlertDialog b = dialogBuilder.create();
b.show();
}
}
ThirdActivity.class:-
public class third_activity extends AppCompatActivity {
ImageView Image1,Image2,Image3,Image4;
TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment2);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setCustomView(R.layout.custom_actionbar);
View view = getSupportActionBar().getCustomView();
Image1=(ImageView)view.findViewById(R.id.cst_ok);
Image2=(ImageView)view.findViewById(R.id.cst_del);
Image3=(ImageView)view.findViewById(R.id.cst_edt);
Image4=(ImageView)view.findViewById(R.id.cst_srh);
title=(TextView)view.findViewById(R.id.cst_txt);
Image1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showdailog();
}
});
Image2.setVisibility(View.GONE);
}
private void showdailog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.custom_dialog, null);
dialogBuilder.setView(dialogView);
final EditText edt = (EditText) dialogView.findViewById(R.id.edit1);
dialogBuilder.setTitle("Custom dialog");
dialogBuilder.setMessage("Enter text below");
dialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// et1.setText(edt.getText());
title.setText(edt.getText());
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//pass
}
});
AlertDialog b = dialogBuilder.create();
b.show();
}
}
Custom_Actionbar_layout:-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="40dp"
android:weightSum="5">
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/ok"
android:id="#+id/cst_ok"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center"
android:gravity="center"
android:text="Custom ActionBar"
android:id="#+id/cst_txt"
android:singleLine="false"
android:maxLines="2"/>
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/delete1"
android:id="#+id/cst_del"/>
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/edit"
android:id="#+id/cst_edt"/>
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/search"
android:id="#+id/cst_srh"/>
</LinearLayout>
And my theme is <style name="AppTheme" parent="Theme.AppCompat.Light">
And text view is dynamically changed text it is given by user. If any one need more details I will update.
You're setting the value of the android:weightSum attribute of your LinearLayout to 5.
When you're removing a View from that layout (setting its visibility to View.GONE), the weightSum of your LinearLayout is still 5, but the actual sum of your Views is only 4, hence the empty space.
Removing the android:weightSum attribute from your LinearLayout should solve the problem:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="40dp">
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/ok"
android:id="#+id/cst_ok"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center"
android:gravity="center"
android:text="Custom ActionBar"
android:id="#+id/cst_txt"
android:singleLine="false"
android:maxLines="2"/>
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/delete1"
android:id="#+id/cst_del"/>
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/edit"
android:id="#+id/cst_edt"/>
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/search"
android:id="#+id/cst_srh"/>
</LinearLayout>

set view visibility == GONE from another view in android

i am new to android development, and from java background , am developing an android app where i have to display of invites which user have got, so the layout will be like below
here invite response view (yes, no , may) will be shown on click of each invite view, but i want the response view to get closed or visibility = Gone when user clicks on another view. currently response views are shown once clicked on invite view.
so to solve this issue, i have added id (inviteId) to each response view as below
final LinearLayout second = (LinearLayout) inviteView.findViewById(R.id.hidden);
second.setId((int) currentInviteId);
now i am trying to get firstly opened response view id when user clicks on next invite view and trying to set the first response view to "GONE"
public class InvitationFragment extends Fragment {
private List<String> eventName = new ArrayList<>();
private List<Long> eventId = new ArrayList<>();
private List<String> eventPlace = new ArrayList<>();
private List<EventMO> eventMOs = new ArrayList<>();
private List<UserMO> userMO = new ArrayList<>();
private Context context;
private UserOccasions userOccasions;
private UserDelegate userDelegate = new UserDelegate();
private EventDelegates eventDelegates = new EventDelegates();
private Gson gson = new Gson();
private ProgressDialog prgDialog;
private EventMO eventMO;
// private long compareEventId;
private SharedPreferences prefs;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final View view = inflater.inflate(R.layout.invitation_tab, container, false);
context = getActivity().getApplicationContext();
prgDialog = new ProgressDialog(getActivity());
eventId.clear();
eventName.clear();
eventPlace.clear();
// Set Progress Dialog Text
prgDialog.setMessage("Please wait...");
// Set Cancelable as False
prgDialog.setCancelable(false);
prgDialog.show();
DatabaseHelper dbHelper = new DatabaseHelper(context);
final UserMO userMO = dbHelper.getRingeeUserData(1);
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... arg0) {
return eventDelegates.getAllEventForUser(userMO, context);
}
#Override
protected void onPostExecute(String eventlists) {
if (eventlists != "null") {
eventMOs = gson.fromJson(eventlists, new TypeToken<List<EventMO>>() {
}.getType());
Toast.makeText(context, "total items of eventMo" + eventMOs.size(), Toast.LENGTH_LONG).show();
for (EventMO eventMO : eventMOs) {
eventName.add(eventMO.getText());
eventId.add(eventMO.getEventId());
eventPlace.add(eventMO.getPlace());
}
DatabaseHelper dbHelper = new DatabaseHelper(context);
//long totalInsertion = dbHelper.insertUserRelationTable(userMOs);
prgDialog.dismiss();
//Toast.makeText(context, "total userMos size " + userMOs.size() + "total db insertion size " + totalInsertion, Toast.LENGTH_LONG).show();
ListView occasionView = (ListView) view.findViewById(R.id.invitation_list_view);
userOccasions = new UserOccasions();
occasionView.setAdapter(userOccasions);
occasionView.setItemsCanFocus(false);
occasionView.setTextFilterEnabled(true);
occasionView.setOnItemClickListener(occasionView.getOnItemClickListener());
}
}
}.execute(null, null, null);
return view;
}
private class UserOccasions extends BaseAdapter {
LayoutInflater mInflater;
TextView eventNameTxtV, eventPlaceTxtV;
UserOccasions() {
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return eventMOs.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return 0;
}
// show list values name and mobile number in contact page
#Override
public View getView(final int position,View inviteView, ViewGroup parent) {
if (inviteView == null) {
inviteView = mInflater.inflate(R.layout.invitation, null);
}
EventMO eventMO = eventMOs.get(position);
final long currentEventId = eventMO.getEventId();
eventNameTxtV = (TextView) inviteView.findViewById(R.id.invitation_title);
eventPlaceTxtV = (TextView) inviteView.findViewById(R.id.invitation_place);
eventNameTxtV.setText(eventMO.getText());
eventPlaceTxtV.setText(eventMO.getPlace());
inviteView.setTag(position);
View v = inviteView.findViewById(R.id.invitation_single);
final LinearLayout first = (LinearLayout) inviteView.findViewById(R.id.invitation_single);
Button yesBtn = (Button) inviteView.findViewById(R.id.yesbutton);
Button noBtn = (Button) inviteView.findViewById(R.id.nobutton);
Button mayBeBtn = (Button) inviteView.findViewById(R.id.buttonmaybe);
final LinearLayout second = (LinearLayout) inviteView.findViewById(R.id.hidden);
second.setId((int) currentEventId);
// to store current event id into shared preference, to compare event ids and close child layout if ids are differents
prefs = context.getSharedPreferences(InvitationFragment.class.getSimpleName(), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putLong("compareEventId", currentEventId);
editor.commit();
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
second.setVisibility(View.GONE);
final String response = "yes";
final EventMO event = new EventMO();
event.setIs_Attend(response);
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... arg0) {
return eventDelegates.updateEvent(event, context);
}
}.execute(null, null, null);
}
});
noBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
second.setVisibility(View.GONE);
final String response = "no";
final EventMO event = new EventMO();
event.setIs_Attend(response);
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... arg0) {
return eventDelegates.updateEvent(event, context);
}
}.execute(null, null, null);
}
});
mayBeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
second.setVisibility(View.GONE);
final String response = "maybe";
final EventMO event = new EventMO();
event.setIs_Attend(response);
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... arg0) {
return eventDelegates.addEvent(event, context);
}
}.execute(null, null, null);
}
});
first.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View invitationView) {
final long compareEventId = prefs.getLong("compareEventId", 0);
final long currentEventId = second.getId();
if(compareEventId != 0 && compareEventId != currentEventId){
LayoutInflater inflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
View inflatedView = inflater.inflate(R.layout.invitation, null);
final View inviteResponseView = (View) inflatedView.findViewById((int) compareEventId);
inviteResponseView.setVisibility(View.GONE);
}
switch (invitationView.getId()) {
case R.id.invitation_single:
second.setVisibility(View.VISIBLE);
break;
}
}
});
return inviteView;
}
}
}
but inviteResponseView is always returning null. need direction to solve this functionality. Thanks for your valuable response.
EDIT :-
my layout xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/invitation_single"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="?android:dividerVertical"
android:dividerPadding="5dp"
android:showDividers="middle"
tools:context=".MainActivity">
<ImageButton
android:id="#+id/image"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/ic_action_event" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:clickable="false"
android:focusable="true"
android:orientation="vertical">
<TextView
android:id="#+id/invitation_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingRight="0dp"
android:paddingTop="3dp"
android:textColor="#color/black"
android:textSize="18sp" />
<TextView
android:id="#+id/invitation_place"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingRight="0dp"
android:textColor="#color/black"
android:textSize="15sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/hidden"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_marginLeft="-270dp"
android:layout_marginTop="60dp"
android:layout_weight="1"
android:clickable="true"
android:focusable="true"
android:orientation="horizontal"
android:paddingTop="1dp"
android:visibility="gone"
android:weightSum="3">
<Button
android:id="#+id/yesbutton"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="7dp"
android:layout_weight="1"
android:background="#color/blue"
android:text="Yes"
android:textColor="#color/black"></Button>
<Button
android:id="#+id/nobutton"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="25dp"
android:layout_weight="1"
android:background="#color/blue"
android:text="No"
android:textColor="#color/black"></Button>
<Button
android:id="#+id/buttonmaybe"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="25dp"
android:layout_marginRight="10dp"
android:layout_weight="1"
android:background="#color/blue"
android:text="Maybe"
android:textColor="#color/black"></Button>
</LinearLayout>
</LinearLayout>
Why don't you use an onFocusChangeListener ?
First of all:
Set in your invitationView layout .xml file (the one which contains the buttons yes, no, maybe) like this:
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"
Note: You must also do this to your parent layout (the layout of the Activity) so when the user touch outside the invitationView, the parent layout will catch the focus.
Then, what you have to do is to set the invitationView.setOnFocusChangeListener to your invitationView, inside your Activity or inside your listAdapater (or recyclerViewAdapter) if you are using it to the invitationView (what I highly recommend).
Like this:
invitationView.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus)
{
inviteResponseView.setVisibility(view.GONE)
}else
inviteResponseView.setVisibility(view.VISIBLE)
}
});
Recommendation:
Recommend you to use a recyclerView instead of fragments to make this job, it pretty easy to use and memory usage efficient. Now it supports most of the devices with the design support library that already has a bunch of tutorials, like the linked ones.
I recommend you use some third-party dependency in your project.
As a matter of fact, nhaarman's ListViewAnimations can do that very well. Download the demo in Play Store and check it.
There's a fully customizable ListView that can expand on user click and show more items. Plus, it supports very cool animations. I've used it in one of my projects and it's very good. You can even set the maximum number of views that can be expanded at once.
In your BaseAdapter add
private boolean showActionView = false;
private int showActionViewFor;
public void showActionView(boolean show, int position) {
showActionView = show;
showActionViewFor = position;
notifyDataSetChanged();
}
Then in your BaseAdapter's getView() add
if(showActionView && position == showActionViewFor) {
second.setVisibility(View.VISIBLE);
} else {
second.setVisibility(View.INVISIBLE);
//Don't use View.GONE
}
Then in your Fragment's onCreateView(), add
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mAdapter.showActionView(true, position);
}
});
Bam! It should work as you need. Whenever you need to hide all action views just call
mAdapter.showActionView(false, 0);
UPDATE:
You need to remove your
first.setOnClickListener(new View.OnClickListener() {}
from your Adapter.
EXTRA: To improve your ListView performance, you should consider implementing the View Holder pattern.

Categories

Resources