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
Related
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>
I'm trying to implement a ContextMenu, but by doing so I checked that my listview was not clickable.
I went over different threads based on this subject and tried everything proposed android:focusable="false" android:focusableInTouchMode="false"
even
descendantFocusability="blocksDescendants"
but still not working
Here is my main xml :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".HomePage">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btnAddTask"
android:id="#+id/btnAddTask"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:onClick="goToAddTask" />
<ListView
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/listViewTasks"
android:layout_alignParentStart="true"
android:layout_above="#+id/btnAddTask"
android:layout_below="#+id/txtTaskList"
android:longClickable="true"
android:clickable="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/txtTaskList"
android:id="#+id/txtTaskList"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Here is my list_item xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:descendantFocusability="blocksDescendants"
android:layout_alignParentStart="true">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnDelete"
android:src="#drawable/no_cross"
android:onClick="goToDeleteTask"
android:layout_gravity="center_vertical"
android:contentDescription="Delete button" />
<LinearLayout
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="vertical"
android:clickable="true">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/txtTaskListName"
android:id="#+id/txtTaskListName"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/txtTaskListDate"
android:id="#+id/txtTaskListDate"
android:layout_below="#+id/txtTaskListName"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/txtTaskListTime"
android:id="#+id/txtTaskListTime"
android:layout_marginLeft="10dp"
android:layout_below="#+id/txtTaskListName"
android:layout_toEndOf="#+id/txtTaskListDate"
android:layout_marginStart="24dp" />
</LinearLayout>
</LinearLayout>
And finally my java code:
public class HomePage extends ActionBarActivity {
final Context context = this;
private static final int EDIT = 0, DELETE = 1;
DatabaseHandler dbHandler;
ListView taskListView;
ArrayAdapter<Task> taskAdapter;
int longClickedItemIndex;
List<Task> Tasks = new ArrayList<Task>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
dbHandler = new DatabaseHandler(getApplicationContext());
taskListView = (ListView) findViewById(R.id.listViewTasks);
// The following piece of code allows to empty database before testing when reinstalling the app for test.
//getApplicationContext().deleteDatabase("myTasks");
registerForContextMenu(taskListView);
taskListView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
return false;
}
});
taskListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
longClickedItemIndex = position;
return false;
}
});
if (dbHandler.getTasksCount() != 0)
Tasks.addAll(dbHandler.getAllTasks());
populateTasksList();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_home_page, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class TaskListAdapter extends ArrayAdapter<Task> {
public TaskListAdapter(){
super(HomePage.this, R.layout.tasklist_item, Tasks);
}
#Override
public View getView(int position, View view, ViewGroup parent){
if (view == null) {
view = getLayoutInflater().inflate(R.layout.tasklist_item, parent, false);
}
Task currentTask = Tasks.get(position);
TextView taskListName = (TextView) view.findViewById(R.id.txtTaskListName);
taskListName.setText(currentTask.getTitle());
TextView taskListDate = (TextView) view.findViewById(R.id.txtTaskListDate);
taskListDate.setText(currentTask.getDate());
TextView taskListTime = (TextView) view.findViewById(R.id.txtTaskListTime);
taskListTime.setText(currentTask.getTime());
/*ImageButton deleteButton = (ImageButton) view.findViewById(R.id.btnDelete);
//deleteButton.setTag(currentTask.getId());
deleteButton.setTag(R.id.taskId,currentTask.getId());
deleteButton.setTag(R.id.position,position);*/
return view;
}
}
private void populateTasksList() {
taskAdapter = new TaskListAdapter();
taskListView.setAdapter(taskAdapter);
}
public void goToAddTask(View view){
Intent intent = new Intent(this, AddTask.class);
startActivity(intent);
}
public void goToDeleteTask(final View view){
AlertDialog alertDialog = new AlertDialog.Builder(context)
// Set Dialog Icon
.setIcon(R.drawable.ic_bullet_key_permission)
// Set Dialog Title
.setTitle(R.string.removeAlert)
// Set Dialog Message
.setMessage(R.string.deleteMessage)
.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ImageButton deleteButton = (ImageButton) view.findViewById(R.id.btnDelete);
// Retrieving the task to delete
int taskId = (int) deleteButton.getTag(R.id.taskId);
Task taskToDelete = dbHandler.getTask(taskId);
// Removing the task from the database and from the calendar
dbHandler.deleteTask(taskToDelete, context);
// Removing the task from the listView
TaskListAdapter tAdapter = (TaskListAdapter)taskListView.getAdapter();
int position = (int)deleteButton.getTag(R.id.position);
tAdapter.remove(tAdapter.getItem(position));
tAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), R.string.removedTask, Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which){
}
})
.create();
alertDialog.show();
}
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
menu.setHeaderIcon(R.drawable.edit_pencil_icon);
menu.setHeaderTitle(R.string.contextMenu_title);
menu.add(menu.NONE, EDIT, menu.NONE, R.string.contextMenu_edit);
menu.add(menu.NONE, DELETE, menu.NONE, R.string.contextMenu_delete);
}
public boolean onContextItemSelected (MenuItem item) {
switch (item.getItemId()) {
case EDIT:
// TODO : Implement editing a task
break;
case DELETE:
deleteTask();
//TODO : to be tested
/*
dbHandler.deleteTask(Tasks.get(longClickedItemIndex);
Tasks.remove(longClickedItemIndex);
taskAdapter.notifyDataSetChanged();
*/
break;
}
return super.onContextItemSelected(item);
}
public void deleteTask(){
AlertDialog alertDialog = new AlertDialog.Builder(context)
// Set Dialog Icon
.setIcon(R.drawable.ic_bullet_key_permission)
// Set Dialog Title
.setTitle(R.string.removeAlert)
// Set Dialog Message
.setMessage(R.string.deleteMessage)
.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ImageButton deleteButton = (ImageButton) findViewById(R.id.btnDelete);
// Retrieving the task to delete
int taskId = (int) deleteButton.getTag(R.id.taskId);
Task taskToDelete = dbHandler.getTask(taskId);
// Removing the task from the database and from the calendar
dbHandler.deleteTask(taskToDelete, context);
// Removing the task from the listView
TaskListAdapter tAdapter = (TaskListAdapter) taskListView.getAdapter();
int position = (int) deleteButton.getTag(R.id.position);
tAdapter.remove(tAdapter.getItem(position));
tAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), R.string.removedTask, Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.create();
alertDialog.show();
}
}
(2 delete functions, cause of my test I'm currently performing).
I finally tried several things and find my solution (for whom it could be usefull).
First of all I had to remove all the things related to "clickable" attribute from all my xml
Then, if you check my list item xml, I have 2 layouts (2 linear one, don't know if this could be different with Relative, did not test this).
What I did is to remove the second one, and modify the core LinearLayout to Relative Layout (to display my elements as I want).
Then I launched again my app and it's perfectly working.
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;
As I am developing an app,where it has a Navigation Drawer it works perfectly but where i placed two images view where they doesn't fire the onClickListener..please tell me how to implement the onclciklistener to work like edit and delete operations...
and the
rowlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/relative">
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/imageView1"
android:src="#drawable/ic_menu_delete" />
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:src="#drawable/ic_menu_edit" />
</RelativeLayout>
and the mainActivity.java
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
final long id) {
text = parent.getItemAtPosition(position).toString();
Toast.makeText(getApplicationContext(), "hello" + text, 3000)
.show();
selectItem(position);
positn = position;
mDrawerList.setItemChecked(position, true);
setTitle(text);
mDrawerLayout.closeDrawer(mDrawerList);
// Toast.makeText(getApplicationContext(), "" + text,
// Toast.LENGTH_SHORT).show();
ImageView edit_image = (ImageView) findViewById(R.id.imageView1);
edit_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "clicked", 3000)
.show();
}
});
if (text.equals("add new item")) {
AlertDialog.Builder builder2 = new AlertDialog.Builder(
MainActivity.this);
final EditText input = new EditText(MainActivity.this);
input.setHeight(100);
input.setWidth(340);
input.setGravity(Gravity.LEFT);
input.setImeOptions(EditorInfo.IME_ACTION_DONE);
builder2.setMessage("Press OK or Cancel");
builder2.setView(input);
builder2.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
userinput = input.getText().toString();
// int length2 = userinput.length();
// String string23 = Integer.toString(length2);
// Log.d("length of userinput", string23);
listItems.add(userinput);
adapter = new ArrayAdapter<String>(
getApplicationContext(),
R.layout.rowlayout, R.id.label,
listItems);
mDrawerList.setAdapter(adapter);
mDrawerLayout.openDrawer(mDrawerList);
String counter = "0";
Log.v("id", "" + id);
Log.v("name", "" + userinput);
Log.v("value", "" + counter);
database1.open();
long insertid;
insertid = database1.Insertvalues(id1,
userinput, counter);
// String string2 = Integer.toString((int)
// insertid);
// Log.d("values inserted", string2);
// Toast.makeText(getApplicationContext(), "" +
// insertid, 3000).show();
}
});
builder2.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
}
});
builder2.show();
}
}
}
Your code works fine.
But the problem is you set onClick for ImageView after click to ListItem
You have to click to ListItem, after that, you can click to ImageView.
Please move this code to outside of onItemClick
ImageView edit_image = (ImageView) findViewById(R.id.imageView1);
edit_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "clicked", 3000)
.show();
}
});
You have to create a custom array adapter and set it to the drawer list view. On the custom adapter getView() when you inflate the item layout, find the image view and set the listener( this will be the inner child items)
#Override
public View getView(int position , View contentView , ViewGroup parent)
{
View row = ((Activity)mContext).getLayoutInflater().inflate(R.layout.rowlayout, null);
ImageView imageView2 = (ImageView) row.findViewById(R.id. imageView2);
imageView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// handle the edit click here
}
});
ImageView imageView1 = (ImageView) row.findViewById(R.id. imageView1);
imageView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// handle the delete click here
}
});
return row;
}
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();