View.OnClickListener in a custom DialogFragment - android

I am trying to implement a custom DialogFragment, following this tutorial. My problem is that I fail to handle my custom's view's button.setOnClickListener event. The strangest part is that I have no problem in geting the .getText() of my button, I just can't find a way to handle the click event. Bellow is my code:
SettingsDialogFragment.java
public class SettingsDialogFragment extends DialogFragment
{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
final View view = inflater.inflate(R.layout.dialog_settings, null);
final Button colorButton =(Button) view.findViewById(R.id.colorButton_dialogSettings);
String s = colorButton.getText().toString();
System.out.println("its working "+s);
//NOT working
colorButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
System.out.println("OnClick");
}
});
// 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_settings, null))
// Add action buttons
.setPositiveButton(R.string.ok, 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) {
SettingsDialogFragment.this.getDialog().cancel();
}
});
return builder.create();
}
`
My custom view code (dialog_settings.xml)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="200dp"
android:layout_height="wrap_content">
<EditText
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"
android:scaleType="center"
android:background="#00CCCC"
android:contentDescription="#string/app_name"
android:text="#string/dialog_settings_title"
android:id="#+id/editText"/>
<Button
android:id="#+id/colorButton_dialogSettings"
android:inputType="textEmailAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/color_picker_title"
android:layout_below="#+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stroke"
android:layout_marginLeft="55dp"
android:id="#+id/radioButtonStroke"
android:checked="false"
android:layout_below="#+id/colorButton_dialogSettings"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fill"
android:id="#+id/radioButton_fill"
android:checked="false"
android:layout_below="#+id/colorButton_dialogSettings"
android:layout_toRightOf="#+id/radioButtonStroke"
android:layout_toEndOf="#+id/radioButtonStroke"
android:layout_marginLeft="10dp"
/>

I am just showing you the important part.. i hope you find their respective lines in your code
final View view = inflater.inflate(R.layout.dialog_settings, null);
// inflating your view..for drawback, this line is [A]
your colorButton has a reference to view.findViewById(R.id.colorButton_dialogSettings) which is from the viewgroup view..which you reference an onclick listener for it..
builder.setView(inflater.inflate(R.layout.dialog_settings, null))
this code right here sets the content view for your dialog. it inflates a the layout and does it's work.. so in the end your builder is not referencing it's content view to view but a new inflated R.layout.dialog_settings layout..
so to solve it just do this
builder.setView(view) // hope you know the view parameter
the view is what you instantiated at line [A] ..
Hope i made sense, and lucid enough for you..let me know if it helps

New Answer
Change your onCreateDialog to this:
import android.view.View.OnClickListener;
public class SettingsDialogFragment extends DialogFragment implements onClickListener
{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
final View view = inflater.inflate(R.layout.dialog_settings, null);
final Button colorButton =(Button) view.findViewById(R.id.colorButton_dialogSettings);
String s = colorButton.getText().toString();
System.out.println("its working "+s);
colorButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
switch (v.getId()) {
case R.id.colorButton_dialogSettings
System.out.println("OnClick");
break;
default:
break;
}
});
// 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_settings, null))
// Add action buttons
.setPositiveButton(R.string.ok, 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) {
SettingsDialogFragment.this.getDialog().cancel();
}
});
return builder.create();
}
In your activity:
private Button colorButton = (Button) findViewById(R.id.colorButton_dialogSettings);
**Old answer that requires you to write your own showDialog method**
Try deleting your button code in the onCreateDialog and add this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_dialog, container, false);
Button colorButton =(Button) v.findViewById(R.id.colorButton_dialogSettings);
public void onClick(View v) {
// When button is clicked, call up to owning activity.
((FragmentDialog)getActivity()).showDialog();
System.out.println("OnClick");
}
});
return v;

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

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>

How to get value of textfield in alertdialog with custom layout

This is my layout for the dialog :-
<?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"
>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="date"
android:ems="10"
android:id="#+id/date"
android:layout_weight="1" />
</LinearLayout>
I call the dialog from a class extending android.support.v4.app.Fragment. Here is my class extending DialogFragment:-
public static class MyDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.date_settings, null));
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
//The problem starts
//How do I get the reference to the EditText
}catch (Exception e){
e.printStackTrace();
}
}
});
return builder.create();
}
}
I call the MyDialogFragment from my class as follows:-
MyDialogFragment dial = new MyDialogFragment();
dial.show(getActivity().getSupportFragmentManager(),"tag");
Now, How do I get the text in the EditText ?
use dialog for getting text from EditText which is in AlertDialog:
public void onClick(DialogInterface dialog, int id) {
try {
EditText editdate = (EditText) ((Dialog)
dialog).findViewById(R.id.date);
}catch (Exception e){
e.printStackTrace();
}
}
or you can also do it using inflated view :
View view = inflater.inflate(R.layout.date_settings, null);
builder.setView(view);
....
EditText editdate = (EditText)view.findViewById(R.id.date);
First you need to give id of EditText
<EditText
android:id="#+id/txtDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="date"
android:ems="10"
android:id="#+id/date"
android:layout_weight="1" />
Do some changes in code like following:
public static class MyDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.date_settings, null);
builder.setView(v);
EditText txtDate = (EditText) v.findViewById(R.id.txtDate);
txtDate.setText("Ben Lind");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
//The problem starts
//How do I get the reference to the EditText
}catch (Exception e){
e.printStackTrace();
}
}
});
return builder.create();
}
}

Using Drawables inside an Dialog

I am running into an issue and don't know the best way to use a set of drawables inside an AlertDialog. The AlertDialog is presented when a user presses a button and is prompted to choose from a list of drawables.
Currently it shows Buttons I have placed in a dialog_view layout when the dialog is created. Ideally I would like to be able to use some type of listview, but if that is not possible I would like to be able to handle the selection/pressing of an item when inside the AlertDialog.
What should I do to handle any actions from within the AlertDialog?
DIALOGFRAGMENT
public class PicturePickerFragment extends DialogFragment {
ArrayList<Integer> imageList = new ArrayList<Integer>();
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// fill an array with selected images
String title = "Picture";
imageList.add(R.drawable.barbershop);
imageList.add(R.drawable.wedding);
imageList.add(R.drawable.meeting);
imageList.add(R.drawable.barbershop);
// return alertdialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
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_view, null))
.setTitle(R.string.event_type)
.setPositiveButton(R.string.select_picture,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// call the method on the parent activity when
// user click the positive button
}
});
return builder.create();
}
}
DIALOG VIEW
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btn_baby"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/baby"
android:text="Baby Shower" />
<Button
android:id="#+id/btn_baking"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/baking"
android:text="Baking" />
<Button
android:id="#+id/btn_barber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/barbershop"
android:text="Barbershop" />
</LinearLayout>
You can use some ListAdapter such as an ArrayAdapter where you present a drawable for every item in the list and then use the adapter when you build the AlertDialog:
builder.setAdapter(myAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//which is the position of the item clicked
}
})
Edit: This is an example that would work with your imageList:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setAdapter(new ArrayAdapter<Integer>(getActivity(), R.layout.dialog_image, imageList) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = getActivity().getLayoutInflater();
view = inflater.inflate(R.layout.dialog_image, parent, false);
} else {
view = convertView;
}
ImageView imageView = (ImageView) view.findViewById(R.id.image);
int resId = getItem(position);
imageView.setImageResource(resId);
return view;
}
}, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.i("Dialog", "selected position " + which);
}
});
return builder.create();
where R.layout.dialog_image contains an ImageView with id android:id="#+id/image" as root element. For example:
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="center"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:minHeight="?attr/listPreferredItemHeight" >
</ImageView>

InvocationTargetException in DialogFragment & NumberPicker

I'm trying to show a NumberPicker in a dialog in order to let the user select a value between 0 and 10. It's my second day spent trying to make it work.
This is what I have:
fragment_number_picker (layout):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/numberPickerFragmentLinearLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal" >
<NumberPicker
android:id="#+id/numberPickerInFragment"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:orientation="horizontal" />
</LinearLayout>
DialogFragment definition:
public class NumberPickerCustomDialog extends DialogFragment {
Context context;
public NumberPickerCustomDialog() {}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
context = getActivity().getApplicationContext();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
LayoutInflater li = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Inflate and set the layout for the dialog
View view = li.inflate(R.layout.fragment_number_picker, null);
builder
// Set view:
.setView(view)
// Add action buttons
.setPositiveButton(R.string.accept, new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int id) {
// Accept number
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
NumberPicker np = (NumberPicker) view.findViewById(R.id.numberPickerInFragment);
np.setMaxValue(200);
np.setMinValue(0);
np.setFocusable(true);
np.setFocusableInTouchMode(true);
return builder.create();
}
}
Call from the main Activity:
public void openNumberPicker(){
FragmentManager fm = getSupportFragmentManager();
NumberPickerCustomDialog npc = new NumberPickerCustomDialog();
npc.show(fm, "fragment_number_picker");
}
I'm getting an InvocationTargetException and I can't make it work.
Any ideas? Thanks!
Try changing the context you're using:
context = getActivity().getApplicationContext();
Instead, you need the activity's own context:
context = getActivity();

Categories

Resources