Dialog width and height issue - java

i use custom dialog but in mobile device and in tab view but design is change when i check on tab
i want same same dialog in all device.
See my below code.
private void startDialog() {
final Dialog dialog = new Dialog(activity);
int width = (int)(getResources().getDisplayMetrics().widthPixels*0.70);
int height = (int)(getResources().getDisplayMetrics().heightPixels*0.65);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.setContentView(R.layout.checkout_alert_dialog);
dialog.show();
dialog.getWindow().setLayout(width, height);
btn_cancle = dialog.findViewById(R.id.btn_cancle);
btn_cancle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity, "Cancel coming soon", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
btn_continue = dialog.findViewById(R.id.btn_continue);
btn_continue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity, " Ok coming soon", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
}
Below is Dialog.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/white"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ImageView
android:id="#+id/iv_pointBox"
android:layout_width="#dimen/_80sdp"
android:layout_height="#dimen/_80sdp"
android:src="#drawable/ic_chekout_popup"
android:layout_centerHorizontal="true"
android:layout_marginTop="#dimen/_30sdp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/normal_input_text_size"
android:text="You've chosen to redeem 865 Points and pay 44.44 AED. The Payment process might take Some times, please do not hit the back button or close the app. Would you like to continue. "
android:layout_centerHorizontal="true"
android:layout_marginLeft="#dimen/_20sdp"
android:layout_marginRight="#dimen/_20sdp"
android:layout_below="#+id/iv_pointBox"
android:layout_marginTop="#dimen/_15sdp"
/>
<View
android:layout_width="match_parent"
android:layout_height="#dimen/_1sdp"
android:background="#color/view_color"
android:layout_above="#+id/linerbutton"
/>
<LinearLayout
android:id="#+id/linerbutton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_alignParentBottom="true"
>
<Button
android:id="#+id/btn_cancle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/lable_cancel"
android:textColor="#color/black"
android:textSize="#dimen/normal_input_text_size"
android:textStyle="bold"
android:background="#null"
android:gravity="center"
android:layout_weight="1"
/>
<View
android:layout_width="#dimen/_1sdp"
android:layout_height="#dimen/_45sdp"
android:background="#color/view_color"
/>
<Button
android:id="#+id/btn_continue"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/lable_continue"
android:textColor="#color/black"
android:textSize="#dimen/normal_input_text_size"
android:textStyle="bold"
android:background="#null"
android:layout_weight="1"
android:gravity="center"
/>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
</LinearLayout>
I mention 2 screenshot of my device :
Mobile Device Screen shot:
Tab Screenshot :
See in screenshot dialog was change. So how to i fix it
Thanks in Advance :

Just look at your layout.xml Your layout height and width is match_parent then it's create a spaces.
Just replace your xml with my xml.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="#dimen/_250sdp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#color/white"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<ImageView
android:id="#+id/iv_pointBox"
android:layout_width="#dimen/_80sdp"
android:layout_height="#dimen/_80sdp"
android:src="#drawable/ic_chekout_popup"
android:layout_gravity="center_horizontal"
android:layout_marginTop="#dimen/_30sdp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/normal_input_text_size"
android:text="You've chosen to redeem 865 Points and pay 44.44 AED. The Payment process might take Some times, please do not hit the back button or close the app. Would you like to continue. "
android:layout_centerHorizontal="true"
android:layout_marginLeft="#dimen/_20sdp"
android:layout_marginRight="#dimen/_20sdp"
android:layout_below="#+id/iv_pointBox"
android:layout_marginTop="#dimen/_15sdp"
/>
<View
android:layout_width="match_parent"
android:layout_height="#dimen/_1sdp"
android:background="#color/view_color"
android:layout_marginTop="#dimen/_50sdp"
/>
<LinearLayout
android:id="#+id/linerbutton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<Button
android:id="#+id/btn_cancle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/lable_cancel"
android:textColor="#color/black"
android:textSize="#dimen/normal_input_text_size"
android:textStyle="bold"
android:background="#null"
android:gravity="center"
android:layout_weight="1"
/>
<View
android:layout_width="#dimen/_1sdp"
android:layout_height="#dimen/_45sdp"
android:background="#color/view_color"
/>
<Button
android:id="#+id/btn_continue"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/lable_continue"
android:textColor="#color/black"
android:textSize="#dimen/normal_input_text_size"
android:textStyle="bold"
android:background="#null"
android:layout_weight="1"
android:gravity="center"
/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
And remove below three lines in java file No need to change height and width at run time:
int width = (int)(getResources().getDisplayMetrics().widthPixels*0.70);
int height = (int)(getResources().getDisplayMetrics().heightPixels*0.65);
dialog.getWindow().setLayout(width, height);

try custom layout
custom.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/imageDialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="6dp" />
<TextView
android:id="#+id/textDialog"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:layout_toRightOf="#+id/imageDialog"/>
<Button
android:id="#+id/declineButton"
android:layout_width="100px"
android:layout_height="wrap_content"
android:text=" Submit "
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:layout_below="#+id/textDialog"
android:layout_toRightOf="#+id/imageDialog"
/>
</RelativeLayout>
in java file
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom);
dialog.setTitle("Title");
to open dialog use
dialog.show();
to dismiss dialog use
dialog.dismiss();

Personally, I prefer to create DialogFragment and set width and height like that:
#Override
public void onResume() {
super.onResume();
Window window = getDialog().getWindow();
int width = getArguments().getInt(BUNDLE_KEY_WIDTH);
int height = getArguments().getInt(BUNDLE_KEY_HEIGHT);
window.setLayout(width, height);
}

Replace the
myAlertDialog.show();
by
alertDialog.show();
and then
alertDialog.getWindow().setLayout(width,height);
it will work perfectly
complete code:
private void startDialog() {
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
myAlertDialog.setTitle("title");
myAlertDialog.setMessage("use this");
AlertDialog alertDialog = myAlertDialog.create();
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = (int) ((int)displaymetrics.widthPixels * 0.9);
int height = (int) ((int)displaymetrics.heightPixels * 0.7);
myAlertDialog.setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Intent pictureActionIntent = null;
pictureActionIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pictureActionIntent, GALLERY_PICTURE);
}
});
myAlertDialog.setNegativeButton("Camera", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 15);
}
});
alertDialog.show();
alertDialog.getWindow().setLayout(width,height);
}
if still not working then you can use like this:
class DialogView extends DialogFragment {
Context context;
public static DialogView newInstance() {
DialogView f = new DialogView();
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme);
context = this.getActivity();
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new Dialog(getActivity(), getTheme()) {
#Override
public void onBackPressed() {
//do your stuff
}
};
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.button_layout_view, container, false);
setCancelable(false);
// RelativeLayout closeBtn = (RelativeLayout) view.findViewById(R.id.bottom_separator); get button ids like this- gallery camera etc and you can use click listener on that
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int width = (int) (metrics.widthPixels * 0.90);
int height = (int) (metrics.heightPixels * 0.95);
this.getDialog().getWindow().setLayout(width, height);
return view;
}
public static DisplayMetrics getDeviceMetrics(Context context) {
DisplayMetrics metrics = new DisplayMetrics();
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
display.getMetrics(metrics);
return metrics;
}
}
create xml for that with two button and title
button_layout_view
then call like this :
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
DialogFragment newFragment = DialogView.newInstance();
newFragment.show(ft, "");

Your dialog's width and height is fine in both devices (you are setting them in your startDialog() method).
If you want the ImageView to be smaller in tablet devices, so the proportions are the same in both mobile and tablets, you should use a different dimens file for them:
First, define a dimen for your image:
Inside dimens.xml
<dimen name="dialog_image_size">XXXdp</dimen>
Then, define the same dimen inside /res/values-sw720dp/dimens.xml for 10'' tablets and inside /res/values-sw600dp/dimens.xml for 7'' tablets, and set a smaller dp for them.
Now, when you are on a tablet, a different size will be loaded, so you can use a smaller one to keep the same proportions than in mobile.

Related

Show entire Bottom sheet with toolbar when keyboard is visible

in my application i have 'bottom sheet dialog fragment' when i open it, it work fine, like below image:
but when keyboard is visible the upper toolbar disappear, like below image show.
My Question is how to make toolbar always visible even when keybord is visible....
Here is my '"sheet bottom xml"'
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/lyt_parent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:orientation="vertical">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_alignParentTop="true"
android:background="#color/grey_5"
android:fitsSystemWindows="true"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="horizontal">
<ImageButton
android:id="#+id/bt_close"
android:layout_width="?attr/actionBarSize"
android:layout_height="?attr/actionBarSize"
android:layout_weight="1"
app:srcCompat="#drawable/ic_close"
app:tint="#color/grey_80" />
<ImageButton
android:id="#+id/save"
android:layout_width="?attr/actionBarSize"
android:layout_height="?attr/actionBarSize"
android:layout_weight="1"
app:srcCompat="#drawable/ic_bookmark_border"
app:tint="#color/grey_80" />
<ImageButton
android:layout_width="?attr/actionBarSize"
android:layout_height="?attr/actionBarSize"
android:layout_weight="1"
app:srcCompat="#drawable/ic_repeat"
app:tint="#color/grey_80" />
<ImageButton
android:layout_width="?attr/actionBarSize"
android:layout_height="?attr/actionBarSize"
app:srcCompat="#drawable/ic_more_vert"
app:tint="#color/grey_80" />
</LinearLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/app_bar_layout2"
android:layout_below="#+id/app_bar_layout"
android:clipToPadding="false"
android:fillViewport="true"
android:scrollbars="none"
android:scrollingCache="true"
app:layout_behavior=
"#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white"
android:orientation="vertical"
android:padding="#dimen/spacing_large">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/bottom_sheet_recycler_comment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:itemCount="10" />
<LinearLayout
android:id="#+id/lyt_spacer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:visibility="gone">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="No comments yet"
android:textSize="22dp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
<LinearLayout
android:id="#+id/app_bar_layout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:clipToPadding="false"
android:paddingBottom="10dp"
android:scrollbars="none"
android:scrollingCache="true"
app:layout_anchorGravity="bottom|center">
<EditText
android:id="#+id/post_view_enter_comment_edit_Text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="4dp"
android:layout_marginEnd="5dp"
android:layout_weight="1"
android:background="#drawable/edit_text_round_bg"
android:hint="Write comment..."
android:lineSpacingExtra="2dp"
android:maxLength="400"
android:maxLines="5"
android:textColor="#color/black"
android:textSize="17sp"/>
<ImageView
android:id="#+id/post_view_send_comment"
android:layout_width="40dp"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginVertical="5dp"
android:layout_marginEnd="10dp"
android:background="#drawable/shape_circle"
android:backgroundTint="#color/blue_grey_300"
android:clickable="true"
android:padding="4dp"
android:paddingStart="6dp"
android:src="#android:drawable/ic_menu_send" />
</LinearLayout>
</RelativeLayout>
And also here my "BottomFragment.java".
public class FragmentBottomSheetDialogFull extends
BottomSheetDialogFragment {
private BottomSheetBehavior mBehavior;
private AppBarLayout app_bar_layout;
private RelativeLayout parent_lyt;
private RecyclerView recyclerView;
TopicRecyclerAdapter adapter;
ArrayList<String> topicsArrayList, selectedArray;
ConstraintLayout sheet_constraint_layout;
private String Post_id;
private String content;
private String topic;
public void setData(String post_id, String post_content,
String topic) {
this.Post_id = post_id;
this.content = post_content;
this.topic = topic;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final BottomSheetDialog dialog = (BottomSheetDialog)
super.onCreateDialog(savedInstanceState);
final View view = View.inflate(getContext(),
R.layout.fragment_bottom_sheet_dialog_full, null);
setStyle(DialogFragment.STYLE_NORMAL,
R.style.DialogStyle);
dialog.setContentView(view);
mBehavior = BottomSheetBehavior.from((View)
view.getParent());
mBehavior.setPeekHeight(BottomSheetBehavior.PEEK_HEIGHT_AUTO);
app_bar_layout = (AppBarLayout)
view.findViewById(R.id.app_bar_layout);
parent_lyt = (RelativeLayout)
view.findViewById(R.id.lyt_parent);
mBehavior.setMaxHeight((Tools.getScreenHeight() / 2) +
100);
recyclerView =
view.findViewById(R.id.bottom_sheet_recycler_comment);
topicsArrayList = new ArrayList<>();
selectedArray = new ArrayList<>();
for (int i = 0; i < 50; i++) {
topicsArrayList.add("my " + i);
}
adapter = new TopicRecyclerAdapter(topicsArrayList,
selectedArray);
recyclerView.setLayoutManager(new
LinearLayoutManager(getContext()));
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
mBehavior.setBottomSheetCallback(new
BottomSheetBehavior.BottomSheetCallback() {
#Override
public void onStateChanged(#NonNull View
bottomSheet, int newState) {
if (BottomSheetBehavior.STATE_HIDDEN ==
newState) {
dismiss();
}
}
#Override
public void onSlide(#NonNull View bottomSheet,
float slideOffset) {
}
});
((ImageButton)
view.findViewById(R.id.bt_close)).setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
});
return dialog;
}
#Override
public void onStart() {
super.onStart();
mBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
}
private void hideView(View view) {
ViewGroup.LayoutParams params = view.getLayoutParams();
params.height = 0;
view.setLayoutParams(params);
// dismiss();
// dismissAllowingStateLoss();
}
private void showView(View view, int size) {
ViewGroup.LayoutParams params = view.getLayoutParams();
params.height = size;
view.setLayoutParams(params);
}
private int getActionBarSize() {
final TypedArray styledAttributes =
getContext().getTheme().obtainStyledAttributes(new int[]
{android.R.attr.actionBarSize});
int size = (int) styledAttributes.getDimension(0, 0);
return size;
}
}
What exactly i seek to achieve is shown in this image, the toolbar is stable despite keyboard is visible or not.
Thanks for any help
You can try this to initialize your activity in manifest.
<activity
android:name=".Activities"
android:configChanges="orientation|screenSize|layoutDirection"
android:exported="true"
android:screenOrientation="portrait"android:windowSoftInputMode="adjustPan|adjustResize|stateAlwaysVisible"/>
The most convenient way that I found to change this is by creating style:
<style name="DialogStyle" parent="Theme.Design.Light.BottomSheetDialog">
<item name="android:windowIsFloating">false</item>
<item name="android:statusBarColor">#android:color/transparent</item>
<item name="android:windowSoftInputMode">adjustResize</item>
And set this in onCreate method of your BottomSheetDialogFragment:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setStyle(DialogFragment.STYLE_NORMAL, R.style.DialogStyle)}
Hope this will help you.
The best way to do that is to make specific style for that inside styles.xml
<style name="DialogStyle" parent="Theme.Design.Light.BottomSheetDialog">
<item name="android:windowIsFloating">false</item>
<item name="android:statusBarColor">#android:color/transparent</item>
<item name="android:windowSoftInputMode">adjustResize|stateAlwaysVisible</item>
Once we can't initialize any fragment or BottomSheetDialogFragment inside our manifest, the best way is to go to styles.xml (DialogStyle) and and make
<item name="android:windowsSoftInputMode">adjustResize|stateAlwaysVisible</item>
After that we should override onCreate inside our FragmentBottomSheetDialog.java
override void onCreate(#Nullable Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NORMAL, R.style.DialogStyle);
}
this works prefectly
Thanks for #hardik-kotadiya

Can the RecyclerView scroll with the rest of the fragment layouts?

I have set up a RecyclerView adapter with ViewPager in an activity namely TvShowEpisodeDetails , it works well but there is one issue, the Layout of RecyclerView is fixed while scrolling up and down in the Fragment(TvShowEpisodeDetailsFragment). But I want it to scroll with them.
The RecyclerView and ViewPager are both set inside viewpager_with_toolbar_overlay.xml Layout , and both has been settup in The Activity.
TvShowEpisodeDetailsFragment is the fragment class which belongs to activity class TvShowEpisodeDetails , the fragment creates as many episodes as a TV Show season can offer.
And off course this issue will be gone if I set RecyclerView adapter inside fragment, but I will get non-fixable highlighting and scrolling issues , that is why I set it inside the activity because it does not give those issues.
I need to make it work somehow inside the activity.
My goal is that RecyclerView and ViewPager has to be in the same layout XML file and they both must either be in the activity or fragment class
Is it possible to make the RecyclerView scroll with rest of the fragment layouts?
or
Is it possible to do it programmatically?
Here is the activity
public class TvShowEpisodeDetails extends MizActivity{
#Override
protected int getLayoutResource() {
return R.layout.viewpager_with_toolbar_overlay;
}
#Override
public void onCreate(Bundle savedInstanceState) {
mBus = MizuuApplication.getBus();
super.onCreate(savedInstanceState);
// Set theme
setTheme(R.style.Mizuu_Theme_NoBackground);
// setting episodeslist
final ArrayList<PlanetModel> episodeslist = new ArrayList<>();
for(TvShowEpisode e : mEpisodes){
episodeslist.add(new PlanetModel(e.mEpisode));
}
// setting RecyclerView
mEpisodesList = (RecyclerView) findViewById(R.id.episodesLIST);
// Setting LinearLayoutManager
LinearLayoutManager layoutManager
= new LinearLayoutManager(this.getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
//mEpisodesList.setLayoutManager(new LinearLayoutManager(mContext));
mEpisodesList.setLayoutManager(layoutManager);
// Setting RecyclerView Adapter
PlanetAdapter.OnItemClickListener indicatorCallback = new PlanetAdapter.OnItemClickListener() {
#Override
public void onItemClick(String item) {
SharedPreferences getPref = getContext().getSharedPreferences("PlanetAdapter", Context.MODE_PRIVATE);
int pos = getPref.getInt("newPosition", 0);
mViewPager.setCurrentItem(pos,false);
}
};
final PlanetAdapter planetAdapter = new PlanetAdapter(episodeslist,indicatorCallback);
mEpisodesList.setAdapter(planetAdapter);
// Setting ViewPager
mViewPager = (ViewPager) findViewById(R.id.awesomepager);
mViewPager.setAdapter(new TvShowEpisodeDetailsAdapter(getSupportFragmentManager()));
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
planetAdapter.setSelectedIndex(position);
planetAdapter.notifyDataSetChanged();
mEpisodesList.smoothScrollToPosition(position);
//mEpisodesList.scrollToPosition(position);
for (int i=0; i<episodeslist.size(); i++)
{
episodeslist.get(i).setPlanetSelected(false);
}
episodeslist.get(position).setPlanetSelected(true);
ViewUtils.updateToolbarBackground(TvShowEpisodeDetails.this, mToolbar, 0, mEpisodes.get(position).getTitle(), Color.TRANSPARENT);
}
});
if (savedInstanceState != null) {
mViewPager.setCurrentItem(savedInstanceState.getInt("tab", 0));
} else {
for (int i = 0; i < mEpisodes.size(); i++) {
if (mEpisodes.get(i).getSeason().equals(MizLib.addIndexZero(mSeason)) && mEpisodes.get(i).getEpisode().equals(MizLib.addIndexZero(mEpisode))) {
mViewPager.setCurrentItem(i);
break;
}
}
}
}
}
viewpager_with_toolbar_overlay
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
android:id="#+id/awesomepager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#068006"
android:layout_marginTop="450dp"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/episodesLIST"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:scrollbars="horizontal" />
</LinearLayout>
<include layout="#layout/toolbar_layout" />
</FrameLayout>
Here is the XML layout of the fragment which is inflated in onCreateView of the fragment class
episode_details.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/abc_input_method_navigation_guard">
<com.miz.views.ObservableScrollView
android:id="#+id/observableScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/episodePhoto"
android:layout_width="match_parent"
android:layout_height="#dimen/backdrop_portrait_height"
android:scaleType="centerCrop"
android:src="#drawable/bg" />
<com.melnykov.fab.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/episodePhoto"
android:layout_alignParentEnd="false"
android:layout_alignParentRight="true"
android:layout_marginTop="#dimen/content_details_fab_negative_margin"
android:layout_marginRight="#dimen/content_details_baseline_margin"
android:src="#drawable/ic_play_arrow_white_36dp"
app:fab_colorNormal="#666"
app:fab_type="mini" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/fab"
android:layout_marginLeft="#dimen/content_details_baseline_margin"
android:layout_marginTop="#dimen/content_details_title_margin_top"
android:layout_marginRight="#dimen/content_details_baseline_margin"
android:layout_toLeftOf="#+id/fab"
android:orientation="vertical">
<TextView
android:id="#+id/movieTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="3"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_title" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/content_details_very_small_margin"
android:layout_marginBottom="#dimen/content_details_baseline_margin"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_subheader"
android:textStyle="bold|italic" />
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:id="#+id/details_area"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#666"
android:baselineAligned="false"
android:elevation="1dp"
android:minHeight="#dimen/content_details_large_margin"
android:orientation="horizontal"
android:paddingLeft="#dimen/content_details_baseline_margin"
android:paddingTop="#dimen/content_details_small_margin"
android:paddingRight="#dimen/content_details_baseline_margin"
android:paddingBottom="#dimen/content_details_small_margin">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="center_horizontal"
android:lines="1"
android:maxLines="1"
android:text="#string/detailsAirDate"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="#dimen/content_details_area_subheader" />
<TextView
android:id="#+id/textReleaseDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_area_header"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/textView61"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="center_horizontal"
android:lines="1"
android:maxLines="1"
android:text="#string/detailsRating"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="#dimen/content_details_area_subheader" />
<TextView
android:id="#+id/textView12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_area_header"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="#dimen/content_details_baseline_margin">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/content_details_baseline_margin"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/director"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_movie_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/writer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_edit_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/guest_stars"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_people_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_folder_open_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_body_text" />
</LinearLayout>
</LinearLayout>
</com.miz.views.ObservableScrollView>
<FrameLayout
android:id="#+id/progress_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg"
android:visibility="gone">
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</FrameLayout>
</FrameLayout>
Update
Fragment
#SuppressLint("InflateParams") public class TvShowEpisodeDetailsFragment extends Fragment {
public TvShowEpisodeDetailsFragment() {}
public static TvShowEpisodeDetailsFragment newInstance(String showId, int season, int episode) {
TvShowEpisodeDetailsFragment pageFragment = new TvShowEpisodeDetailsFragment();
Bundle bundle = new Bundle();
bundle.putString("showId", showId);
bundle.putInt("season", season);
bundle.putInt("episode", episode);
pageFragment.setArguments(bundle);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
mContext = getActivity();
mBus = MizuuApplication.getBus();
mShowFileLocation = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean(SHOW_FILE_LOCATION, true);
mPicasso = MizuuApplication.getPicassoDetailsView(getActivity());
mMediumItalic = TypefaceUtils.getRobotoMediumItalic(mContext);
mMedium = TypefaceUtils.getRobotoMedium(mContext);
mCondensedRegular = TypefaceUtils.getRobotoCondensedRegular(mContext);
mDatabaseHelper = MizuuApplication.getTvEpisodeDbAdapter();
LocalBroadcastManager.getInstance(mContext).registerReceiver(mBroadcastReceiver,
new IntentFilter(LocalBroadcastUtils.UPDATE_TV_SHOW_EPISODE_DETAILS_OVERVIEW));
loadEpisode();
}
#Override
public void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mBroadcastReceiver);
}
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
loadEpisode();
loadData();
}
};
private void loadEpisode() {
if (!getArguments().getString("showId").isEmpty() && getArguments().getInt("season") >= 0 && getArguments().getInt("episode") >= 0) {
Cursor cursor = mDatabaseHelper.getEpisode(getArguments().getString("showId"), getArguments().getInt("season"), getArguments().getInt("episode"));
if (cursor.moveToFirst()) {
mEpisode = new TvShowEpisode(getActivity(),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SHOW_ID)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_TITLE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_PLOT)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_AIRDATE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_DIRECTOR)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_WRITER)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_GUESTSTARS)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_RATING)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_HAS_WATCHED)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_FAVOURITE))
);
mEpisode.setFilepaths(MizuuApplication.getTvShowEpisodeMappingsDbAdapter().getFilepathsForEpisode(
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SHOW_ID)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE))
));
}
cursor.close();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.episode_details, container, false);
}
#Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mBackdrop = (ImageView) view.findViewById(R.id.imageBackground);
mEpisodePhoto = (ImageView) view.findViewById(R.id.episodePhoto);
mDetailsArea = view.findViewById(R.id.details_area);
mTitle = (TextView) view.findViewById(R.id.movieTitle);
mSeasonEpisodeNumber = (TextView) view.findViewById(R.id.textView7);
mDescription = (TextView) view.findViewById(R.id.textView2);
mFileSource = (TextView) view.findViewById(R.id.textView3);
mAirDate = (TextView) view.findViewById(R.id.textReleaseDate);
mRating = (TextView) view.findViewById(R.id.textView12);
mDirector = (TextView) view.findViewById(R.id.director);
mWriter = (TextView) view.findViewById(R.id.writer);
mGuestStars = (TextView) view.findViewById(R.id.guest_stars);
mScrollView = (ObservableScrollView) view.findViewById(R.id.observableScrollView);
mFab = (FloatingActionButton) view.findViewById(R.id.fab);
mFab.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ViewUtils.animateFabJump(v, new SimpleAnimatorListener() {
#Override
public void onAnimationEnd(Animator animation) {
play();
}
});
}
});
...
}
...
}
I have set up a RecyclerView adapter with ViewPager in an activity namely TvShowEpisodeDetails , it works well but there is one issue, the Layout of RecyclerView is fixed while scrolling up and down in the Fragment(TvShowEpisodeDetailsFragment). But I want it to scroll with them.
It's hard to use the RecyclerView outside of the ViewPager page fragment; because you can't synchronize and link the touch/motion events when you scroll the page up/down (or when you swipe to next/previous page) between both the page fragment and a standalone (i.e. activity) RecyclerView. Even that won't be smooth.
So, the RecyclerView should be a part of the ViewPager page.
And off course this issue will be gone if I set RecyclerView adapter inside fragment, but I will get unfixable highlighting and scrolling issues
So, now the issue of adding the RecyclerView in the ViewPager fragment is the highlighting issue of the RecyclerView item when you click on any item or when you swipe the ViewPager to right/left page.
But, the main issue is that there is a RecyclerView instance per page, i.e. if you have 5 pages, then you have 5 RecyclerViews.
So, it's a cumbersome to track highlighting only within the RecyclerView adapter class. And hence manipulating that with OnClickListeners solely will have issues of linking these RecyclerView and adapter instances together to update their highlighting item.
So, a simpler approach is to pass a parameter to the RecyclerView adapter with the selected item (which is definitely equals to the current ViewPager page position).
And then do a check in the onBindViewHolder() if the position equals to the passed-in value, then highlight the item; otherwise keep items with the original color.
So, wrapping this up into actions:
Change the adapter constructor to accept a highlighted_position parameter
public PlanetAdapter(ArrayList<PlanetModel> episodeslist,
int highlightedPosition, OnItemClickListener listener)
Whenever you create the ViewPager fragment using newInstance() pass-in the current position of the page fragment:
So, in the TvShowEpisodeDetails activity:
for (int i = 0; i < mEpisodes.size(); i++)
fragments.add(TvShowEpisodeDetailsFragment
.newInstance(mShowId,
Integer.parseInt(mEpisodes.get(i).getSeason()),
Integer.parseInt(mEpisodes.get(i).getEpisode()),
i)); // The position
And in the TvShowEpisodeDetailsFragment fragment, register this into a field in the fragment argument:
public static TvShowEpisodeDetailsFragment newInstance(String showId, int season, int episode, int position) { // adding position
TvShowEpisodeDetailsFragment pageFragment = new TvShowEpisodeDetailsFragment();
Bundle bundle = new Bundle();
// trimmed code.
bundle.putInt("position", position); // <<<< into the bundle
pageFragment.setArguments(bundle);
return pageFragment;
}
And set that in the adapter creation:
int currentPosition = getArguments().getInt("position");
planetAdapter = new PlanetAdapter(episodeslist, currentPosition, new PlanetAdapter.OnItemClickListener() {
#Override
public void onItemClick(final int pos) {
mCallback.sendText(pos);
}
});
And reflect that in the adapter to highlight the item:
public class PlanetAdapter extends RecyclerView.Adapter<PlanetAdapter.PlanetViewHolder> {
private final int highlightedPos;
public PlanetAdapter(ArrayList<PlanetModel> episodeslist, int highlightedPosition, OnItemClickListener listener) {
this.episodeslist = episodeslist;
this.listener = listener;
this.highlightedPos = highlightedPosition; // <<< set the position
}
#Override
public void onBindViewHolder(PlanetAdapter.PlanetViewHolder vh, final int position) {
TextView tv = (TextView) vh.itemView;
PlanetModel planetModel = episodeslist.get(position);
tv.setText(planetModel.getPlanetName());
tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.bg, 0, 0, 0);
if (highlightedPos == position) { //<<<<< Highlight the item
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryLight));
Log.d("LOG_TAG", "onClick: Highlight item: " + highlightedPos);
} else {
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryDark));
Log.d("LOG_TAG", "onClick: No highlight: " + highlightedPos);
}
}
}

getWidth() returns 0 even after applying a workaround

My java code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
final TextView textView = (TextView) findViewById(R.id.text1);
final Button button = (Button) findViewById(R.id.button1);
button.post(new Runnable() {
#Override
public void run() {
int buttonWidth = button.getWidth();
int textWidth = textView.getWidth();
button.setWidth(buttonWidth-textWidth);
}
});
My xml views:
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Timer"
android:textSize="16sp"/>
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="+5"/>
I'm using the second way as described in this answer.
What I want to do is have the button fill the entire width with just enough space for the textView. I've been learning Android for the last few months only so it'll be helpful if you could explain in a lucid manner.
you can use a linearlayout with your button having a weight of 1 and your textview to wrap content.
try this:
<?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="match_parent"
android:orientation="horizontal">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="some text" />
</LinearLayout>
Use the addOnGlobalLayoutListener instead from the solution you linked, that usually works for me when I see this issue.
myView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT > 16) {
myView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
else {
myView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
myView.getWidth();
}
});

If else statement of popup when click different image button in android

I am face some problem about the if else statement of the popup window.i want to set when i click different image button and then will pop up different image, but now after i code and test the pop up is no function...
this is my java code
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.macarons, container, false);
ImageButton ma1 = (ImageButton) view.findViewById(R.id.ma1);
ImageButton ma2 = (ImageButton) view.findViewById(R.id.ma2);
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
final int width = size.x;
final int height = size.y;
positionPopup = (RelativeLayout) view.findViewById(R.id.popup_position);
if (view.equals(ma1)) {
ma1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(LAYOUT_INFLATER_SERVICE);
View customView = inflater.inflate(R.layout.popup, null);
ImageView img1 = (ImageView) customView.findViewById(R.id.popup_img);
img1.setImageResource(R.drawable.ma_bananacho_popup);
myPopUp = new PopupWindow(customView);
myPopUp.setWidth(width - 50);
myPopUp.setHeight(height - 50);
myPopUp.setOutsideTouchable(true);
myPopUp.setFocusable(true);
myPopUp.showAtLocation(positionPopup, Gravity.CENTER, 0, 0);
}
});
}
else if (view.equals(ma2)) {
ma2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(LAYOUT_INFLATER_SERVICE);
View customView = inflater.inflate(R.layout.popup, null);
ImageView img2 = (ImageView) customView.findViewById(R.id.popup_img);
img2.setImageResource(R.drawable.chocolate);
myPopUp = new PopupWindow(customView);
myPopUp.setWidth(width - 50);
myPopUp.setHeight(height - 50);
myPopUp.setOutsideTouchable(true);
myPopUp.setFocusable(true);
myPopUp.showAtLocation(positionPopup, Gravity.CENTER, 0, 0);
}
});
}
return view;
}
this is my popup xml
<?xml version="1.0" encoding="utf-8"?>
<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:gravity="center"
android:orientation="vertical">
<ImageView
android:id="#+id/popup_img"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="20dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"/>
</RelativeLayout>
and this is fragment xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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="wrap_content"
xmlns:tools="http://schemas.android.com/tools"
android:layout_alignParentTop="true"
tools:ignore="ContentDescription">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#FFFFFF"
android:id="#+id/popup_position">
<GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:columnCount="2"
android:layout_marginTop="50dp"
android:layout_marginBottom="50dp">
<ImageButton
android:layout_width="0dp"
android:layout_height="190dp"
android:layout_columnWeight="1"
android:background="#drawable/ma_bananacho"
android:gravity="center"
android:layout_gravity="fill_horizontal"
android:id="#+id/ma1"/>
<ImageButton
android:id="#+id/ma2"
android:layout_width="0dp"
android:layout_height="190dp"
android:layout_columnWeight="1"
android:layout_gravity="fill_horizontal"
android:background="#drawable/ma_blueberry"
android:gravity="center" />
<ImageButton
android:layout_width="0dp"
android:layout_height="190dp"
android:layout_columnWeight="1"
android:background="#drawable/ma_chomint"
android:gravity="center"
android:layout_gravity="fill_horizontal" />
<ImageButton
android:layout_width="0dp"
android:layout_height="190dp"
android:layout_columnWeight="1"
android:background="#drawable/ma_coffee"
android:gravity="center"
android:layout_gravity="fill_horizontal" />
<ImageButton
android:layout_width="0dp"
android:layout_height="190dp"
android:layout_columnWeight="1"
android:background="#drawable/ma_greentea"
android:gravity="center"
android:layout_gravity="fill_horizontal" />
<ImageButton
android:layout_width="0dp"
android:layout_height="190dp"
android:layout_columnWeight="1"
android:background="#drawable/ma_strawcho"
android:gravity="center"
android:layout_gravity="fill_horizontal" />
</GridLayout>
</RelativeLayout>
</ScrollView>
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(LAYOUT_INFLATER_SERVICE);
View customView = inflater.inflate(R.layout.popup, null);
ImageView img1 = (ImageView) customView.findViewById(R.id.popup_img);
if (v.getId() == R.id.ma1) {
img1.setImageResource(R.drawable.ma_bananacho_popup);
} else if (v.getId() == R.id.ma2) {
img1.setImageResource(R.drawable.chocolate);
}
myPopUp = new PopupWindow(customView);
myPopUp.setWidth(width - 50);
myPopUp.setHeight(height - 50);
myPopUp.setOutsideTouchable(true);
myPopUp.setFocusable(true);
myPopUp.showAtLocation(positionPopup, Gravity.CENTER, 0, 0);
}
};
ma1.setOnClickListener(clickListener);
ma2.setOnClickListener(clickListener);
Create a common clickListener set it to the 2 image views ma1, ma2
Change the image resource of popup by comparing viewIds as below
in java any overide method will not work in inside if condition because overide method should come directly inside class . so when you r using any overide method you have to put in under the class or direct in class . hare you r using anonymous
class so you have to put if else inside overide onclick method .for exa.
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(condition){
//for if condition is true
}else{
//for if condition is false
}
}
};

How to setimageresource of popup imageview's image from activityA's button - Android

Currently I have a activity that has a lot of buttons and each button pops up a popup that is used from this site
each button has its own image to view, i wanted to change the image rather than creating individual popup.
ActivityA
Button backbtn;
public ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hiraganaactivity);
final Button btnOpenPopup = (Button)findViewById(R.id.abutton);
btnOpenPopup.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater
= (LayoutInflater) getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
final PopupWindow popupWindow = new PopupWindow(
popupView,
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
Button btnDismiss = (Button) popupView.findViewById(R.id.close);
btnDismiss.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
popupWindow.dismiss();
}
});
popupWindow.showAsDropDown(btnOpenPopup, 30, -250);
}
});
final Button ibutton = (Button)findViewById(R.id.ibutton);
ibutton.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
image = (ImageView) findViewById(R.id.imageview);
image.setImageResource(R.drawable.hiraflash_i);
LayoutInflater layoutInflater
= (LayoutInflater)getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
final PopupWindow popupWindow = new PopupWindow(
popupView,
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
Button btnDismiss = (Button)popupView.findViewById(R.id.close);
btnDismiss.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
popupWindow.dismiss();
}
});
popupWindow.showAsDropDown(btnOpenPopup, 30, -250);
}});
backbtn = (Button) findViewById(R.id.backhira);
backbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(HiraganaActivity.this, Study_Menu.class));
finish();
}
});
}
When abutton is clicked, the popup shows normally with the default set image.
However when ibutton is clicked, the application crashes.
Edit:
HiraganaActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".HiraganaActivity"
tools:showIn="#layout/activity_hiraganaactivity"
android:background="#drawable/hiraganabg"
>
<Button
style="?android:attr/buttonStyleSmall"
android:textAllCaps="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop = "#drawable/adraw"
android:id="#+id/abutton"
android:layout_marginTop="100dp"
android:layout_marginLeft="9dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="20sp"
android:text="a"
android:typeface="normal" />
<Button
style="?android:attr/buttonStyleSmall"
android:textAllCaps="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop = "#drawable/idraw"
android:text="i"
android:id="#+id/ibutton"
android:layout_alignTop="#+id/abutton"
android:layout_toRightOf="#+id/abutton"
android:layout_toEndOf="#+id/abutton"
android:textSize="20sp"
android:typeface="normal"
android:layout_marginLeft="1dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back"
android:id="#+id/backhira"
android:textStyle="bold|italic"
android:textSize="15sp"
android:layout_marginBottom="26dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="false"
android:layout_alignParentRight="false"
android:layout_centerHorizontal="true"
android:backgroundTint="#b9f600"
android:textColor="#0414a3" />
And Popup.xml
<?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="#00546e">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="2dp"
android:background="#929292">
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="30dp"
android:layout_marginLeft="40dp"
android:layout_marginRight="40dp"
android:layout_marginBottom="20dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/aflashhira"
android:id="#+id/imageview" />
<Button
android:id="#+id/close"
android:layout_marginTop="10dp"
android:layout_marginLeft="70dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Close" />
</LinearLayout>
</LinearLayout>
From Log:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.afropoker.kanaapp.HiraganaActivity$2.onClick(HiraganaActivity.java:56)
After you inflate your popup view
View popupView = layoutInflater.inflate(R.layout.popup, null);
Get the imageview using -
ImageView img = (ImageView)popupView.findViewById(R.id.img);// whatever is the id of your ImageView in your popup layout
img.setBackgroundResource(R.id.background_res); //any resource id which you want to set as a background
Using above mechanism you can change the image background any time you want

Categories