I have a simple View I've created. I'd like to be able to set its class variables via the Eclipse GUI Plugin's Design tool. Or though the .xml. Is this possible?
Here is what I currently have:
package com.lifecoderdev.android.drawing1;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
public class BoundedView extends View
{
public String CellName = "No name.";
public BoundedView( Context context )
{
super( context );
}
public BoundedView( Context context, AttributeSet attrs )
{
super( context, attrs );
}
public BoundedView( Context context, AttributeSet attrs, int defStyle )
{
super( context, attrs, defStyle );
}
#Override
public void onDraw(Canvas canvas)
{
}
#Override
public boolean onTouchEvent( MotionEvent event )
{
Toast t = Toast.makeText( getContext(), "Selected: " + CellName + "!", Toast.LENGTH_SHORT );
t.show();
return false;
}
}
The View's only job is to be placed in a relative layout, and when it's clicked, do alert a message. That part works just fine, but I'd really like to be able to set CellName via either XML or the Properties panel.
Read the answer by casebash in the following link:
Android Custom View Properties
You'll have to use TypedArray to get your attributes from the xml layout in the last constructor of your custom View(public BoundedView( Context context, AttributeSet attrs, int defStyle )).
The Snake game from the Android SDK is a good example of this.
Related
i'm trying to build the settings for an app and i want to make it customizable, letting the user decide between light and dark theme. I already did this https://www.hidroh.com/2015/02/16/support-multiple-themes-android-app/ following this tutorial.
The problem is, i want another option to select the accent color, like many apps do. How can i achieve this independently from dark/light? Is there a way to avoid the restart of the activity?
The approach I have used is that, keep your colors in an array and let users select the color and store the index of selected color in preferences. So once when the activity is loading read the stored color and set the color accordingly
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(ContextCompat.getColor(this,colors.getResourceId(chapter_key-1, 0)));
}
package com.**********.app.customViews;
/**
* Created by pakistantechhouse on 18/02/2017.
*/
import android.content.Context;
import android.graphics.Canvas;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.widget.RelativeLayout;
import com.**********.app.R;
public class CRelativeLayout extends RelativeLayout {
public CRelativeLayout(Context context) {
super(context);
if (!isInEditMode()) {
//TODO get your color here from the preferences and apply to the view
this.setBackgroundColor(ContextCompat.getColor(context, R.color.colorPrimary));
}
}
public CRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
if (!isInEditMode()) {
//TODO get your color here from the preferences and apply to the view
this.setBackgroundColor(ContextCompat.getColor(context, R.color.colorPrimary));
}
}
public CRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
if (!isInEditMode()) {
//TODO get your color here from the preferences and apply to the view
this.setBackgroundColor(ContextCompat.getColor(context, R.color.colorPrimary));
}
}
protected void onDraw (Canvas canvas) {
super.onDraw(canvas);
}
}
Is there any way to view custom fonts/views in the preview section of Android Studio?
I have used font-awesome as a custom typeface to show microphone icon in my app. Everything is working fine. But as we all know the preview section cannot load custom views.
Is there any plugin or hack to see the custom views in the preview window while coding?
This is what I am loading on my app:
This is what I see in the preview section:
To make FontAwesome icons visible in Android Studio XML designer you can.
Create custom view
Apply font in constructor
Add custom attr if you want to set font from xml
Here is full demo code in gist
Demo img with code from comment:
Important parts: (pretty much the same as Declaring a custom android UI element using XML but with small tuning)
TextViewWithFont.java - Custom view class
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.TextView;
public class TextViewWithFont extends TextView {
public TextViewWithFont(Context context) {
super(context);
init(context, null, 0);
}
public TextViewWithFont(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0);
}
public TextViewWithFont(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
// Load attributes
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TextViewPlusFont, 0, 0);
try {
String fontInAssets = ta.getString(R.styleable.TextViewPlusFont_customFont);
setTypeface(Typefaces.get(context, "fonts/"+ fontInAssets));
} finally {
ta.recycle();
}
}
}
res/values/attrs.xml - Need this to use app:customFont="fontawesome-webfont.ttf"in our layout xml.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TextViewPlusFont">
<attr name="customFont" format="string"/>
</declare-styleable>
</resources>
Typefaces.java - Helper class to reuse fonts (Cache for fonts)
import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;
import java.util.Hashtable;
public class Typefaces {
private static final String TAG = "Typefaces";
private static final Hashtable<String, Typeface> cache = new Hashtable<String, Typeface>();
public static Typeface get(Context c, String assetPath) {
synchronized (cache) {
if (!cache.containsKey(assetPath)) {
try {
Typeface t = Typeface.createFromAsset(c.getAssets(),
assetPath);
cache.put(assetPath, t);
Log.e(TAG, "Loaded '" + assetPath);
} catch (Exception e) {
Log.e(TAG, "Could not get typeface '" + assetPath
+ "' because " + e.getMessage());
return null;
}
}
return cache.get(assetPath);
}
}
}
activity_main.xml - Layout and how to use TextViewWithFont custom view
<?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">
<com.example.TextViewWithFont
xmlns:app="http://schemas.android.com/apk/res/com.example"
app:customFont="fontawesome-webfont.ttf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="\uf1e2"
android:textSize="60dp"/>
</LinearLayout>
Preview section loads custom views fine as long as these views are correctly written. You have to remember about all small details like draw/onDraw/dispatchDraw methods, measuring and layouting, setting correct theme, styling, providing editMode data, etc.
The deal is that Android Studio has its own Context and Resources classes which are unable to perform certain things. For example these classes lack implementation of reading assets from assets folder and raw resources from raw folder.
To load a custom font, you need assets folder which you don't have access to in Android Studio. Custom view should work, more or less.
Does anyone knows if its possible to make the RatingBar go from right-to-Left instead of left to right, or have an idea how to do it?
You can use android:rotation="180" in your Ratingbar to rotate it
i used this way on my read-only Ratingbars, i dont know if this will effect interacting with the Ratingbar.
Use attribute android:scaleX="-1"
OR
package com.example.selection;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.RatingBar;
public class InvertRatingBar extends RatingBar {
public InvertRatingBar(Context context) {
super(context);
}
public InvertRatingBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
public InvertRatingBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int width = this.getMeasuredWidth();
event.setLocation(width - event.getX(), event.getY());
return super.onTouchEvent(event);
}
#Override
protected synchronized void onDraw(Canvas canvas) {
int width = this.getMeasuredWidth();
Matrix matrix = canvas.getMatrix();
matrix.preTranslate(width, 0);
matrix.preScale(-1.f, 1);
canvas.setMatrix(matrix);
super.onDraw(canvas);
}
}
You have to customize the RatingBar..
However you just have to play tricks with displaying RatingBar Images & then some sort of reverse calculations.
Trick will be displaying reverse Images in RatingBar.. swap selected and unselected images in RatingBar.
Allow user to rate on RatingBar. You have to swap selected and unselected calculations. I mean you have to do reverse calculations.
Complete Working example of custom RatingBar on StackOverflow answered by me only.
Download RatingBar icons from here : http://developer.android.com/guide/practices/ui_guidelines/icon_design.html
edit 4:33pm 022111
I forgot to include my xml code. I'm so stupid.
Now I tried attrs to the super class and it still didn't help...
I tried searching for everything but no avail.
My code is very very simple.
The following includes everything I changed from the initial code I get from creating a project.
Thumbknightview.java
package com.google.www.Thumbknight;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
public class ThumbKnightView extends View{
public ThumbKnightView(Context context) {
super(context);
}
public ThumbKnightView(Context context, AttributeSet attrs) {
super(context, attrs); // edit 4:33pm 022111
}}
YoAndroid.java
package com.google.www.Thumbknight;
import android.app.Activity;
import android.os.Bundle;
public class YoAndroid extends Activity {
/** Called when the activity is first created. */
//private ThumbKnightView tnv;
float x;
float y;
float lastx;
float lasty;
float maxspeed = 8;
int ipi = -1;
int firstfinger;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}}
main.xml
I know it might look stupid for experts but for me, it gave me 3+ hours of searching and reading. Please go easy on me.
You need to specify more details - what is your problem? Also, past relevant section of your layout XML.
The code, as such, looks mostly harmless. The only thing to remember is that when you chain the constructor call to super class, pass AttributeSet as well. You will have to also pass this AttributeSet to constructors of your child views.
For. e.g: if you are creating a Button you would say new Button(activityContext,attrs);
public ThumbKnightView(Context context, AttributeSet attrs) {
super(context,attrs);
}}
I want to give the effect that the ListView has faded from whatever is around it. By default it is set to whatever colour your ListView is. I can adjust the orientation of the FadingEdge and the size of the FadingEdge but not the colour. Is it possible?
You'll need to create a new class that extends ListView.
package com.mypackage;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;
public class ColorFadeListView extends ListView
{
// fade to green by default
private static int mFadeColor = 0xFF00FF00;
public ColorFadeListView(Context context, AttributeSet attrs)
{
this(context, attrs,0);
}
public ColorFadeListView(Context context, AttributeSet attrs, int defStyle)
{
super(context,attrs,defStyle);
setFadingEdgeLength(30);
setVerticalFadingEdgeEnabled(true);
}
#Override
public int getSolidColor()
{
return mFadeColor;
}
public void setFadeColor( int fadeColor )
{
mFadeColor = fadeColor;
}
public int getFadeColor()
{
return mFadeColor;
}
}
You can use this list view identically to a normal ListView (though you'll have to cast it properly to use the fadeColor accessor methods). In your XML, instead of defining an object as <ListView android:properties.../> define it as <com.mypackage.ColorFadeListView android:properties.../>
Yes you can !
setCacheColorHint(Color.WHITE);
You can try this (it's a hack, I know):
int glowDrawableId = context.getResources().getIdentifier("overscroll_glow", "drawable", "android");
Drawable androidGlow = context.getResources().getDrawable(glowDrawableId);
androidGlow.setColorFilter(brandColor, PorterDuff.Mode.MULTIPLY);
I took advantage of the fact that the glow effect is actually a shared Drawable and applied a filter on it: http://evendanan.net/android/branding/2013/12/09/branding-edge-effect/