resize Android canvas - java

I'm a relative beginner with Java and I'm still struggling somewhat with views. I've not had much success with searching through other posts or on-line tutorials. I won't post any code for this because I suspect many of you will know what's going on.
I have a canvas that allows me to draw lines on the screen with my finger, etc. I've got it working fine. My next task is to use a command button to save it as an image. The canvas covers the whole screen so the button I inserted on to the layout (in activity_main.xml) can't be seen.
My specific question is do I deal with the size of the canvas and access to the command button through a method(s) in the DrawView.java class or in the XML file in layout? Links to any good tutorials would be great. Thanks.

Use FrameLayout to show it overlappingly
In the XML the button would come below your View whose Canvas you are drawing on.
Frame Layout Example
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#D6FFD6"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:src="#drawable/android"
android:scaleType="fitCenter"
android:layout_height="fill_parent"
android:layout_width="fill_parent"/>
<TextView
android:text="learnandroideasily.blogspot.com"
android:textSize="30sp"
android:textStyle="bold"
android:textColor="#003399"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:gravity="center"/>
</FrameLayout>
Update based on your comments
This does the entire layout dynamically, no button in the XML needed. Replace TextView or ImageView with your button. Change parameters accordingly.
public class BlahActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout rl = new FrameLayout(this);
rl.addView(cv, GlobalVars.screenWidth, GlobalVars.screenHeight);
setContentView(rl);
ImageView fs = new ImageView(this);
fs.setImageResource(R.drawable.icon);
rl.addView(fs);
TextView fs = new TextView(this);
fs.setText("Bar seco");
fs.setTextColor(android.R.color.white);
fs.setTextSize(1,14);
fs.setLayoutParams(new ViewGroup.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
rl.addView(fs);
}
}

Related

Overlaying slider element on top of CardView

I am trying to build a slider that slides on top of my current view in Android. I built the slider using the SlideUp library found here https://github.com/mancj/SlideUp-Android. The slider is taking the inner RelativeLayout as a view source. When I pull up the slider it ends up behind the CardView. I've looked through all the methods in the library and there isn't one that allows you to move the slider to the foreground. I've also tried to bring the slider view to foreground with .bringToFront() method. Moving the slider view before the CardView in the .xml file does nothing either. Is there a good way to bring the slider to foreground... or the CardView in the background? (without hiding the CardView)
JAVA
//code to build slider
View slideView = findViewById(R.id.slider);
//tried putting slideView.bringToFront() here before passing it to the object but that did nothing
SlideUp slideUp = new SlideUpBuilder(slideView)
.withStartState(SlideUp.State.HIDDEN)
.withStartGravity(Gravity.BOTTOM)
.build();
//code to bring up slider. View "share" exists, it's just irrelevant so I didn't include in the .xml file
buttonView.findViewById(R.id.share).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//tried putting slideView.bringToFront() here as well
slideUp.toggle(); //toggles slider up/down
}
});
XML
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:background="#color/background"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginRight="5dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="20dp"
android:layout_marginBottom="60dp">
</android.support.v7.widget.CardView>
<RelativeLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/slider"
android:background="#color/primary">
</RelativeLayout>
</RelativeLayout>
I figured it out. I found out I can add android:elevation="2dp" for the slider and 0dp for the CardView

Problems When Changing Visibility and Background of a View

I have a LinearLayout in which a TextView's visibility and background (GradientDrawable) changes according to a function myFunction():
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="1"
android:animateLayoutChanges="true"
android:gravity="center"
android:orientation="vertical" >
(...Some views...)
<TextView
android:id="#+id/currentPercentage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:gravity="center"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:singleLine="true"
android:text="XX.X%"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/White" />
</LinearLayout>
The currentPercentage TextView has GONE visibility by default and, according to some events in the fragment that contains it, may have it changed to Visible (or back to GONE) and its background to a different GradientDrawable like so:
myFunction(...){
TextView currentPercentage= (TextView) getView().findViewById(R.id.currentPercentage);
if(condition ... ) {
Color color = // Color based on the condition...
GradientDrawable gd = new GradientDrawable(
GradientDrawable.Orientation.TL_BR,
new int[] {color,color});
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
int dp = Math.round(10f / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
gd.setCornerRadius(dp);
currentChartPercentage.setBackground(gd);
} else if( otherCondition...)
{
// ... similar stuff ...
} else {
// Hide the currentPercentage TextView
currentPercentage.setVisibility(View.GONE);
}
}
This works fine as the TextView's background and visibility change smoothly whenever myFunction() is called and the other elements in the LinearLayout move (with animation) to make room for the TextView.
My issue is that whenever the visibility goes from GONE to VISIBLE, the View fades in nicely (as expected because of android:animateLayoutChanges="true") but right in the end shows up with an annoying black background where the GradientDrawable round corners are (see image).
Right after that, if I touch something else or drag the fragment (it's inside a ViewPager), the black background disappears. If myFunction() is called again, with the View already VISIBLE, then the background color changes as desired with no black background.
Also, if I disable the animation, I don't get the black background too. Thus, the problem seems to be related to the visibility going from GONE to VISIBLE with an animation.
This behavior is obtained on an emulator with Android 4.3 and I haven't tested it on my real device yet.
Does anybody have a clue on why this may be happening?
EDIT:
Just tested this on a real device with ICS without any issue.
EDIT 2:
I once had a problem with an undesirable background showing up in a ListView similar to Background ListView becomes black when scrolling but in this case, setting a cacheColorHint does nothing.

Show Button or Image on top of screen

I am working on a Android Project in which I need to show a Button or ImageView on header of my activity(Screen). Below is my XML layout of my activity.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/app"
android:layout_width="1dp"
android:layout_height="1dp"
android:layout_margin="2px"
android:orientation="vertical"
android:padding="2px" >
<LinearLayout
android:id="#+id/tabBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ImageView
android:id="#+id/BtnSlide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="0px"
android:padding="0px"
android:src="#drawable/button" />
</LinearLayout>
</LinearLayout>
With the above layout, I can see my black button image just below the Proximity title. Is it possible to show my button image to left of Proximity instead of getting shown one line below Proximity?
Or
Is there any way, I can make the image which is left to Proximity title clickable? if I can do that, then I don't need to show Black Button image at the top.
That image is coming from AndroidManifest.xml file. I am not sure how to make that clickable.
With the above layout, I can see my black button image just below the
Proximity title. Is it possible to show my button image to left of
Proximity instead of getting shown one line below Proximity?
Since Proximity is in titlebar you need to create your own custom titlebar to be able to place button to titlebar. Here is example how to achieve it.
Also try to think an usage of ActionBar.
Try this
Button b=new Button(context);
View v = findViewById (android.R.id.title); // Getting the title bar view
v.addView(b); // setting Button
v.setClickable(true);
v.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v) {
Toast.makeText(context, "You have clicked on Title", Toast.LENGTH_SHORT).show();
}
});
How ever I'll suggest you to use ActionBar
Note: I haven't tried that. Let me know if it work for you

Create a Custom ImageButton Class with FrameLayout and TextView

I am a newbie, so, any help is appreciated. I read a lot of posts here at StackOverflow and also I searched for my doubt in Google, but it's hard to find a good answer.
Here is what I am trying to do:
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
<ImageButton
android:background="#layout/roundcorners"
android:id="#+id/hug"
android:scaleType="centerInside"
android:cropToPadding="false"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingBottom="10dip"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:src="#drawable/hug">
</ImageButton>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:textColor="#000000"
android:textSize="15dip"
android:textStyle="bold"
android:paddingBottom="5dip"
android:clickable="true"
android:text="Hug">
</TextView>
</FrameLayout>
Above you guys can see the XML version of what I need.
The point is... I will have many of these FrameLayouts at run time. Every information to fill out the buttons will come from a database.
So, I need to create a Java Class where I can use a loop through all the registers from my database and instantiate a new FrameLayout Class (this class must have an ImageButton and a TextView as you can see from above XML) and just pass parameters, like this:
for (int i = 0; i < mArray.length; i++) {
button = new MyNewImageButton(name, src, text);
}
The above is just to simplify. What I mean is that I will pass parameters from my database when creating an Instance of this class that I am planning to create. Of course, every single button created will be added to the layout.
So... my question is: I know how to do this using XML, but I am REALLY having a hard time to create a class to do this.
Any thoughts? Any help is appreciated.
P.S.: Sorry if I made any mistake in my English, ok? I am a Brazilian. Someday my English will be flawless! Sorry if this question was already answered.
sorry to answer my own question to make another question. I tried to use the comments but there's a limitation in the number of characters, so, I am really sorry.
Hey guys and #blessenm. Well... I tried to use inflater and I came up with the following code:
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// *******************************************
setContentView(R.layout.main);
//this is my main screen
//it's a linearlayout vertical orientation
ViewGroup parent = (ViewGroup) findViewById(R.id.tela_principal);
//these two new LinearLayouts will be one above the other,
//just like two lines
LinearLayout l1 = new LinearLayout(this);
LinearLayout l2 = new LinearLayout(this);
//inside of each linearlayout I set the orientation to horizontal
//so, everytime a picture is inflated from xml, it will fill in one
//linearlayout
l1.setOrientation(LinearLayout.HORIZONTAL);
l2.setOrientation(LinearLayout.HORIZONTAL);
//setting linearlayout parameters, so they fill the whole screen
l1.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
l2.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
//the first two inflated xml imagebuttons I add to LinearView1
view = LayoutInflater.from(getBaseContext()).inflate(R.layout.figurabotao,
l1, true);
view = LayoutInflater.from(getBaseContext()).inflate(R.layout.figurabotao,
l1, true);
//the next two inflated xml imagebuttons I add to LinearView2
view = LayoutInflater.from(getBaseContext()).inflate(R.layout.figurabotao,
l2, true);
view = LayoutInflater.from(getBaseContext()).inflate(R.layout.figurabotao,
l2, true);
//after the above, we should have a grid 2X2
//after linearlayouts are filled, I add them to the main screen
parent.addView(l1, new LinearLayout.LayoutParams(0, 0, 1));
parent.addView(l2, new LinearLayout.LayoutParams(0, 0, 1));
However this is not working. In the errorlog I get the following message:
"Unhandled event loop exception".
Any ideas about what I am doing wrong?
Thanks!
If you are just trying to create a view from the xml and add it to the layout. Just use the LayoutInflater.
Inside the activity use something like
FrameLayout frame = (FrameLayout)getLayoutInfalter.inflate(
R.id.YOUR_VIEW_XML,null);
layout.addView(frame);
If you are trying to create a class extend the frame layout or the the view. Create a constructor which takes your parameters and assign's the required values.
EDIT:
To Acess Elements Inside
If you have set id's to those element, you can access them by
TextView text = (TextView)frame.findViewById(R.id.yourtextview);
Or you can use the child index like
TextView text = (TextView)frame.getChildAt(0);
It sounds like you are looking for a way to create a view class that will be an ImageButton and a TextView wrapped with a FrameLayout.
In this case, you could look into creating your own View class. Probably a View class that extends FrameLayout. See this dev article for more information about how to create a custom view. http://developer.android.com/guide/topics/ui/custom-components.html
Specifically the "Compound Controls" section: http://developer.android.com/guide/topics/ui/custom-components.html#compound

Android overlay a view ontop of everything?

Can you overlay a view on top of everything in android?
In iPhone I would get the new view set its frame.origin to (0,0) and its width and height to the width and height of self.view. Adding it to self.view would then cause it to act as an overlay, covering the content behind (or if it had a transparent background then showing the view behind).
Is there a similar technique in android? I realise that the views are slightly different (there are three types (or more...) relativelayout, linearlayout and framelayout) but is there any way to just overlay a view on top of everything indiscriminately?
Simply use RelativeLayout or FrameLayout. The last child view will overlay everything else.
Android supports a pattern which Cocoa Touch SDK doesn't: Layout management.
Layout for iPhone means to position everything absolute (besides some strech factors). Layout in android means that children will be placed in relation to eachother.
Example (second EditText will completely cover the first one):
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/root_view">
<EditText
android:layout_width="fill_parent"
android:id="#+id/editText1"
android:layout_height="fill_parent">
</EditText>
<EditText
android:layout_width="fill_parent"
android:id="#+id/editText2"
android:layout_height="fill_parent">
<requestFocus></requestFocus>
</EditText>
</FrameLayout>
FrameLayout is some kind of view stack. Made for special cases.
RelativeLayout is pretty powerful. You can define rules like View A has to align parent layout bottom, View B has to align A bottom to top, etc
Update based on comment
Usually you set the content with setContentView(R.layout.your_layout) in onCreate (it will inflate the layout for you). You can do that manually and call setContentView(inflatedView), there's no difference.
The view itself might be a single view (like TextView) or a complex layout hierarchy (nested layouts, since all layouts are views themselves).
After calling setContentView your activity knows what its content looks like and you can use (FrameLayout) findViewById(R.id.root_view) to retrieve any view int this hierarchy (General pattern (ClassOfTheViewWithThisId) findViewById(R.id.declared_id_of_view)).
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/root_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id = "#+id/Everything"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- other actual layout stuff here EVERYTHING HERE -->
</LinearLayout>
<LinearLayout
android:id="#+id/overlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right" >
</LinearLayout>
Now any view you add under LinearLayout with android:id = "#+id/overlay" will appear as overlay with gravity = right on Linear Layout with android:id="#+id/Everything"
You can use bringToFront:
View view=findViewById(R.id.btnStartGame);
view.bringToFront();
The best way is ViewOverlay , You can add any drawable as overlay to any view as its overlay since Android JellyBeanMR2(Api 18).
Add mMyDrawable to mMyView as its overlay:
mMyDrawable.setBounds(0, 0, mMyView.getMeasuredWidth(), mMyView.getMeasuredHeight())
mMyView.getOverlay().add(mMyDrawable)
I have just made a solution for it. I made a library for this to do that in a reusable way that's why you don't need to recode in your XML. Here is documentation on how to use it in Java and Kotlin. First, initialize it from an activity from where you want to show the overlay-
AppWaterMarkBuilder.doConfigure()
.setAppCompatActivity(MainActivity.this)
.setWatermarkProperty(R.layout.layout_water_mark)
.showWatermarkAfterConfig();
Then you can hide and show it from anywhere in your app -
/* For hiding the watermark*/
AppWaterMarkBuilder.hideWatermark()
/* For showing the watermark*/
AppWaterMarkBuilder.showWatermark()
Gif preview -
I have tried the awnsers before but this did not work.
Now I jsut used a LinearLayout instead of a TextureView, now it is working without any problem. Hope it helps some others who have the same problem. :)
view = (LinearLayout) findViewById(R.id.view); //this is initialized in the constructor
openWindowOnButtonClick();
public void openWindowOnButtonClick()
{
view.setAlpha((float)0.5);
FloatingActionButton fb = (FloatingActionButton) findViewById(R.id.floatingActionButton);
final InputMethodManager keyboard = (InputMethodManager) getSystemService(getBaseContext().INPUT_METHOD_SERVICE);
fb.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// check if the Overlay should be visible. If this value is false, it is not shown -> show it.
if(view.getVisibility() == View.INVISIBLE)
{
view.setVisibility(View.VISIBLE);
keyboard.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
Log.d("Overlay", "Klick");
}
else if(view.getVisibility() == View.VISIBLE)
{
view.setVisibility(View.INVISIBLE);
keyboard.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
}
bringToFront() is super easy for programmatic adjustments, as stated above. I had some trouble getting that to work with button z order because of stateListAnimator. If you end up needing to programmatically adjust view overlays, and those views happen to be buttons, make sure to set stateListAnimator to null in your xml layout file. stateListAnimator is android's under-the-hood process to adjust translationZ of buttons when they are clicked, so the button that is clicked ends up visible on top. This is not always what you want... for full Z order control, do this:

Categories

Resources