I'm really new on Android Programming, i have any error on my code,anyone can help if something wrong in this code? The log cat show me these errors:
08-07 11:59:46.773: E/AndroidRuntime(26185): java.lang.RuntimeException: Unable to start activity
ComponentInfo{uiv.makedirect.activity/uiv.makedirect.activity.ManagerActivity}: java.lang.NullPointerException
08-07 11:59:46.773: E/AndroidRuntime(26185): at uiv.makedirect.utilities.RadioStateDrawable.<init>(RadioStateDrawable.java:78)
08-07 11:59:46.773: E/AndroidRuntime(26185): at uiv.makedirect.utilities.TabBarButton.setState(TabBarButton.java:66)
And my code :
Activity i using for create Tabactivity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
* set this activity as the tab bar delegate so that onTabChanged is called when users tap on the bar
*/
setDelegate(new SliderBarActivityDelegateImpl());
Intent home = new Intent(this, HomeActivity.class);
Intent feed = new Intent(this, FeedActivity.class);
Intent cart = new Intent(this, CartActivity.class);
Intent invite = new Intent(this, InviteActivity.class);
Intent account = new Intent(this, AccountActivity.class);
/*
* This adds a title and an image to the tab bar button Image should be a PNG file with transparent background. Shades are opaque areas in on and off state are specific as parameters
*/
this.addTab("Home", R.drawable.star, RadioStateDrawable.SHADE_GRAY, RadioStateDrawable.SHADE_BLUE, home);
this.addTab("Feed", R.drawable.icon_feed, RadioStateDrawable.SHADE_GRAY, RadioStateDrawable.SHADE_BLUE, feed);
this.addTab("Cart", R.drawable.ico_cart, RadioStateDrawable.SHADE_GRAY, RadioStateDrawable.SHADE_BLUE, cart);
this.addTab("Invite", R.drawable.ico_invite, RadioStateDrawable.SHADE_GRAY, RadioStateDrawable.SHADE_BLUE, invite);
this.addTab("Account", R.drawable.star, RadioStateDrawable.SHADE_GRAY, RadioStateDrawable.SHADE_BLUE, account);
/*
* commit is required to redraw the bar after add tabs are added if you know of a better way, drop me your suggestion please.
*/
commit();
}
ScrollableTabActivity:
public class ScrollableTabActivity extends ActivityGroup implements RadioGroup.OnCheckedChangeListener{
private LocalActivityManager activityManager;
private LinearLayout contentViewLayout;
private LinearLayout.LayoutParams contentViewLayoutParams;
private HorizontalScrollView bottomBar;
private RadioGroup.LayoutParams buttonLayoutParams;
private RadioGroup bottomRadioGroup;
private Context context;
private List intentList;
private List titleList;
private List states;
private SliderBarActivityDelegate delegate;
private int defaultOffShade;
private int defaultOnShade;
private IntentFilter changeTabIntentFilter;
private ChangeTabBroadcastReceiver changeTabBroadcastReceiver;
public static String CURRENT_TAB_INDEX;
public static String ACTION_CHANGE_TAB = "com.mobyfactory.changeTab";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
activityManager = getLocalActivityManager();
setContentView(R.layout.customslidingtabhost);
contentViewLayout = (LinearLayout)findViewById(R.id.contentViewLayout);
bottomBar = (HorizontalScrollView)findViewById(R.id.bottomBar);
bottomRadioGroup = (RadioGroup)findViewById(R.id.bottomMenu);
contentViewLayoutParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
defaultOffShade = RadioStateDrawable.SHADE_GRAY;
defaultOnShade = RadioStateDrawable.SHADE_YELLOW;
bottomRadioGroup.setOnCheckedChangeListener(this);
intentList = new ArrayList();
titleList = new ArrayList();
states = new ArrayList();
buttonLayoutParams = new RadioGroup.LayoutParams(320/5, RadioGroup.LayoutParams.WRAP_CONTENT);
}
public void onResume()
{
changeTabIntentFilter = new IntentFilter(ACTION_CHANGE_TAB);
changeTabBroadcastReceiver = new ChangeTabBroadcastReceiver();
registerReceiver(changeTabBroadcastReceiver, changeTabIntentFilter);
super.onResume();
}
public void onPause()
{
unregisterReceiver(changeTabBroadcastReceiver);
super.onPause();
}
public void commit()
{
bottomRadioGroup.removeAllViews();
int optimum_visible_items_in_portrait_mode = 5;
try
{
WindowManager window = getWindowManager();
Display display = window.getDefaultDisplay();
int window_width = display.getWidth();
optimum_visible_items_in_portrait_mode = (int) (window_width/64.0);
}
catch (Exception e)
{
optimum_visible_items_in_portrait_mode = 5;
}
int screen_width = getWindowManager().getDefaultDisplay().getWidth();
int width;
if (intentList.size()<=optimum_visible_items_in_portrait_mode)
{
width = screen_width/intentList.size();
}
else
{
width = screen_width/5;
//width = 320/5;
}
RadioStateDrawable.width = width;
RadioStateDrawable.screen_width = screen_width;
buttonLayoutParams = new RadioGroup.LayoutParams(width, RadioGroup.LayoutParams.WRAP_CONTENT);
for (int i=0; i<intentList.size(); i++)
{
TabBarButton tabButton = new TabBarButton(this);
int[] iconStates = (int[]) states.get(i);
if (iconStates.length==1)
tabButton.setState( titleList.get(i).toString(),iconStates[0]);
else if (iconStates.length==2)
tabButton.setState(titleList.get(i).toString(), iconStates[0], iconStates[1]);
else if (iconStates.length==3)
tabButton.setState(titleList.get(i).toString(), iconStates[0], iconStates[1], iconStates[2]);
tabButton.setId(i);
tabButton.setGravity(Gravity.CENTER);
bottomRadioGroup.addView(tabButton, i, buttonLayoutParams);
}
setCurrentTab(0);
}
protected void addTab(String title, int offIconStateId, int onIconStateId, Intent intent)
{
int[] iconStates = {onIconStateId, offIconStateId};
states.add(iconStates);
intentList.add(intent);
titleList.add(title);
//commit();
}
protected void addTab(String title, int iconStateId, Intent intent)
{
//int[] iconStates = {iconStateId};
int[] iconStates = {iconStateId, defaultOffShade, defaultOnShade};
states.add(iconStates);
intentList.add(intent);
titleList.add(title);
//commit();
}
protected void addTab(String title, int iconStateId, int offShade, int onShade, Intent intent)
{
int[] iconStates = {iconStateId, offShade, onShade};
states.add(iconStates);
intentList.add(intent);
titleList.add(title);
//commit();
}
And RadioStateDrawable for display image in tab:
public class RadioStateDrawable extends Drawable {
private Bitmap bitmap;
private Bitmap highlightBitmap;
private Shader shader;
private Shader textShader;
Context context;
public static int width;
public static int screen_width;
private boolean highlight;
private String label;
public static final int SHADE_GRAY = 0;
public static final int SHADE_BLUE = 1;
public static final int SHADE_MAGENTA = 2;
public static final int SHADE_YELLOW = 3;
public static final int SHADE_GREEN = 4;
public static final int SHADE_RED = 5;
public static final int SHADE_ORANGE = 6;
public RadioStateDrawable(Context context, int imageID, String label, boolean highlight, int shade)
{
super();
this.highlight = highlight;
this.context = context;
this.label = label;
InputStream is = context.getResources().openRawResource(imageID);
bitmap = BitmapFactory.decodeStream(is).extractAlpha();
setShade(shade);
highlightBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.bottom_bar_highlight);
}
public RadioStateDrawable(Context context, int imageID, String label, boolean highlight, int startGradientColor, int endGradientColor)
{
super();
this.highlight = highlight;
this.context = context;
this.label = label;
InputStream is = context.getResources().openRawResource(imageID);
bitmap = BitmapFactory.decodeStream(is).extractAlpha();
int[] shades = new int[] { startGradientColor, endGradientColor };
shader = new LinearGradient(0, 0, 0, bitmap.getHeight(), shades, null, Shader.TileMode.MIRROR);
}
public void setShade(int shade)
{
int[] shades = new int[2];
switch (shade)
{
case SHADE_GRAY: {
shades = new int[] { Color.LTGRAY, Color.DKGRAY };
break;
}
case SHADE_BLUE: {
shades = new int[] { Color.CYAN, Color.BLUE };
break;
}
case SHADE_RED: {
shades = new int[] { Color.MAGENTA, Color.RED };
break;
}
case SHADE_MAGENTA: {
shades = new int[] { Color.MAGENTA, Color.rgb(292, 52, 100) };
break;
}
case SHADE_YELLOW: {
shades = new int[] { Color.YELLOW, Color.rgb(255, 126, 0) };
break;
}
case SHADE_ORANGE: {
shades = new int[] { Color.rgb(255, 126, 0), Color.rgb(255, 90, 0) };
break;
}
case SHADE_GREEN: {
shades = new int[] { Color.GREEN, Color.rgb(0, 79, 4) };
break;
}
}
shader = new LinearGradient(0, 0, 0, bitmap.getHeight(), shades, null, Shader.TileMode.MIRROR);
if (highlight)
textShader = new LinearGradient(0, 0, 0, 10, new int[] { Color.WHITE, Color.LTGRAY }, null, Shader.TileMode.MIRROR);
else
textShader = new LinearGradient(0, 0, 0, 10, new int[] { Color.LTGRAY, Color.DKGRAY }, null, Shader.TileMode.MIRROR);
}
#Override
public void draw(Canvas canvas) {
int bwidth = bitmap.getWidth();
int bheight = bitmap.getHeight();
/*
* if (width==0) { if (screen_width==0) screen_width = 320; width=screen_width/5; }
*/
int x = (width - bwidth) / 2;
int y = 2;
canvas.drawColor(Color.TRANSPARENT);
Paint p = new Paint();
p.setColor(Color.WHITE);
p.setStyle(Paint.Style.FILL);
p.setTextSize(19);
p.setTypeface(Typeface.DEFAULT_BOLD);
p.setFakeBoldText(true);
p.setTextAlign(Align.CENTER);
p.setShader(textShader);
p.setAntiAlias(true);
canvas.drawText(label, width / 2, y + bheight + 20, p);
p.setShader(shader);
canvas.drawBitmap(bitmap, x, y, p);
}
ERROR APPEARS WHEN I CHANGE THE IMAGE TAB
my guess is that your app crashes because of this last line in your RadioStateDrawable function.
the way to get a specific drawable from your resources is like this:
int id = getResources().getIdentifier(bottom_bar_highlight,"drawable", getPackageName());
BitmapFactory.decodeResource(getResources(), id);
After reading your code clearly, I think error java.lang.NullPointerException may come from context.getResources(). I googled about usage of context.getResources().openRawResource() and context.getResources().getIdentifier().
I think that you passed wrong parameter to this method: context.getResources().getIdentifier() .
You may try this:
int id = context.getResources().getIdentifier("drawable/bottom_bar_highlight","drawable", context.getPackageName());
Good luck.
Related
For the university project, we have to solve the problems of a game. In the game that was given to me, there are many problems, for example, the spikes do not come down, the background is not displayed completely, the points and lives are not visible. Can someone help me? How can I use an activity instead of using Android view? Note: In this game, the first character must be saved and spikes will be thrown on him from the top of the screen, when the spikes hit the ground, an explosion will occur.
public class GameView extends View {
Bitmap background, ground, rabbit;
Rect recetBacground, rectGround;
Context context;
Handler handler;
final long UPDATE_MILLS = 30;
Runnable runnable;
Paint textPaint = new Paint();
Paint healthpaint = new Paint();
float TEXT_SIZE = 120;
int points = 0;
int life = 3;
static int dWidth, dHeight;
Random random;
float rabbitX, rabbitY;
float oldX;
float oldRabbitX;
ArrayList<Spike> spikes;
ArrayList<Explosion> explosions;
public GameView(Context context) {
super(context);
this.context = context;
background = BitmapFactory.decodeResource(getResources(), R.drawable.background);
ground = BitmapFactory.decodeResource(getResources(), R.drawable.ground);
rabbit = BitmapFactory.decodeResource(getResources(), R.drawable.rabbit);
Display display = ((Activity) getContext()).getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
dWidth = size.x;
dHeight = size.y;
recetBacground = new Rect(0, 0, dWidth, dHeight);
rectGround = new Rect(0, dHeight - ground.getHeight(), dWidth ,dHeight);
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
invalidate();
}
};
textPaint.setColor(Color.rgb(255, 165, 0));
textPaint.setTextSize(TEXT_SIZE);
textPaint.setTextAlign(Paint.Align.LEFT);
textPaint.setTypeface(ResourcesCompat.getFont(context, R.font.pingiefont));
healthpaint.setColor(Color.GREEN);
random = new Random();
rabbitX = dWidth / 2 - rabbit.getWidth() / 2;
rabbitY = dHeight - ground.getHeight() - rabbit.getHeight();
spikes = new ArrayList<>();
explosions = new ArrayList<>();
for (int i = 0; i < 3; i++) {
Spike spike = new Spike(context);
spikes.add(spike);
}
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(background, null, recetBacground, null);
canvas.drawBitmap(ground, null, rectGround, null);
canvas.drawBitmap(rabbit, rabbitX, rabbitY, null);
for (int i = 0; i < spikes.size(); i++) {
canvas.drawBitmap(spikes.get(i).getSpike(spikes.get(i).spikeFarm), spikes.get(i).spikeX, spikes.get(i).spikeY, null);
spikes.get(i).spikeFarm++;
if (spikes.get(i).spikeFarm > 2) {
spikes.get(i).spikeFarm = 0;
}
spikes.get(i).spikeY += spikes.get(i).spikeVelocity;
if (spikes.get(i).spikeY + spikes.get(i).getSpikeHeight() >= dHeight - ground.getHeight()) {
points += 10;
Explosion explosion = new Explosion(context);
explosion.explosionX = spikes.get(i).spikeX;
explosion.explosionY = spikes.get(i).spikeY;
explosions.add(explosion);
spikes.get(i).resetPosition();
}
}
for (int i = 0; i < spikes.size(); i++) {
if(spikes.get(i).spikeX+spikes.get(i).getSikeWidth()>=rabbitX
&& spikes.get(i).spikeX <= rabbitX+rabbit.getWidth()
&& spikes.get(i).spikeY+spikes.get(i).getSikeWidth() >= rabbitY
&& spikes.get(i).spikeY+spikes.get(i).getSikeWidth()<= rabbitY +rabbit.getHeight()){
life--;
spikes.get(i).resetPosition();
if (life==0){
Intent intent=new Intent(context,GameOver.class);
intent.putExtra("points:",points);
context.startActivity(intent);
((Activity) context).finish();
}
}
}
for (int i=0;i<explosions.size();i++){
canvas.drawBitmap(explosions.get(i).getExplosion(explosions.get(i).explosionFarm),explosions.get(i).explosionX,
explosions.get(i).explosionY,null );
explosions.get(i).explosionFarm++;
if (explosions.get(i).explosionFarm>3){
explosions.remove(i);
}
}
if (life==2) {
healthpaint.setColor(Color.YELLOW);
}
else{
healthpaint.setColor(Color.RED);
}
canvas.drawRect(dWidth-200,30,dWidth-200+60*life,80,healthpaint);
canvas.drawText(""+points,20,TEXT_SIZE,textPaint);
handler.postDelayed(runnable,UPDATE_MILLS);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float touchX=event.getX();
float touchY=event.getY();
if (touchY>= rabbitY){
int action = event.getAction();
if(action== MotionEvent.ACTION_DOWN){
oldX=event.getX();
oldRabbitX=rabbitX;
}
if(action==MotionEvent.ACTION_MOVE){
float shift = oldX- touchX;
float newRabbitX =oldRabbitX-shift;
if(newRabbitX<=0)
rabbitX=0;
else if (newRabbitX>=dWidth-rabbit.getWidth())
rabbitX = dWidth - rabbit.getWidth();
else
rabbitX=newRabbitX;
}
}
return true;
}
}
public class Spike {
Bitmap spike[] = new Bitmap[3];
int spikeFarm =0;
int spikeX,spikeY,spikeVelocity;
Random random;
public Spike(Context context){
spike[0]= BitmapFactory.decodeResource(context.getResources(),R.drawable.spike0);
spike[1]= BitmapFactory.decodeResource(context.getResources(),R.drawable.spike1);
spike[2]= BitmapFactory.decodeResource(context.getResources(),R.drawable.spike2);
random=new Random();
}
public Bitmap getSpike(int spikeFarm){
return spike[spikeFarm];
}
public int getSikeWidth(){
return spike[0].getWidth();
}
public int getSpikeHeight(){
return spike[0].getHeight();
}
public void resetPosition(){
spikeX=random.nextInt(GameView.dWidth-getSikeWidth());
spikeY=-200+random.nextInt(600)* -1;
spikeVelocity= 35+random.nextInt(16);
}
}
I'm doing a small school project of object detection by color. When the object arrives in the center of the screen, it must have a sound. So the sound does not stay uninterrupted, I tried to put a delay on it. But every time the application arrives at the point of playing the sound, it closes. I already researched here and in other forums and the solutions presented did not work.
public class MainActivity extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2{
static {
if(!OpenCVLoader.initDebug()){
Log.d("TAG", "OpenCV not loaded");
} else {
Log.d("TAG", "OpenCV loaded");
}
}
public void voltatela(View v) {
setContentView(R.layout.activity_main);
}
Mat imgHVS, imgThresholded;
Scalar sc1, sc2;
JavaCameraView cameraView;
int largura, altura;
public void Verde(View v) {
sc1 = new Scalar(45, 20, 10);
sc2 = new Scalar(75, 255, 255);
irTelaCamera();
}
public void Azul(View v) {
sc1 = new Scalar(80, 50, 50);
sc2 = new Scalar(100, 255, 255);
irTelaCamera();
}
public void Vermelho(View v) {
sc1 = new Scalar(110, 100, 50);
sc2 = new Scalar(130, 255, 255);
irTelaCamera();
}
public void irTelaCamera(){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.telacamera);
cameraView = (JavaCameraView)findViewById(R.id.cameraview);
cameraView.setCameraIndex(0); //0 para traseira e 1 para dianteira
cameraView.setCvCameraViewListener(this);
cameraView.enableView();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayMetrics displayMetrics = new DisplayMetrics();
WindowManager windowmanager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
windowmanager.getDefaultDisplay().getMetrics(displayMetrics);
}
#Override
protected void onPause() {
super.onPause();
cameraView.disableView();
}
#Override
public void onCameraViewStarted(int width, int height) {
imgHVS = new Mat(width,height, CvType.CV_16UC4);
imgThresholded = new Mat(width,height, CvType.CV_16UC4);
largura = width;
altura = height;
}
#Override
public void onCameraViewStopped() {
}
#Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
Point centrotela = new Point((largura*0.5),(altura*0.5));
final MediaPlayer som = MediaPlayer.create(this, R.raw.bip);
Imgproc.medianBlur(imgHVS,imgHVS,1);
Imgproc.cvtColor(inputFrame.rgba(), imgHVS,Imgproc.COLOR_BGR2HSV);
Core.inRange(imgHVS, sc1, sc2, imgThresholded);
Imgproc.GaussianBlur(imgThresholded, imgThresholded, new Size(3, 3), 1, 1);
Mat circles = new Mat();
double dp = 1.2d;
int minRadius = 20;
int maxRadius = 0;
double param1 = 100, param2 = 20;
int desvio = (int) (minRadius*0.5);
Imgproc.HoughCircles(imgThresholded, circles, Imgproc.HOUGH_GRADIENT, dp, imgThresholded.rows()/4, 100, 20, minRadius, maxRadius);
int numCircles = (circles.rows() == 0) ? 0 : circles.cols();
for (int i = 0; i < numCircles; i++) {
double[] circleCoordinates = circles.get(0, i);
int x = (int) circleCoordinates[0], y = (int) circleCoordinates[1];
Point center = new Point(x, y);
int radius = (int) circleCoordinates[2];
if((((center.x-desvio) <= centrotela.x) && ((center.x+desvio) >= centrotela.x))) {
if ((((center.y-desvio) <= centrotela.y) && ((center.y+desvio) >= centrotela.y))) {
som.start();
Imgproc.circle(imgThresholded, center, radius, new Scalar(100, 255, 255), 4);
// Play sound after 2 sec delay
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
som.stop();
}
}, 2000);
}}
}
Imgproc.circle(imgThresholded,centrotela,50, new Scalar(100,255,255),7);
Imgproc.circle(imgThresholded,centrotela,25, new Scalar(100,255,255),4);
Imgproc.circle(imgThresholded,centrotela,5, new Scalar(100,255,255),-1);
return imgThresholded;
}
}
You have to write sop.start(); instead of sop.stop() inside the handler;
Have you tried playing the sound in a different thread (AsyncTask? See example here). You would have to keep track if you have already spawned a task though, otherwise, you will end up creating too many threads playing the same sound.
I have a custom view object which reads in data and shows that data using a partially clipped image. This class also allows for an "indicator" sliding button to indicate when the data goes over a certain amount. My problem is two fold. The first error I ran in to after a lot of work and testing was the Java.lang.outOfMemory error, or OOM in android. I fixed it by getting and recycling all of the bitmaps in my BitmapDrawables, then making all of those drawables null. The error was popping up after about 9 screen rotations but that fixed it. However it then created another bug and I cant seem to fix both bugs at once. The other bug happens when I got to the home screen, by pressing back or whatever else. By returning to the app after leaving it, I get a null reference to a bitmap drawable error which crashes my app.
The app restores correctly when rotating the screen and I get no memory issues but now when I leave the app completely and go back in I get null reference errors. It just doesn't make any sense why sometimes my objects are being instantiated and other times they are not.
This is my view code:
public class indBar extends View {
//Variables
private int view_height;
private int view_width;
private int touchY;
private int buttonX;
private int buttonY;
private int buttonX2;
private int buttonY2;
private int barX;
private int barY;
private int barX2;
private int barY2;
private int indX;
private int indY;
private int indX2;
private int indY2;
private int arrowX;
private int arrowY;
private int arrowX2;
private int arrowY2;
private int mActivePointerId;
private int indPerc;
private int levelPerc;
private int currentLevel;
private int backOffset;
private int oldLevel;
private int oldCurrLevel;
private boolean startup = true;
//Resource Management
private ViewTreeObserver viewTreeObserver;
private Resources res;
private BitmapDrawable colorBar;
private BitmapDrawable emptyBar;
private BitmapDrawable unpressedButton;
private BitmapDrawable pressedButton;
private BitmapDrawable indicator;
private BitmapDrawable arrow;
private BitmapDrawable redButton;
private ClipDrawable colorbarClip;
private Rect buttonBounds;
private Rect indBounds;
private Rect arrowBounds;
private RectF borderRect;
private RectF backRect;
private Paint borderPaint;
private Paint backPaint;
private Timer animate;
private int animateDelay = 1;
private int animateSpeed;
private boolean animateComplete = true;
//Defaults
private int def_background = Color.BLACK;
private int SIZE = 200;
//Customizable
private int set_background;
public indBar(Context context, AttributeSet attrs) {
super(context, attrs);
readAttrs(context, attrs, 0);
init();
}
public indBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
readAttrs(context, attrs, defStyleAttr);
init();
}
public indBar(Context context) {
super(context);
readAttrs(context, null, 0);
init();
}
private void init(){
//System
if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB) setLayerType(View.LAYER_TYPE_SOFTWARE, null);
viewTreeObserver = getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
getViewTreeObserver().removeOnGlobalLayoutListener(this);
view_width = getWidth();
view_height = getHeight();
afterLayout();
}
});
}
res = getResources();
animateSpeed = 15;
animate = new Timer();
animate.schedule(new TimerTask() {
#Override
public void run() {
animateBar();
}
}, 0, animateDelay);
borderPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
borderPaint.setFilterBitmap(true);
borderPaint.setDither(true);
borderPaint.setStyle(Paint.Style.FILL);
borderPaint.setColor(Color.BLACK);
backPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
backPaint.setFilterBitmap(true);
backPaint.setDither(true);
backPaint.setStyle(Paint.Style.FILL);
backPaint.setColor(set_background);
}
public void afterLayout(){
//Images - Create resource directory object, use it to set an image to a bitmap
// object using bitmap factory and scale it. Then create a drawable using that bitmap.
// Set the bounds of the new drawable bitmap. Assign it to a clip object for partial rendering
backOffset = 20;
borderRect = new RectF(0, 0, view_width, view_height);
backRect = new RectF(backOffset, backOffset, view_width - backOffset, view_height - backOffset);
//Set bar dims
barX = view_width/6;
barX2 = barX + view_width/3;
barY = (view_width - barX2 + 2) / 2;
barY2 = view_height - barY;
//Full Bar
if(colorBar == null) colorBar = new BitmapDrawable(res, BitmapFactory.decodeResource(res, R.drawable.colorbar));
colorBar.setBounds(barX, barY, barX2, barY2);
if(colorbarClip == null) colorbarClip = new ClipDrawable(colorBar, Gravity.BOTTOM, ClipDrawable.VERTICAL);
colorbarClip.setBounds(barX, barY, barX2, barY2);
colorbarClip.setLevel(currentLevel);
//Empty Bar
if(emptyBar == null) emptyBar = new BitmapDrawable(res, BitmapFactory.decodeResource(res, R.drawable.colorempty));
emptyBar.setBounds(barX, barY, barX2, barY2);
//Button
buttonX = barX2 + 2;
buttonX2 = view_width - backOffset;
buttonY = (view_height - barY - (((barY2 - barY)*indPerc)/100)) - ((buttonX2 - buttonX)/2);
buttonY2 = buttonY + (buttonX2 - buttonX);
buttonBounds = new Rect(buttonX, buttonY, buttonX2, buttonY2);
if(unpressedButton == null) unpressedButton = new BitmapDrawable(res, BitmapFactory.decodeResource(res, R.drawable.unpressedbutton));
unpressedButton.setBounds(buttonBounds);
if(redButton == null) redButton = new BitmapDrawable(res, BitmapFactory.decodeResource(res, R.drawable.redbutton));
redButton.setBounds(buttonBounds);
if(pressedButton == null) pressedButton = new BitmapDrawable(res, BitmapFactory.decodeResource(res, R.drawable.pressedbutton));
pressedButton.setBounds(buttonBounds);
pressedButton.setVisible(false, false);
redButton.setVisible(false, false);
//Indicator and arrow
int arrowHeight = view_height/40;
indX = view_width/14;
indX2 = buttonX2/2 + backOffset;
indY = buttonY + (buttonY2 - buttonY)/2;
indY2 = indY + 3;
arrowX = indX;
arrowX2 = buttonX2/6;
arrowY = indY - arrowHeight;
arrowY2 = indY2 + arrowHeight;
indBounds = new Rect(indX, indY, indX2, indY2);
arrowBounds = new Rect(arrowX, arrowY, arrowX2, arrowY2);
if(indicator == null) indicator = new BitmapDrawable(res, BitmapFactory.decodeResource(res, R.drawable.indicator));
if(arrow == null) arrow = new BitmapDrawable(res, BitmapFactory.decodeResource(res, R.drawable.arrow));
indicator.setBounds(indBounds);
arrow.setBounds(arrowBounds);
setLevel(currentLevel);
setIndPerc();
startup = false;
}
#Override
protected void onDraw(Canvas canvas){
if(!startup) {
if(levelPerc >= indPerc) {
redButton.setVisible(true, true);
} else {
redButton.setVisible(false, false);
}
canvas.drawRoundRect(borderRect, 40, 40, borderPaint);
canvas.drawRoundRect(backRect, 40, 40, backPaint);
emptyBar.draw(canvas);
colorbarClip.draw(canvas);
indicator.draw(canvas);
arrow.draw(canvas);
if (unpressedButton.isVisible()) unpressedButton.draw(canvas);
if (pressedButton.isVisible()) pressedButton.draw(canvas);
if (redButton.isVisible()) redButton.draw(canvas);
}
}
private void readAttrs(Context context, AttributeSet attrs, int defStyleAttr) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.indBar, defStyleAttr, 0);
set_background = a.getInteger(R.styleable.indBar_set_background, def_background);
a.recycle();
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int chosenWidth = chooseDimension(widthMode, widthSize);
int chosenHeight = chooseDimension(heightMode, heightSize);
setMeasuredDimension(chosenWidth, chosenHeight);
}
private int chooseDimension(int mode, final int size) {
switch (mode) {
case MeasureSpec.AT_MOST:
case MeasureSpec.EXACTLY:
return size;
case MeasureSpec.UNSPECIFIED:
default:
return SIZE;
}
}
#Override
protected void onRestoreInstanceState(Parcelable state) {
Bundle bundle = (Bundle) state;
Parcelable superState = bundle.getParcelable("superState");
super.onRestoreInstanceState(superState);
currentLevel = bundle.getInt("barLevel");
indPerc = bundle.getInt("indPerc");
startup = true;
}
#Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
Bundle state = new Bundle();
state.putParcelable("superState", superState);
state.putInt("barLevel", currentLevel);
state.putInt("indPerc", indPerc);
unpressedButton.getBitmap().recycle();
redButton.getBitmap().recycle();
pressedButton.getBitmap().recycle();
colorBar.getBitmap().recycle();
emptyBar.getBitmap().recycle();
indicator.getBitmap().recycle();
arrow.getBitmap().recycle();
unpressedButton = null;
redButton = null;
pressedButton = null;
colorBar = null;
emptyBar = null;
indicator = null;
arrow = null;
colorbarClip = null;
return state;
}
#Override
public boolean onTouchEvent(MotionEvent e){
int action = e.getActionMasked();
switch (action){
case MotionEvent.ACTION_DOWN: //New Touch
final int ai = MotionEventCompat.getActionIndex(e);
touchY = (int) MotionEventCompat.getY(e, ai);
unpressedButton.setVisible(false, false);
pressedButton.setVisible(true, false);
mActivePointerId = MotionEventCompat.getPointerId(e, 0);
return true;
case MotionEvent.ACTION_MOVE: //Movement
final int ai2 = MotionEventCompat.findPointerIndex(e, mActivePointerId);
int changeY = (int) MotionEventCompat.getY(e, ai2) - touchY;
buttonMove(changeY);
touchY = (int) MotionEventCompat.getY(e, ai2);
invalidate();
return true;
case MotionEvent.ACTION_UP: //Touch ended
unpressedButton.setVisible(true, false);
pressedButton.setVisible(false, false);
return true;
case MotionEvent.ACTION_POINTER_UP:
int pointerIndex = MotionEventCompat.getActionIndex(e);
int pointerId = MotionEventCompat.getPointerId(e, pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
touchY = (int) MotionEventCompat.getY(e, newPointerIndex);
mActivePointerId = MotionEventCompat.getPointerId(e, newPointerIndex);
}
return true;
default:
return super.onTouchEvent(e);
}
}
private void buttonMove(int y){
if(buttonY + y >= backOffset && buttonY2 + y <= view_height - backOffset) {
buttonY += y;
buttonY2 += y;
indY += y;
indY2 += y;
arrowY += y;
arrowY2 += y;
buttonBounds.set(buttonX, buttonY, buttonX2, buttonY2);
indBounds.set(indX, indY, indX2, indY2);
arrowBounds.set(arrowX, arrowY, arrowX2, arrowY2);
indicator.setBounds(indBounds);
arrow.setBounds(arrowBounds);
unpressedButton.setBounds(buttonBounds);
pressedButton.setBounds(buttonBounds);
redButton.setBounds(buttonBounds);
setIndPerc();
postInvalidate();
}
}
private void setIndPerc(){
int part = indY - barY + ((indY2 - indY)/2);
int whole = barY2 - barY;
indPerc = 100 - ((part*100)/whole);
}
private void setLevelPerc(){
if(colorbarClip != null) {
levelPerc = (colorbarClip.getLevel() * 100) / 10000;
}
}
public void setLevel(int level){
if(animateComplete){
oldCurrLevel = level;
oldLevel = currentLevel;
animateComplete = false;
}
currentLevel = level;
}
public int getIndicatorPerc(){ return indPerc; }
public int getLevelPerc(){ return levelPerc; }
private void animateBar(){
if(colorbarClip != null){
int tempLevel;
if(!animateComplete) {
if (oldLevel > oldCurrLevel) {
tempLevel = oldLevel - animateSpeed;
if (tempLevel < oldCurrLevel) {
oldLevel = oldCurrLevel;
animateComplete = true;
} else oldLevel = tempLevel;
} else {
tempLevel = oldLevel + animateSpeed;
if (tempLevel > oldCurrLevel) {
oldLevel = oldCurrLevel;
animateComplete = true;
} else oldLevel = tempLevel;
}
if(oldLevel == oldCurrLevel) animateComplete = true;
if(animateComplete){
if(oldCurrLevel != currentLevel){
animateComplete = false;
oldLevel = oldCurrLevel;
oldCurrLevel = currentLevel;
}
}
}
colorbarClip.setLevel(oldLevel);
setLevelPerc();
postInvalidate();
}
}
}
The logcat for the null error:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.drawable.BitmapDrawable.setVisible(boolean, boolean)' on a null object reference
at prospect_industries.viewobject.indBar.onDraw(indBar.java:217)
at android.view.View.draw(View.java:16468)
at android.view.View.updateDisplayListIfDirty(View.java:15398)
at android.view.View.getDisplayList(View.java:15420)
at android.view.View.draw(View.java:16190)
at android.view.ViewGroup.drawChild(ViewGroup.java:3713)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3506)
at android.view.View.updateDisplayListIfDirty(View.java:15393)
at android.view.View.getDisplayList(View.java:15420)
at android.view.View.draw(View.java:16190)
at android.view.ViewGroup.drawChild(ViewGroup.java:3713)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3506)
at android.view.View.updateDisplayListIfDirty(View.java:15393)
at android.view.View.getDisplayList(View.java:15420)
at android.view.View.draw(View.java:16190)
at android.view.ViewGroup.drawChild(ViewGroup.java:3713)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3506)
at android.view.View.updateDisplayListIfDirty(View.java:15393)
at android.view.View.getDisplayList(View.java:15420)
at android.view.View.draw(View.java:16190)
at android.view.ViewGroup.drawChild(ViewGroup.java:3713)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3506)
at android.view.View.updateDisplayListIfDirty(View.java:15393)
at android.view.View.getDisplayList(View.java:15420)
at android.view.View.draw(View.java:16190)
at android.view.ViewGroup.drawChild(ViewGroup.java:3713)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3506)
at android.view.View.updateDisplayListIfDirty(View.java:15393)
at android.view.View.getDisplayList(View.java:15420)
at android.view.View.draw(View.java:16190)
at android.view.ViewGroup.drawChild(ViewGroup.java:3713)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3506)
at android.view.View.draw(View.java:16471)
at android.widget.FrameLayout.draw(FrameLayout.java:598)
at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:3107)
at android.view.View.updateDisplayListIfDirty(View.java:15398)
at android.view.View.getDisplayList(View.java:15420)
at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:310)
at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:316)
at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:355)
at android.view.ViewRootImpl.draw(ViewRootImpl.java:2925)
at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2722)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2309)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1298)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6982)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:821)
at android.view.Choreographer.doCallbacks(Choreographer.java:606)
at android.view.Choreographer.doFrame(Choreographer.java:576)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:807)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6872)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
How to change text color of Segmented Controls (if not selected), see below images:
I am getting like this (text in white color):
And want to design this (text in blue color):
Why i am getting space between 3 and 4 button ?
XML:
<com.om.go.widget.SegmentedButton
android:id="#+id/segmented"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
myapp:gradientColorOnStart="#ffffff"
myapp:gradientColorOnEnd="#ffffff"
myapp:gradientColorOffStart="#016de3"
myapp:gradientColorOffEnd="#016de3"
myapp:textStyle="#style/TextViewStyleHeaderButtonBlue"
myapp:strokeColor="#016de3"
myapp:strokeWidth="1dip"
myapp:cornerRadius="4dip"
myapp:btnPaddingTop="7dip"
myapp:btnPaddingBottom="7dip"
/>
SegmentedButton.java:-
public class SegmentedButton extends LinearLayout {
private StateListDrawable mBgLeftOn;
private StateListDrawable mBgRightOn;
private StateListDrawable mBgCenterOn;
private StateListDrawable mBgLeftOff;
private StateListDrawable mBgRightOff;
private StateListDrawable mBgCenterOff;
private int mSelectedButtonIndex = 0;
private List<String> mButtonTitles = new ArrayList<String>();
private int mColorOnStart;
private int mColorOnEnd;
private int mColorOffStart;
private int mColorOffEnd;
private int mColorSelectedStart;
private int mColorSelectedEnd;
private int mColorStroke;
private int mStrokeWidth;
private int mCornerRadius;
private int mTextStyle;
private int mBtnPaddingTop;
private int mBtnPaddingBottom;
private OnClickListenerSegmentedButton mOnClickListenerExternal;
public SegmentedButton(Context context) {
super(context);
}
public SegmentedButton(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SegmentedButton, 0, 0);
CharSequence btnText1 = a.getString(R.styleable.SegmentedButton_btnText1);
CharSequence btnText2 = a.getString(R.styleable.SegmentedButton_btnText2);
if (btnText1 != null) {
mButtonTitles.add(btnText1.toString());
}
if (btnText2 != null) {
mButtonTitles.add(btnText2.toString());
}
mColorOnStart = a.getColor(R.styleable.SegmentedButton_gradientColorOnStart, 0xFF0000);
mColorOnEnd = a.getColor(R.styleable.SegmentedButton_gradientColorOnEnd, 0xFF0000);
mColorOffStart = a.getColor(R.styleable.SegmentedButton_gradientColorOffStart, 0xFF0000);
mColorOffEnd = a.getColor(R.styleable.SegmentedButton_gradientColorOffEnd, 0xFF0000);
mColorStroke = a.getColor(R.styleable.SegmentedButton_strokeColor, 0xFF0000);
mColorSelectedEnd = a.getColor(R.styleable.SegmentedButton_gradientColorSelectedEnd, 0xFF0000);
mColorSelectedStart = a.getColor(R.styleable.SegmentedButton_gradientColorSelectedStart, 0xFF0000);
mStrokeWidth = a.getDimensionPixelSize(R.styleable.SegmentedButton_strokeWidth, 1);
mCornerRadius = a.getDimensionPixelSize(R.styleable.SegmentedButton_cornerRadius, 4);
mTextStyle = a.getResourceId(R.styleable.SegmentedButton_textStyle, -1);
mBtnPaddingTop = a.getDimensionPixelSize(R.styleable.SegmentedButton_btnPaddingTop, 0);
mBtnPaddingBottom = a.getDimensionPixelSize(R.styleable.SegmentedButton_btnPaddingBottom, 0);
a.recycle();
buildDrawables(mColorOnStart, mColorOnEnd, mColorOffStart, mColorOffEnd,
mColorSelectedStart, mColorSelectedEnd, mCornerRadius, mColorStroke,
mStrokeWidth);
if (mButtonTitles.size() > 0) {
_addButtons(new String[mButtonTitles.size()]);
}
}
public void clearButtons() {
removeAllViews();
}
public void addButtons(String ... titles) {
_addButtons(titles);
}
#SuppressWarnings("deprecation")
private void _addButtons(String[] titles) {
for (int i = 0; i < titles.length; i++) {
Button button = new Button(getContext());
button.setText(titles[i]);
button.setTag(new Integer(i));
button.setOnClickListener(mOnClickListener);
if (mTextStyle != -1) {
button.setTextAppearance(getContext(), mTextStyle);
}
if (titles.length == 1) {
// Don't use a segmented button with one button.
return;
} else if (titles.length == 2) {
if (i == 0) {
button.setBackgroundDrawable(mBgLeftOff);
} else {
button.setBackgroundDrawable(mBgRightOn);
}
} else {
if (i == 0) {
button.setBackgroundDrawable(mBgLeftOff);
} else if (i == titles.length-1) {
button.setBackgroundDrawable(mBgRightOn);
} else {
button.setBackgroundDrawable(mBgCenterOn);
}
}
LinearLayout.LayoutParams llp =
new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.WRAP_CONTENT,
1);
addView(button, llp);
button.setPadding(0, mBtnPaddingTop, 0, mBtnPaddingBottom);
}
}
private void buildDrawables(int colorOnStart,
int colorOnEnd,
int colorOffStart,
int colorOffEnd,
int colorSelectedStart,
int colorSelectedEnd,
float crad,
int strokeColor,
int strokeWidth)
{
// top-left, top-right, bottom-right, bottom-left
float[] radiiLeft = new float[] {
crad, crad, 0, 0, 0, 0, crad, crad
};
float[] radiiRight = new float[] {
0, 0, crad, crad, crad, crad, 0, 0
};
float[] radiiCenter = new float[] {
0, 0, 0, 0, 0, 0, 0, 0
};
GradientDrawable leftOn = buildGradientDrawable(colorOnStart, colorOnEnd, strokeWidth, strokeColor);
leftOn.setCornerRadii(radiiLeft);
GradientDrawable leftOff = buildGradientDrawable(colorOffStart, colorOffEnd, strokeWidth, strokeColor);
leftOff.setCornerRadii(radiiLeft);
GradientDrawable leftSelected = buildGradientDrawable(colorSelectedStart, colorSelectedEnd, strokeWidth, strokeColor);
leftSelected.setCornerRadii(radiiLeft);
GradientDrawable rightOn = buildGradientDrawable(colorOnStart, colorOnEnd, strokeWidth, strokeColor);
rightOn.setCornerRadii(radiiRight);
GradientDrawable rightOff = buildGradientDrawable(colorOffStart, colorOffEnd, strokeWidth, strokeColor);
rightOff.setCornerRadii(radiiRight);
GradientDrawable rightSelected = buildGradientDrawable(colorSelectedStart, colorSelectedEnd, strokeWidth, strokeColor);
rightSelected.setCornerRadii(radiiRight);
GradientDrawable centerOn = buildGradientDrawable(colorOnStart, colorOnEnd, strokeWidth, strokeColor);
centerOn.setCornerRadii(radiiCenter);
GradientDrawable centerOff = buildGradientDrawable(colorOffStart, colorOffEnd, strokeWidth, strokeColor);
centerOff.setCornerRadii(radiiCenter);
GradientDrawable centerSelected = buildGradientDrawable(colorSelectedStart, colorSelectedEnd, strokeWidth, strokeColor);
centerSelected.setCornerRadii(radiiCenter);
List<int[]> onStates = buildOnStates();
List<int[]> offStates = buildOffStates();
mBgLeftOn = new StateListDrawable();
mBgRightOn = new StateListDrawable();
mBgCenterOn = new StateListDrawable();
mBgLeftOff = new StateListDrawable();
mBgRightOff = new StateListDrawable();
mBgCenterOff = new StateListDrawable();
for (int[] it : onStates) {
mBgLeftOn.addState(it, leftSelected);
mBgRightOn.addState(it, rightSelected);
mBgCenterOn.addState(it, centerSelected);
mBgLeftOff.addState(it, leftSelected);
mBgRightOff.addState(it, rightSelected);
mBgCenterOff.addState(it, centerSelected);
}
for (int[] it : offStates) {
mBgLeftOn.addState(it, leftOn);
mBgRightOn.addState(it, rightOn);
mBgCenterOn.addState(it, centerOn);
mBgLeftOff.addState(it, leftOff);
mBgRightOff.addState(it, rightOff);
mBgCenterOff.addState(it, centerOff);
}
}
private List<int[]> buildOnStates() {
List<int[]> res = new ArrayList<int[]>();
res.add(new int[] {
android.R.attr.state_focused, android.R.attr.state_enabled});
res.add(new int[] {
android.R.attr.state_focused, android.R.attr.state_selected, android.R.attr.state_enabled});
res.add(new int[] {
android.R.attr.state_pressed});
return res;
}
private List<int[]> buildOffStates() {
List<int[]> res = new ArrayList<int[]>();
res.add(new int[] {
android.R.attr.state_enabled});
res.add(new int[] {
android.R.attr.state_selected, android.R.attr.state_enabled});
return res;
}
private GradientDrawable buildGradientDrawable(int colorStart, int colorEnd, int strokeWidth, int strokeColor) {
GradientDrawable gd = new GradientDrawable(
GradientDrawable.Orientation.TOP_BOTTOM,
new int[] { colorStart, colorEnd });
gd.setShape(GradientDrawable.RECTANGLE);
gd.setStroke(strokeWidth, strokeColor);
return gd;
}
private OnClickListener mOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
Button btnNext = (Button)v;
int btnNextIndex = ((Integer)btnNext.getTag()).intValue();
if (btnNextIndex == mSelectedButtonIndex) {
return;
}
handleStateChange(mSelectedButtonIndex, btnNextIndex);
if (mOnClickListenerExternal != null) {
mOnClickListenerExternal.onClick(mSelectedButtonIndex);
}
}
};
#SuppressWarnings("deprecation")
private void handleStateChange(int btnLastIndex, int btnNextIndex) {
int count = getChildCount();
Button btnLast = (Button)getChildAt(btnLastIndex);
Button btnNext = (Button)getChildAt(btnNextIndex);
if (count < 3) {
if (btnLastIndex == 0) {
btnLast.setBackgroundDrawable(mBgLeftOn);
} else {
btnLast.setBackgroundDrawable(mBgRightOn);
}
if (btnNextIndex == 0) {
btnNext.setBackgroundDrawable(mBgLeftOff);
} else {
btnNext.setBackgroundDrawable(mBgRightOff);
}
} else {
if (btnLastIndex == 0) {
btnLast.setBackgroundDrawable(mBgLeftOn);
} else if (btnLastIndex == count-1) {
btnLast.setBackgroundDrawable(mBgRightOn);
} else {
btnLast.setBackgroundDrawable(mBgCenterOn);
}
if (btnNextIndex == 0) {
btnNext.setBackgroundDrawable(mBgLeftOff);
} else if (btnNextIndex == count-1) {
btnNext.setBackgroundDrawable(mBgRightOff);
} else {
btnNext.setBackgroundDrawable(mBgCenterOff);
}
}
btnLast.setPadding(0, mBtnPaddingTop, 0, mBtnPaddingBottom);
btnNext.setPadding(0, mBtnPaddingTop, 0, mBtnPaddingBottom);
mSelectedButtonIndex = btnNextIndex;
}
public int getSelectedButtonIndex() {
return mSelectedButtonIndex;
}
public void setPushedButtonIndex(int index) {
handleStateChange(mSelectedButtonIndex, index);
}
public void setOnClickListener(OnClickListenerSegmentedButton listener) {
mOnClickListenerExternal = listener;
}
public interface OnClickListenerSegmentedButton {
public void onClick(int index);
}
}
My app Features:
Take photo from camera or picture gallery; //done
Collection of funny stickers; //done
Share created comical photos via email, mms etc. //done
Save 'stickered' photos in picture gallery; //done
Move, scale and rotate sticker images;
In this issue.. I am facing difficulty... I can able to add but I cant able to select the stickers after sticking two or more...while i am adding two or three stickers to an image then i can't able to select stickers individually. Or by selecting the stickers are changing automatically.
Facing this issue from last one week...
Can anyone suggest me any sample example program or supported lib file?
I tried Aviary but it is not suitable for this application.
Below is my List of Code:
public class MyMain extends Activity implements OnClickListener {
private static final int FROM_GALLERY = 200, CAMERA_PIC_REQUEST = 201,
SELECT_STICK_IMAGE = 10, FROM_SAVE_LIB = 11;
private ImageView mainImage, imgNew, imgSave, cat, stickyImage, done, flip,back,trash;
private RelativeLayout catWangMainImgLayout, rl_mainImageBottamBar1,
rl_mainImageBottamBar2;
public static int width, height, imWidth;
public OnTouchListener onTouchListenerStickImage = null;
private Bitmap camera_thumbnail;
static int l=0,m=0;
Pinch pig;
String image_id;
ArrayList stickyItemId = new ArrayList();
static Bitmap join;
private LinearLayout carHead, editImage;
private OnClickListener stickyImageListner, doneListener;
ArrayList sticky_list = new ArrayList();
public static int drag_x, drag_y;
int index = -1;
boolean stk_in_rect = false;
ImageView imageView_stky, imageView3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.cat_wang_main);
Info.sticky_param = new ArrayList();
String type = getIntent().getExtras().getString("action_type");
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
Info.widthAfterZoom = Info.screenWidth = width = metrics.widthPixels;
imWidth = width - width / 15;
Info.screenHight = height = metrics.heightPixels;
stickyImage.setImageDrawable(getResources().getDrawable(Integer.parseInt(stickyItemId.get(index).toString())));
stickyImage.setBackgroundResource(R.drawable.image_border);
stickyImage.setPadding(20, 20, 20, 20);
Bitmap bmap3 = loadBitmapFromView(stickyImage);
imageView3.setOnTouchListener(null);
Pinch.matrix = Info.getMat(index);
imageView3.setOnTouchListener(Info.onTch);
imageView3.setImageBitmap(bmap3);
imageView3.bringToFront();
setMainBottanEditBar();
}
}
return true;
}
};
doneListener = new OnClickListener() {
#Override
public void onClick(View v) {
try {
l=0;
m=0;
imageView_stky = (ImageView) catWangMainImgLayout.getChildAt(Info.current_matrix_id+1);
imageView_stky.setImageBitmap(null);
imageView_stky.setAlpha(255);
stickyImage = new ImageView(CatWangMain.this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(Info.screenWidth, Info.screenWidth);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
stickyImage.setLayoutParams(params);
stickyImage.setPadding(20, 20, 20, 20);
sticky_list.add(stickyImage);
Bitmap bmap2 = loadBitmapFromView(stickyImage);
imageView_stky.setOnTouchListener(null);
imageView_stky.setOnTouchListener(onTouchListenerStickImage);
imageView_stky.setImageBitmap(bmap2);
setSelectStickyMode();
Info.addMat(Pinch.matrix,index);
Pinch.editMood = false;
//int i =0;
Info.sticky_param.set(Info.current_matrix_id,new SavedStickyImageParam(Info.ceterOfX, Info.ceterOfY, Info.widthAfterZoom, Info.rotation));
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (NotFoundException e) {
e.printStackTrace();
}
}
};
}
void camera() {
Context context = this;
PackageManager packageManager = context.getPackageManager();
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
// yes
Log.i("camera", "This device has camera!");
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
} else {
// no
Log.i("camera", "This device has no camera!");
pickImage();
}
}
void pickImage() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, FROM_GALLERY);
}
void createStickyImage(Bitmap bitmap, int id) {
pig = new Pinch(this, catWangMainImgLayout);
pig.addImage(bitmap, id);
}
super.onActivityResult(requestCode, resultCode, data);
int req = requestCode;
switch (req) {
case FROM_GALLERY:
setMainImageBg(resultCode, data);
break;
case SELECT_STICK_IMAGE:
addStickyImage(resultCode, data);
break;
case CAMERA_PIC_REQUEST:
if (requestCode == CAMERA_PIC_REQUEST) {
if (resultCode == RESULT_OK) {
// data.getExtras()
camera_thumbnail = (Bitmap) data.getExtras().get("data");
mainImage = (ImageView) findViewById(R.id.img_mainImg);
mainImage.setImageBitmap(camera_thumbnail);
} else {
finish();
}
} else {
}
break;
case FROM_SAVE_LIB:
Bundle b = getIntent().getExtras();
String sd = (String) b.getString("fromSaveImag");
if (resultCode == 13) {
callDialog_SaveToLib();
}
break;
default:
break;
}
}
void addStickyImage(int resultCode, Intent data){
if (resultCode == RESULT_OK) {
//sticky_param_added = false;
index = index +1;
Pinch.drag_x_value = Info.screenWidth/2;
Info.ceterOfX = Info.screenWidth/2;
Info.ceterOfY = Info.screenWidth/2;
Info.widthAfterZoom = Info.screenWidth;
Info.rotation = 0;
image_id = data.getStringExtra("img");
stickyItemId.add(image_id);
Toast.makeText(getApplicationContext(),"" + Integer.parseInt(image_id), Toast.LENGTH_SHORT).show();
stickyImage = new ImageView(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(Info.screenWidth, Info.screenWidth);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
stickyImage.setLayoutParams(params);
stickyImage.setImageDrawable(getResources().getDrawable(
Integer.parseInt(stickyItemId.get(stickyItemId.size() - 1).toString())));
stickyImage.setBackgroundResource(R.drawable.image_border);
stickyImage.setPadding(20, 20, 20, 20);
Bitmap bmap = loadBitmapFromView(stickyImage);
createStickyImage(bmap, 1);
setMainBottanEditBar();
}
}
public static Bitmap loadBitmapFromView(View v) {
Bitmap b = Bitmap.createBitmap(v.getLayoutParams().width,v.getLayoutParams().height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
v.draw(c);
return b;
}
void callDialogToGoHome() {
AlertDialog alert;
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(CatWangMain.this);
alertBuilder.setMessage("Are you sure you want to start over?");
alertBuilder.setPositiveButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alertBuilder.setNegativeButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();
}
});
alert = alertBuilder.create();
alert.show();
}
void callDialog_SaveToLib() {
AlertDialog alertSaveLIb;
AlertDialog.Builder alertBuilderSaveLib = new AlertDialog.Builder(
CatWangMain.this);
alertBuilderSaveLib.setTitle("OMG !");
alertBuilderSaveLib.setMessage("yo! we totally saved that graphic !");
alertBuilderSaveLib.setPositiveButton("Thanks",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alertSaveLIb = alertBuilderSaveLib.create();
alertSaveLIb.show();
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.img_new:
callDialogToGoHome();
break;
case R.id.img_save:
try {
mainImage.buildDrawingCache();
Bitmap viewBitmap1 = mainImage.getDrawingCache();
if (catWangMainImgLayout.getChildCount() > 1) {
join = madeJoinBitmap(viewBitmap1);
} else {
join = viewBitmap1;
}
} catch (Exception e) {
e.printStackTrace();
}
Intent intentFlip = new Intent(CatWangMain.this, SaveImage.class);
ByteArrayOutputStream blob = new ByteArrayOutputStream();
join.compress(CompressFormat.PNG, 80 , blob);
byte[] bitmapdata = blob.toByteArray();
intentFlip.putExtra("bitmap", bitmapdata);
startActivityForResult(intentFlip, FROM_SAVE_LIB);
break;
case R.id.img_cat:
Intent catWongItems = new Intent(this, CatWongStickyItems.class);
startActivityForResult(catWongItems, 10);
break;
default:
break;
}
}
private Bitmap madeJoinBitmap(Bitmap main) {
ImageView imageView = null;
Bitmap _bmp2 = null;
Bitmap bmOverlay = Bitmap.createBitmap(main.getWidth(), main.getHeight(), main.getConfig());
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(main, new Matrix(), null);
if (catWangMainImgLayout.getChildCount() > 1) {
for (int y = 0; y < sticky_list.size(); y++) {
imageView = (ImageView) sticky_list.get(y);
imageView.buildDrawingCache();
_bmp2 = imageView.getDrawingCache();
if((Matrix)Info.matrixList.get(y) != null)
{
canvas.drawBitmap(_bmp2, (Matrix)Info.matrixList.get(y),null);
}else {
canvas.drawBitmap(_bmp2, new Matrix(), null);
}
}
}
return bmOverlay;
}
void setMainBottanEditBar() {
editImage = (LinearLayout) findViewById(R.id.ll_edit);
editImage.setVisibility(View.VISIBLE);
rl_mainImageBottamBar1 = (RelativeLayout) findViewById(R.id.rl_bottam_bar);
rl_mainImageBottamBar1.setVisibility(View.INVISIBLE);
rl_mainImageBottamBar2 = (RelativeLayout) findViewById(R.id.rl_bottam_bar2);
rl_mainImageBottamBar2.setVisibility(View.VISIBLE);
carHead = (LinearLayout) findViewById(R.id.ll_catHead);
carHead.setVisibility(View.INVISIBLE);
done = (ImageView) findViewById(R.id.img_done);
done.setOnClickListener(doneListener);
back = (ImageView) findViewById(R.id.img_back);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
imageView_stky = (ImageView) catWangMainImgLayout.getChildAt(Info.current_matrix_id+1);
if(l==0)
{
imageView_stky.setAlpha(50);
l=1;
}
else
{
l=0;
imageView_stky.setAlpha(255);
}
setMainBottanEditBar();
} catch (Exception e) {
e.printStackTrace();
}
}
});
flip = (ImageView) findViewById(R.id.img_flip);
flip.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "flip.. in progress",Toast.LENGTH_SHORT).show();
}
});
trash = (ImageView) findViewById(R.id.img_trash);
trash.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
imageView_stky = (ImageView) catWangMainImgLayout.getChildAt(Info.current_matrix_id+1);
imageView_stky.setImageBitmap(null);
imageView_stky.setAlpha(255);
stickyImage = new ImageView(CatWangMain.this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
Info.screenWidth, Info.screenWidth);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
stickyImage.setLayoutParams(params);
stickyImage.setImageDrawable(getResources().getDrawable(Integer.parseInt((String)stickyItemId.get(index))));
stickyImage.setPadding(20, 20, 20, 20);
sticky_list.add(stickyImage);
Bitmap bmap2 = loadBitmapFromView(stickyImage);
imageView_stky.setOnTouchListener(null);
imageView_stky.setOnTouchListener(onTouchListenerStickImage);
imageView_stky.setImageBitmap(bmap2);
setSelectStickyMode();
Info.addMat(Pinch.matrix, Info.current_matrix_id);
Pinch.editMood = false;
Info.sticky_param.set(Info.current_matrix_id,new SavedStickyImageParam(Info.ceterOfX, Info.ceterOfY, Info.widthAfterZoom, Info.rotation));
catWangMainImgLayout.removeViewAt(catWangMainImgLayout.getChildCount() - 1);
catWangMainImgLayout.invalidate();
stickyItemId.remove(index);
setSelectStickyMode();
sticky_list.remove(index);
Info.sticky_param.remove(index);
Info.deleteMat(index);
Info.current_matrix_id = Info.current_matrix_id - 1;
index=index-1;;
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
void setSelectStickyMode() {
editImage = (LinearLayout) findViewById(R.id.ll_edit);
editImage.setVisibility(View.INVISIBLE);
rl_mainImageBottamBar1 = (RelativeLayout) findViewById(R.id.rl_bottam_bar);
rl_mainImageBottamBar1.setVisibility(View.VISIBLE);
rl_mainImageBottamBar2 = (RelativeLayout) findViewById(R.id.rl_bottam_bar2);
rl_mainImageBottamBar2.setVisibility(View.INVISIBLE);
carHead = (LinearLayout) findViewById(R.id.ll_catHead);
carHead.setVisibility(View.VISIBLE);
}
private Bitmap decodeFile(File f) {
try {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
final int REQUIRED_SIZE = 70;
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE
&& o.outHeight / scale / 2 >= REQUIRED_SIZE) scale *= 2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}
}
///////////////////////////////////////
public class Info {
static int screenWidth = CatWangMain.width, screenHight, stickyImageID = 90;
static OnTouchListener onTch;
public static ArrayList matrixList;
public static Point p1;
public static Point p2;
public static int ceterOfX, ceterOfY, widthAfterZoom = screenWidth, rotation;
public static ArrayList sticky_param;// = new ArrayList();;
public static int current_matrix_id = -1;
public static boolean checkPointInRect(float rx, float ry, int rw, int rh, int rot, float px, float py, boolean x){
double rotRad = (Math.PI * rot) / 180;
double dx = px - rx;
double dy = py - ry;
double h1 = Math.sqrt(dx * dx + dy * dy);
double currA = Math.atan2(dy,dx);
double newA = currA - rotRad;
double x2 = Math.cos(newA) * h1;
double y2 = Math.sin(newA) * h1;
if (x2 > - 0.5 * rw && x2 < 0.5 * rw && y2 > - 0.5 * rh && y2 < 0.5 * rh)
return true;
return false;
}
public static void addMat(Matrix m){
if(matrixList == null){
matrixList = new ArrayList();
}
}
public static void addMat(Matrix m, int position){
matrixList.set(position, m);
}
public static void deleteMat(int pos){
matrixList.remove(pos);
}
public static Matrix getMat(int pos){
return (Matrix)matrixList.get(pos);
}
public static int getMatrixSize(){
return matrixList.size();
}
}
////////////////////////////////////
public class Pinch //implements OnTouchListener
{
public static Matrix matrix = new Matrix();
public static Matrix savedMatrix = new Matrix();
RelativeLayout parent;
Activity context;
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE, preRotate, rotate;
public int x,y;
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
private boolean singleTouch;
public static float scale = 1;
public static int drag_x_value = Info.screenWidth/2, drag_y_value = Info.screenWidth/2;
public static boolean editMood;
OnTouchListener touchLis = new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
ImageView view = (ImageView) v;
dumpEvent(event);
}else {
Info.ceterOfX = (int)mid.x;
Info.ceterOfY = (int)mid.y;
}
case MotionEvent.ACTION_POINTER_UP:
return true; // indicate event was handled
}
};
public Pinch(Activity context, RelativeLayout parent) {
this.context = context;
this.parent = parent;
}
public ImageView addImage(Bitmap image, int id) {
matrix = new Matrix();
ImageView tempImage = new ImageView(context);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
tempImage.setId(Info.stickyImageID);
Info.stickyImageID = Info.stickyImageID + 1;
tempImage.setImageBitmap(image);
tempImage.setLayoutParams(params);
Info.onTch = touchLis;
tempImage.setOnTouchListener(Info.onTch);
matrix.postScale(01.00f, 01.00f);
tempImage.setScaleType(ScaleType.MATRIX);
tempImage.setImageMatrix(matrix);
Info.ceterOfY = Info.ceterOfX;
Info.addMat(Pinch.matrix);
Info.current_matrix_id = Info.getMatrixSize()-1;
Info.sticky_param.add(new SavedStickyImageParam(Info.ceterOfX, Info.ceterOfY, Info.widthAfterZoom, Info.rotation));
parent.addView(tempImage);
return tempImage;
}
set the tag by setTag() for each image view then, in On Click Event u can select the image by getTag()..