Android Issue with activity context - java

So I have a helper class that reuses a lot of code through out the application, one of the methods is shown below:
public void setTitleTextSize(final int id){
infoButton = ((Activity) context).findViewById(R.id.info_button);
ViewTreeObserver customTitleScale = infoButton.getViewTreeObserver();
customTitleScale.addOnPreDrawListener(new OnPreDrawListener() {
#Override
public boolean onPreDraw() {
int infoWidth = infoButton.getMeasuredWidth();
if(infoWidth !=0){
if(Build.VERSION.SDK_INT >= 11.0){
TypedValue tv = new TypedValue();
((Activity) context).getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true);
actionBarWidth = ((Activity) context).getResources().getDimensionPixelSize(tv.resourceId);
}
DisplayMetrics metrics = new DisplayMetrics();
Display Screen = ((Activity) context).getWindowManager().getDefaultDisplay();
Screen.getMetrics(metrics);
int screenWidth = metrics.widthPixels;
int titleWidth = screenWidth - infoWidth - actionBarWidth;
TextView titleText = (TextView) ((Activity) context).findViewById(R.id.title_text);
titleText.setText(id);
TextPaint paint = titleText.getPaint();
Rect rect = new Rect();
String text = String.valueOf(titleText.getText());
int textLength = text.length();
paint.getTextBounds(text, 0, textLength, rect);
if(rect.width() > titleWidth){
float scale = (float) titleWidth / (float) rect.width();
float textSize = titleText.getTextSize();
float scaleSize = (float) (textSize * (scale*0.8));
titleText.setTextSize(TypedValue.COMPLEX_UNIT_PX, scaleSize);
}
infoButton.getViewTreeObserver().removeOnPreDrawListener(this);
}
return false;
}
});
}
I use this particular method on all of my activities.
The problem I've got is I don't want to display the infoButton on every activity but when I add View infoButton = findViewById(R.id.info_button); infoButton.setVisibility(View.GONE); to the activity, the screen is just black.
So I was thinking on how to do this and the only thing I can thing of is to pass a boolean into the method stating whether the info view is visible or not. I suppose I'd do an if statement saying `if true then display it, if false then don't but I can't figure out how to do this.
Any help would be amazing thanks.

Try to use method infoButton.getVisibility()
it will return you the integer to get visibility status of you widget.

I figured out the issue I was having, My logic wasn't correct for the if statement if(infoWidth !=0). The code wasn't running if the activity didn't have an info button because the infoWidth would always be zero. So I changed the logic to if(infoWidth !=0 || !displayInfoButton) which works perfectly.

Related

How to Auto Size text by height programmaticaly?

I have a vertical LinearLayout with a height of 32dp and i want to fit two TextView of 16dp each. The length of the text is different and i want it to always nicely fit in a single line.
I have tried with an AutoTextView and with a classic TextView + AutoSizing by TextViewCompat but none of these really work. My text shrink a bit but always finish to be crop at the bottom.
Here the base code
LinearLayout adressTextLayout = new LinearLayout(activity);
adressTextLayout.setOrientation(LinearLayout.VERTICAL);
adressTextLayout.setLayoutParams(new TableLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
//icon_size_big = 32dp
(int) (activity.getResources().getDimension(R.dimen.icon_size_big))));
boolean noAdress = true;
//First line with Country, Region and department
if(!mondialAdress.isEmpty()){
noAdress = false;
TextView tx = Utils.createAutoFitTextView(activity, mondialAdress, true, (int) (activity.getResources().getDimension(R.dimen.icon_size_big)/2));
tx.setTypeface(null, Typeface.ITALIC);
adressTextLayout.addView(tx);
}
//Second line with adress, postal code and city
if(!localAdress.isEmpty()){
noAdress = false;
TextView tx = Utils.createAutoFitTextView(activity, localAdress, true, (int) (activity.getResources().getDimension(R.dimen.icon_size_big)/2));
adressTextLayout.addView(tx);
}
//Default line in case we didn't found any adress
if(noAdress){
adressTextLayout.addView(Utils.createAutoFitTextView(activity, activity.getResources().getString(R.string.hint_provide_information), true, 0));
}
Here is the createAutoFitTextView() function with TextViewCompat
public static TextView createAutoFitTextView(Activity activity, String text, boolean singleLine, int maxHeight) {
TextView textView = new AutofitTextView(activity);
textView.setText(text);
//MATCH_PARENT by default
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, maxHeight > 0 ? maxHeight : ViewGroup.LayoutParams.MATCH_PARENT);
textView.setLayoutParams(params);
//Auto Sizing by TextViewCompat
TextViewCompat.setAutoSizeTextTypeWithDefaults(textView, TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
if(singleLine){
textView.setSingleLine(true);
}
return textView;
}
Here the function with AutoFitTextView
public static AutofitTextView createAutoFitTextView(Activity activity, String text, boolean singleLine, int maxHeight) {
AutofitTextView textView = new AutofitTextView(activity);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, maxHeight != -1 ? maxHeight : ViewGroup.LayoutParams.MATCH_PARENT);
textView.setLayoutParams(params);
textView.setText(text);
if(singleLine){
textView.setSingleLine(true);
}
return textView;
}
Here a the result :
With TextViewCompat
With AutoFillTextView:

How to calculate the height of a scrollView using ViewTreeObserver?

I have a ScrollView with some layouts in it, called the fragment_about_sl.xml.And the class associated to it is called AboutSLFragment.java.I want to calculate the height of the scrollView to get height ratio for an image.I researched the web and found this code.
ViewTreeObserver vto = scrollView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
scrollView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int scrollViewHeightInPixels = layout.getMeasuredHeight();
//This is equal with %45 weight you tried before
int height = (scrollViewHeightInPixels * 45) / 100;
ViewGroup.LayoutParams pagerParams = viewPager.getLayoutParams();
pagerParams.height = height;
}
});
As shown in the above code.It just have said scrollView instead of getting it from findViewById().And also in the below code,it just says layout.getMeasuredHeight() instead of specifying the name of layout.
int scrollViewHeightInPixels = layout.getMeasuredHeight();
The question is that I want to know what is meant by layout here(above).What should I put there,is it the id of the scrollView?If so I developed a code myself and I want to know whether it is correct.Please help me I am new to android.The id of the scrollview I used is aboutslscrollview.
final View view = rootView.findViewById(R.id.aboutslscrollview);
ViewTreeObserver vto = view.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int scrollViewHeightInPixels = view.getMeasuredHeight();
//This is equal with %45 weight you tried before
int height = (scrollViewHeightInPixels * 45) / 100;
ViewGroup.LayoutParams pagerParams = viewPager.getLayoutParams();
pagerParams.height = height;
}
});

Get screen size out of Activity class

I need to know the screen size in a class which extends ArrayAdapter class. I can't use getWindowManager method because my class doesn't extend Activity class. What could I do?
using DisplayMatrics
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
double x = Math.pow(metrics.widthPixels/metrics.xdpi,2);
double y = Math.pow(metrics.heightPixels/metrics.ydpi,2);
double screenInches = Math.sqrt(x+y);
also get width and height pixels as below
double heightpixel = metrics.heightPixels;
double widthpixel = metrics.widthPixels;
use WindowManager
WindowManager window = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Display display = window.getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
use getWindowManager() method in activity class and get screen width and height after pass width and height in adapter constructor or use shared prefrence.
Pass the context to the custom ArrayAdapter and then get the size from it
Like this:
public class TestAdapter extends ArrayAdapter<String> {
public TestAdapter(Context context, ArrayList<String> tests) {
super(context, 0, tests);
}
public void SomeMethod() {
Context ctx = getContext();
DisplayMetrics metrics = ctx.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
}
}

Darken/Dim/Blur Activity when navigation drawer is open

I am using LDrawer in my project. I need to make the activity which is hosting the navigation drawer darken/dim/blur when the navigation drawer is opened.
I have gone through similar questions on Stackoverflow and I have not found a satisfiying answer.
Is there any simple trick to make the activity's layout darken/dim/blur when I open my NavigationDrawer
I have the RelativeLayout of my activity defined as
RelativeLayout myActivity = (RelativeLayout) findViewById(R.id.myActivity)
I have the toggle code for NavigationDrawer below
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
//I want to manipulate myActivity's Layout here
mDrawerLayout.openDrawer(mDrawerList);
}
}
return super.onOptionsItemSelected(item);
}
Is there any simple trick to make the activity's layout Darken/Dim/Blur when I open my NavigationDrawer ?
Yes, you can simply change the background image of your activity as Blur when you open the drawer.
Other way is change the alpha or your activity simply by setalpha() and pass the value how much change you want.
If you have list control on your activity and you want to make that blur then below code will work.
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int screenWidth = size.x;
int screenHeight = size.y;
Bitmap blurBitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.invitation_blur_bg);
Rect rect = new Rect(0, 0, blurBitmap.getWidth(), blurBitmap.getHeight());
Implement the OnScrollListener on your activity or fragment where you want to apply this.
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
for (int i = 0; i < listview.getChildCount(); i++) {
View c = listview.getChildAt(i);
Rect r = new Rect();
c.getHitRect(r);
RelativeLayout llItemBg = ((RelativeLayout ) c.findViewById(R.id.root_layout of list item);
Drawable d = new BitmapDrawable(getResources(), cropImage(r,c));
itemBackground.setBackgroundDrawable(d);
}
}
private Bitmap cropImage(Rect r, View c2) {
Bitmap bmOverlay = Bitmap.createBitmap(screenWidth - 60,
c2.getHeight(), Bitmap.Config.ARGB_8888);
Rect rect1=new Rect(0, 0, bmOverlay.getWidth(), bmOverlay.getHeight());
Paint p = new Paint();
Canvas c = new Canvas(bmOverlay);
rect.right = r.right;
rect.top = rect.top;
rect.bottom = r.bottom / 2;
c.drawBitmap(blurBitmap, r, rect1, p);
return bmOverlay;
}

My ImageButton isn't rescaling like the code is telling it to. Infact it's not doing anything

My ImageButton isn't rescaling like the code is telling it to. Infact it's not doing anything.
Code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayShowCustomEnabled(true);
setTitle("Valour");
setContentView(R.layout.activity_main_screen);
getScreenRes();
}
public void getScreenRes() {
DisplayMetrics display = this.getResources().getDisplayMetrics();
int width = display.widthPixels;
int height = display.heightPixels;
int buttonheight = display.heightPixels / 8;
double buttonwidth = buttonheight * 2.66666667;
int buttonwidthint = (int) Math.round(buttonwidth);
ImageButton firsttimeFB = (ImageButton) findViewById(R.id.firsttime_fb);
firsttimeFB.getLayoutParams().width = buttonwidthint;
firsttimeFB.getLayoutParams().height = buttonheight;
}
XML:
<ImageButton
android:layout_width="50dip"
android:layout_height="50dip"
android:background="#drawable/facebook"
android:id="#+id/firsttime_fb"
/>
And it ends up looking like this:
call setLayoutParams() from the firsttimeFB after change the width and height.
Try using android:src and change the ScaleType, see if that makes it scale better.
Also after setting the width and hight by calling getLayoutParams() you should call request layout or the changes will not be displayed.
If you want to set the width based on the height or vice versa you should create your own custom ImageButton class which contains the following code:
public class CustomImageButton extends ImageButton{
...
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int height = getMeasuredHeight();
float constant = 2.6666;
setMeasuredDimension(height * constant, height);
}
...
}
What I want to add is that I am wondering what you are trying to do. I can not think of a senario in which I need the screensize to determen the size of the button. Try to rethink your approach and ask yourself if what you are doing is making any sense.
Try this:
public void getScreenRes(){
DisplayMetrics display = this.getResources().getDisplayMetrics();
int width = display.widthPixels;
int height = display.heightPixels;
int buttonheight = display.heightPixels / 8;
double buttonwidth = buttonheight * 2.66666667;
int buttonwidthint = (int) Math.round(buttonwidth);
ImageButton firsttimeFB = (ImageButton) findViewById(R.id.firsttime_fb);
LayoutParams lp = firsttimeFB.getLayoutParams();
lp.width = buttonwidthint;
lp.height = buttonheight;
firsttimeFB.setLayoutParams(lp);
}

Categories