Unable to imlement drag and drop - android

I am trying to make a alphabet exam. I have a ImageView11 which shows the a random alphabet which you have to guess. And the imageView_alphabet_image_1 and imageView_alphabet_image_2 will show two options which I have to guess and I will drag the ImageView11 image on correct ImageView which is showing down. But I'm able to do it for only first time when i click on refresh it always showing incorrect toast
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btn_refresh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Refresh"/>
<LinearLayout
android:id="#+id/dragLinearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imgView_des"
android:layout_width="70dp"
android:layout_height="80dp"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<LinearLayout
android:id="#+id/bottomLinearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:orientation="horizontal"
android:weightSum="1" >
<ImageView
android:id="#+id/imgView_alphabetImage_1"
android:layout_width="70dp"
android:layout_height="80dp"
android:layout_weight="0.25"
android:src="#drawable/a" />
<ImageView
android:id="#+id/imgView_alphabetImage_2"
android:layout_width="70dp"
android:layout_height="80dp"
android:layout_weight="0.25"
android:src="#drawable/a" />
</LinearLayout>
package com.example.cleardoubt;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.DragEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.DragShadowBuilder;
import android.view.View.OnClickListener;
import android.view.View.OnDragListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements OnClickListener,
OnTouchListener, OnDragListener {
private ImageView _imgView_des;
private ImageView _imgView_alphabetImage_1;
private ArrayList<Integer> _alphabet_arrayList;
private Button _btn_refresh;
private ImageView _imgView_alphabetImage_2;
private ArrayList<Integer> _tempArrayList;
private ArrayList<Integer> _finalTempArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initView();
setContentView(R.layout.activity_main);
_imgView_des = (ImageView) findViewById(R.id.imgView_des);
_imgView_des.setOnClickListener(this);
_imgView_des.setOnTouchListener(this);
_imgView_des.setOnDragListener(this);
_imgView_alphabetImage_1 = (ImageView) findViewById(R.id.imgView_alphabetImage_1);
_imgView_alphabetImage_1.setOnClickListener(this);
_imgView_alphabetImage_1.setOnDragListener(this);
_imgView_alphabetImage_2 = (ImageView) findViewById(R.id.imgView_alphabetImage_2);
_imgView_alphabetImage_2.setOnClickListener(this);
_imgView_alphabetImage_2.setOnDragListener(this);
_btn_refresh = (Button) findViewById(R.id.btn_refresh);
_btn_refresh.setOnClickListener(this);
}
private void initView() {
_alphabet_arrayList = new ArrayList<Integer>();
_alphabet_arrayList.add(R.drawable.a);
_alphabet_arrayList.add(R.drawable.b);
_alphabet_arrayList.add(R.drawable.c);
_alphabet_arrayList.add(R.drawable.d);
_alphabet_arrayList.add(R.drawable.e);
_alphabet_arrayList.add(R.drawable.f);
_alphabet_arrayList.add(R.drawable.g);
_tempArrayList = new ArrayList<Integer>();
_finalTempArrayList = new ArrayList<Integer>();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.imgView_des:
break;
case R.id.imgView_alphabetImage_1:
if (_imgView_des
.getDrawable()
.getConstantState()
.equals(_imgView_alphabetImage_1.getDrawable()
.getConstantState())) {
Toast.makeText(this, "matched", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "not matched", Toast.LENGTH_SHORT).show();
}
break;
case R.id.imgView_alphabetImage_2:
if (_imgView_des
.getDrawable()
.getConstantState()
.equals(_imgView_alphabetImage_2.getDrawable()
.getConstantState())) {
Toast.makeText(this, "matched", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "not matched", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btn_refresh:
Random random = new Random();
int index = random.nextInt(7);
_imgView_des.setImageResource(_alphabet_arrayList.get(index));
_imgView_des.setVisibility(View.VISIBLE);
_tempArrayList = (ArrayList<Integer>) _alphabet_arrayList.clone();
_tempArrayList.remove(index);
Collections.shuffle(_tempArrayList, random);
for (int j = 0; j < 1; j++) {
_finalTempArrayList.add(_tempArrayList.get(j));
}
_finalTempArrayList.add(_alphabet_arrayList.get(index));
Collections.shuffle(_finalTempArrayList);
Log.e(" _finalTempArrayList after suffel", _finalTempArrayList.toString());
_imgView_alphabetImage_1.setImageResource(_finalTempArrayList.get(0));
_imgView_alphabetImage_2.setImageResource(_finalTempArrayList.get(1));
_finalTempArrayList.clear();
break;
default:
break;
}
}
#Override
public boolean onTouch(View v, MotionEvent e) {
if (e.getAction() == MotionEvent.ACTION_DOWN) {
// ClipData clipData = ClipData.newPlainText("", "");
DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(v);
v.startDrag(null, shadowBuilder, v, 0);
v.setVisibility(View.INVISIBLE);
return true;
} else {
return false;
}
}
#Override
public boolean onDrag(View v, DragEvent e) {
switch (e.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
// if (e.getClipDescription().hasMimeType(
// ClipDescription.MIMETYPE_TEXT_PLAIN)) {
// return true;
// } else {
// Toast.makeText(this, "can not accept the image",
// Toast.LENGTH_SHORT).show();
//
// }
// return false;
break;
case DragEvent.ACTION_DROP:
if (_imgView_des
.getDrawable()
.getConstantState()
.equals(_imgView_alphabetImage_1.getDrawable()
.getConstantState())) {
ViewGroup viewGroup = (ViewGroup) v.getParent();
viewGroup.removeView(_imgView_des);
v.setBackground(this.getResources().getDrawable(R.drawable.a));
return true;
}
else if(_imgView_des
.getDrawable()
.getConstantState()
.equals(_imgView_alphabetImage_2.getDrawable()
.getConstantState()))
{
ViewGroup viewGroup = (ViewGroup) v.getParent();
viewGroup.removeView(_imgView_des);
v.setBackground(this.getResources().getDrawable(R.drawable.a));
return true;
}
// else {
// return false;
// }
break;
case DragEvent.ACTION_DRAG_ENDED:
Log.v("a", e.getResult() + "");
if (e.getResult()) {
_imgView_des.setVisibility(View.INVISIBLE);
Log.v("asddd", e.getResult() + "");
Toast.makeText(this, " accept the image",
Toast.LENGTH_SHORT).show();
return true;
} else {
_imgView_des.setVisibility(View.VISIBLE);
Toast toast = new Toast(this);
ImageView view = new ImageView(this);
view.setImageResource(R.drawable.unsuccess);
toast.setView(view);
toast.show();
return true;
}
default:
break;
}
return false;
}
}

I checked you code the problem is in your onDrag method.
case DragEvent.ACTION_DROP event did not call because of you did not return flag case DragEvent.ACTION_DRAG_STARTED: event. You have to pass true flag like below code
case DragEvent.ACTION_DRAG_STARTED:
return true;

Related

Navigation Drawer menu items aren't clickable [duplicate]

This question already has answers here:
NavigationView OnNavigationItemSelectedListener not being called
(3 answers)
setNavigationItemSelectedListener Not Working
(3 answers)
Closed 2 years ago.
Nothing is happening when I'm selecting any option from the navigation drawer. As soon as I click on the navigation drawer the drawer closes. I'll add my GitHub repository link also if you want to try correcting from there you are very much welcome:
https://github.com/tanmay380/andorid-studio-
This is my alphabetBaseShow class which shows the Navigation Drawer (I'll delete some of the lines so that it uses less space)
package com.example.myapplication.background;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Environment;
import android.speech.tts.TextToSpeech;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.myapplication.R;
import com.example.myapplication.infront.CharacterSelection;
import com.example.myapplication.infront.SplashScreen;
import com.software.shell.fab.ActionButton;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
public class alphabetBaseShow extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
protected String mPracticeString;
protected DrawingView mDrawView;
public SeekBar seekBar;
Button button;
public boolean draw = true;
AudioManager audio;
protected TextView mScoreTimerView;
protected TextView mBestScoreView;
protected boolean mDone;
public AlertDialog.Builder alertDialog;
private static final int STORAGE_PERMISSION_CODE = 101;
public TextView colorset;
public NavigationView navigationView;
//private TextToSpeech textToSpeech;
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
System.gc();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alphabet_show);
Toolbar toolbar = findViewById(R.id.PracticeToolbar);
setSupportActionBar(toolbar);
// textToSpeech=new TextToSpeech(this,LanguageSelection);
drawerLayout = findViewById(R.id.drawerLayout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.close, R.string.open);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDrawView = new DrawingView(this);
seekBar = findViewById(R.id.size1);
mDrawView = findViewById(R.id.DrawingView);
mBestScoreView = (TextView) findViewById(R.id.best_score_View);
mScoreTimerView = (TextView) findViewById(R.id.score_and_timer_View);
mPracticeString = getIntent().getStringExtra(getResources().getString(R.string.practice_string));
mDone = false;
mScoreTimerView.bringToFront();
mDrawView.canVibrate(true);
mDrawView.setBitmapFromText(mPracticeString);
audio = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
/*switch (audio.getStreamVolume(AudioManager.STREAM_MUSIC)) {
case AudioManager.RINGER_MODE_SILENT:
Toast.makeText(getApplicationContext(), "TURN UP THE VOLUME", Toast.LENGTH_SHORT).show();
}*/
if ((audio.getStreamVolume(AudioManager.STREAM_MUSIC) > 1)) {
SplashScreen.TTSobj.speak(mPracticeString, TextToSpeech.QUEUE_FLUSH, null, null);
}
else if (audio.getStreamVolume(AudioManager.STREAM_MUSIC) == 0) {
audio.setStreamVolume(AudioManager.STREAM_MUSIC, 10, 1);
SplashScreen.TTSobj.speak(mPracticeString, TextToSpeech.QUEUE_FLUSH, null, null);
}
}
catch (Exception e) {
showErrorDialog(e);
}
}
private void toggleSeekbar() {
if (seekBar.getVisibility() == View.INVISIBLE) {
seekBar.setVisibility(View.VISIBLE);
seekBar.bringToFront();
mDrawView.candraw(false);
}
else {
seekBar.setVisibility(View.INVISIBLE);
mDrawView.candraw(true);
}
}
public void clickit() {
toggleSeekbar();
setSize();
}
public void setSize() {
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
mDrawView.setCurrentWidth(progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
toggleSeekbar();
}
});
return;
}
public void practiceOnClick(View v) {
switch (v.getId()) {
case R.id.reset:
if (mDone) {
mDrawView.init();
}
mDrawView.setBitmapFromText(mPracticeString);
mBestScoreView.setAnimation(Animator.createFadeOutAnimation());
mDrawView.startAnimation(Animator.createScaleUpAnimation());
mScoreTimerView.setAnimation(Animator.createFadeOutAnimation());
Animator.createYFlipForwardAnimation(findViewById(R.id.done));
((ActionButton) findViewById(R.id.done)).setImageResource(R.drawable.ic_done);
Animator.createYFlipBackwardAnimation(findViewById(R.id.done));
mDone = false; //implies that the user isn't done
mDrawView.candraw(true);
break;
case R.id.done:
String result = mDrawView.saveBitmap(mPracticeString, "");
if (result.charAt(0) == '/')
result = "Trace Saved";
Toast.makeText(this, result, Toast.LENGTH_SHORT).show(); // Toast displayed with the status of saving the trace
if (!mDone) {
float best = SplashScreen.mDbHelper.getScore(mPracticeString);
if (best < mDrawView.score()) {
best = mDrawView.score();
SplashScreen.mDbHelper.writeScore(mPracticeString, best);
}
//Animations for when the user is done with the trace
mDrawView.startAnimation(Animator.createScaleDownAnimation());
findViewById(R.id.best_score_View).bringToFront();
((TextView) findViewById(R.id.best_score_View)).setText("Best: " + String.valueOf(best));
mScoreTimerView.setText("Score: " + String.valueOf(mDrawView.score()));
mScoreTimerView.setAnimation(Animator.createFadeInAnimation());
mBestScoreView.setAnimation(Animator.createFadeInAnimation());
Animator.createYFlipForwardAnimation(findViewById(R.id.done));
((ActionButton) findViewById(R.id.done)).setImageResource(R.drawable.ic_save);
Animator.createYFlipBackwardAnimation(findViewById(R.id.done));
mDrawView.candraw(false);
mDone = true;
}
}
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (!mDone) {
int next = Arrays.asList(SplashScreen.CHARACTER_LIST).indexOf(mPracticeString);
switch (item.getItemId()) {
case R.id.action_next:
next = (next + 1) % SplashScreen.CHARACTER_LIST.length;
break;
case R.id.action_previous:
next = (next + SplashScreen.CHARACTER_LIST.length - 1) % SplashScreen.CHARACTER_LIST.length;
break;
case R.id.setting:
clickit();
break;
}
if (item.getItemId() == R.id.action_next || item.getItemId() == R.id.action_previous) {
mPracticeString = SplashScreen.CHARACTER_LIST[next];
mDrawView.setBitmapFromText(mPracticeString);
SplashScreen.TTSobj.speak(mPracticeString, TextToSpeech.QUEUE_FLUSH, null, null);
}
}
return super.onOptionsItemSelected(item);
}
protected void showErrorDialog(final Exception e) {
new AlertDialog.Builder(this)
.setTitle("ERROR")
.setMessage(Log.getStackTraceString(e))
.setPositiveButton("Save to File", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + File.separator + getResources().getString(R.string.app_name));
File file = new File(mediaStorageDir.getPath() + File.separator + "error.txt");
if (file.exists() || file.createNewFile()) {
FileOutputStream fOut = new FileOutputStream(file, true);
fOut.write(("\n\n" + new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault()).format(new Date()) + "\n\n").getBytes());
fOut.write(Log.getStackTraceString(e).getBytes());
fOut.flush();
fOut.close();
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int id = menuItem.getItemId();
switch (id) {
case R.id.green:
SplashScreen.TTSobj.speak(mPracticeString, TextToSpeech.QUEUE_FLUSH, null, null);
break;
case R.id.red:
Toast.makeText(getApplicationContext(), "REd", Toast.LENGTH_SHORT).show();
break;
case R.id.black:
Toast.makeText(getApplicationContext(), "REd", Toast.LENGTH_SHORT).show();
break;
case R.id.blue:
Toast.makeText(getApplicationContext(), "REd", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
}
This is my XML file (deleted some Textview lines as they were not important hence less space will be required):
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".background.alphabetBaseShow">
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:layout_marginTop="55dp"
app:headerLayout="#layout/header"
app:menu="#menu/colors"
android:clickable="true">
</android.support.design.widget.NavigationView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="#+id/PracticeToolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/ActionbarBg"
app:title="PRACTICE " />
<com.example.myapplication.background.DrawingView
android:id="#+id/DrawingView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="50dp" />
<com.software.shell.fab.ActionButton
android:id="#+id/done"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="0dp"
android:layout_marginRight="0dp"
android:layout_marginBottom="0dp"
android:onClick="practiceOnClick"
app:button_color="#color/ButtonBg"
app:image="#drawable/ic_done" />
<com.software.shell.fab.ActionButton
android:id="#+id/reset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentBottom="true"
android:onClick="practiceOnClick"
app:button_color="#color/ButtonBg"
app:image="#drawable/ic_reset" />
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
This is my colors.xml (menu file). I've even tried to add onClick inside item, but it didn't work:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/green"
android:icon="#drawable/ic_save"
android:title="GREEN" />
<item
android:id="#+id/black"
android:icon="#drawable/ic_save"
android:title="BLACK" />
<item
android:id="#+id/blue"
android:icon="#drawable/ic_save"
android:title="BLUE" />
<item
android:id="#+id/red"
android:icon="#drawable/ic_save"
android:title="RED"
android:onClick="toast"/>
</group>
</menu>
Created a pull request to your repository. Check out.
P.S.:
You should have used the same version of support and design libraries
Do not use System.gs (!)
The main reason why your navigation item click listener did not work was - you did not assign your interface implementation,
navigationView.setNavigationItemSelectedListener(this);
instead of
navigationView.setNavigationItemSelectedListener(new OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Some stuff here
}
});
as you have implemented the interface NavigationView.OnNavigationItemSelectedListener.
I just need to put the NAVIGATIONDRAWER part at the end.

Set Click to two different triangular images in a single layout

I tried to set click to the triangular images placed as shown in figure. But the problem is only one image click is working. And I have implemented as follows:
<ImageView
android:id="#+id/twoWheeler" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/front_screen_design_twowheeler"
android:scaleType="fitStart"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fourWheeler"
android:src="#drawable/front_screen_design_fourwheeler"
android:scaleType="fitEnd" />
two.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(MainActivity.this,BikeActivity.class);
startActivity(i);
}
});
four.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(MainActivity.this,FourActivity.class);
startActivity(i);
}
});
As you have mentioned in your question I have created the same example for your solution.
I have used two images with half transparent area.
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rlParent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/triangle" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/triangle2" />
</RelativeLayout>
MainActivity.java
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ImageView imageView, imageView1;
private RelativeLayout rlParent;
private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
rlParent = (RelativeLayout) findViewById(R.id.rlParent);
imageView = (ImageView) findViewById(R.id.imageView);
imageView1 = (ImageView) findViewById(R.id.imageView1);
rlParent.setOnTouchListener(new MyTouchListener(rlParent, this));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.imageView:
showToast("Image 1 Click");
break;
case R.id.imageView1:
showToast("Image 2 Click");
break;
}
}
private class MyTouchListener implements View.OnTouchListener {
private ViewGroup viewGroup;
private View.OnClickListener onClickListener;
public MyTouchListener(ViewGroup viewGroup, View.OnClickListener onClickListener) {
this.viewGroup = viewGroup;
this.onClickListener = onClickListener;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
for (int pos = 0; pos < viewGroup.getChildCount(); pos++) {
View view = viewGroup.getChildAt(pos);
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
int x = (int) event.getX();
int y = (int) event.getY();
if (bitmap.getPixel(x, y) != Color.TRANSPARENT) {
if (onClickListener != null) {
onClickListener.onClick(view);
break;
}
}
}
break;
}
return true;
}
}
}
You can check below screenshots to check particular image click,
Screenshots
I hope it helps you.
The thing with imageview is it takes a rectangular space. So in your case one imageview is placed above another thus only one imageview is clicked. to achieve that you need to create custom class to implement triangular imageview click try this or look for custom imageview...
You can wrap them in a FrameLayout
framelayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
//calculate the position by event.getX(),event.getY();
if(point in triOne){
}else{
}
return true;
}
});

check if the right radioButton is checked and calculate the score

i have an android application that display a flag and group of radio buttons that each time the user check any radio button the application will display a button that allow to go to the next page using intent .
what i need is that each time the user check the right answer the system must calculate its score until the application finish .
the score will start by 0/0 and will finish after four rounds.
for now i need just to display the score of the user in the second page
i will appreciate any help
MainActivity.java
package com.devleb.flagology;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btnS;
RadioGroup rdgS;
RadioButton rdS1, rdS2, rdS3, rdS4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rdgS = (RadioGroup) findViewById(R.id.rdg1);
rdgS.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
if(rdS1.isChecked()||rdS2.isChecked()||rdS3.isChecked()||rdS4.isChecked()){
btnS.setVisibility(View.VISIBLE);
}
}
});
rdS1 = (RadioButton) findViewById(R.id.rd_s1);
rdS2 = (RadioButton) findViewById(R.id.rd_s2);
rdS3 = (RadioButton) findViewById(R.id.rd_s3);
rdS4 = (RadioButton) findViewById(R.id.rd_s4);
btnS = (Button) findViewById(R.id.btn_s);
btnS.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String input;
String result = null;
Double dbl;
Intent i = new Intent(MainActivity.this, SecondActivity.class);
switch (v.getId()) {
case R.id.rd_s1:
input = rdS1.getText().toString();
dbl = Double.parseDouble(input);
i.putExtra("score", 0);
break;
case R.id.rd_s2:
i.putExtra("score", 0);
break;
case R.id.rd_s3:
i.putExtra("score", 25);
break;
case R.id.rd_s4:
i.putExtra("score", 0);
break;
default:
break;
}
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.hint_icon:
ShowAlertDialog();
break;
case R.id.about_icon:
Toast.makeText(this, "developed by Georges Matta",
Toast.LENGTH_SHORT).show();
default:
break;
}
return super.onOptionsItemSelected(item);
}
public void ShowAlertDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Hint")
.setMessage("The famouse sport is Bullfighting")
.setCancelable(false)
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
edited code
rdS1 = (RadioButton) findViewById(R.id.rd_s1);
rdS2 = (RadioButton) findViewById(R.id.rd_s2);
rdS3 = (RadioButton) findViewById(R.id.rd_s3);
rdS4 = (RadioButton) findViewById(R.id.rd_s4);
btnS = (Button) findViewById(R.id.btn_s);
btnS.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String input;
String result = null;
Double dbl;
Intent i = new Intent(MainActivity.this, SecondActivity.class);
switch (rdgS.getCheckedRadioButtonId()) {
case R.id.rd_s1:
input = rdS1.getText().toString();
dbl = Double.parseDouble(input);
result = String.valueOf(dbl);
i.putExtra("score", result);
break;
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="34dp"
android:src="#drawable/spanish" />
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/imageView1"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Gess the Country of the flag"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#CCFF99" />
<RadioGroup
android:id="#+id/rdg1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/imageView1" >
<RadioButton
android:id="#+id/rd_s1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Egypt"
android:textColor="#CCFF99" />
<RadioButton
android:id="#+id/rd_s2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="China"
android:textColor="#CCFF99" />
<RadioButton
android:id="#+id/rd_s3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Spanish"
android:textColor="#CCFF99" />
<RadioButton
android:id="#+id/rd_s4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/radioGroup1"
android:layout_below="#+id/radioGroup1"
android:text="Italy"
android:textColor="#CCFF99" />
</RadioGroup>
<Button
android:id="#+id/btn_s"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/rdg1"
android:layout_below="#+id/rdg1"
android:text="Next"
android:visibility="invisible" />
</RelativeLayout>
SecondActivity.java
package com.devleb.flagology;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class SecondActivity extends Activity {
TextView txt_result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
txt_result = (TextView) findViewById(R.id.txtResult);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("score");
txt_result.setText(value);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
}
activity_second.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".SecondActivity" >
<TextView
android:id="#+id/txtResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Simple solution is to modify your switch case as follows:
...
Intent i = new Intent(MainActivity.this, SecondActivity.class);
switch (rdgS.getCheckedRadioButtonId()) {
case R.id.rd_s1:
input = rdS1.getText().toString();
dbl = Double.parseDouble(input);
i.putExtra("score", 0);
break;
case R.id.rd_s2:
i.putExtra("score", 0);
break;
case R.id.rd_s3:
i.putExtra("score", 25);
break;
case R.id.rd_s4:
i.putExtra("score", 0);
break;
default:
break;
}
startActivity(i);
...
...
After this since your are passing in int values, you should use getInt() method. In your oncreate of SecondActivity do this:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = String.valueOf(extras.getInt("score"));
txt_result.setText(value);
}
There is a problem here:
Intent intent = new Intent(MainActivity.this, SecondPage.class);
intent.putExtra("showResult", result);
startActivity(intent);
This should match extras.getString("score"); string in the second activity, so change it to:
Intent intent = new Intent(MainActivity.this, SecondPage.class);
intent.putExtra("score", result);
startActivity(intent);
In your onClick(View v) handler, v refers to the button btn_s, therefore switch (v.getId()) will not work since v.getId() will always return id of the button, i.e. R.id.btn_s.
You need to query states of the radio button separately, for example use
if (rdS1.isChecked()) {
// first ratio button is checked
} else if (rdS2.isChecked()) {
// second is checked
} else if ...
Replace your switch (v.getId()) in onClick(View v) with that if.

error: Binary XML file line#3: You must supply a layout width attribute

i'va already read all answers related with these questions and I'm sure none solves my problem, I'm getting crazy with this error, please any help would be appreciated
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dip"
android:orientation="vertical" >
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/title_scaned_value"/>
<TextView
android:id="#+id/scanedFormat"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/title_scaned_value_empty"/>
<TextView
android:id="#+id/scanedValue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/title_scaned_value_empty"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="#string/title_scan"
android:onClick="commandScan"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="productes"
android:onClick="productes"/>
My activity related with this layout works fine, but when i click a button to start another activity this error appears.
I'm workin with Zxing library and here's my CaptureActivity:
package org.example.sherlock_;
import org.example.sherlock_.helpers.ExceptionHelper;
import android.content.Intent;
import android.graphics.Bitmap;
import com.google.zxing.Result;
import com.google.zxing.client.android.result.ResultHandler;
public class CaptureActivity extends com.google.zxing.client.android.CaptureActivity {
#Override
public void handleDecodeInternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {
//super.handleDecodeInternally(rawResult, resultHandler, barcode);
try {
Intent resultIntent = new Intent();
resultIntent.putExtra(com.google.zxing.client.android.Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
resultIntent.putExtra(com.google.zxing.client.android.Intents.Scan.RESULT, resultHandler.getDisplayContents());
setResult(RESULT_OK, resultIntent);
finish();
} catch (Exception e) {
ExceptionHelper.manage(this, e);
}
}
}
I post my MainActivity too because I'm going really mad :)
package org.example.sherlock_;
import org.example.sherlock_.helpers.ExceptionHelper;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
public class MainActivity extends SherlockActivity {
private TextView scanedValue;
private TextView scanedFormat;
private final static int SCAN_CODE_REQUEST_CODE = 123456;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scanedValue = (TextView)findViewById(R.id.scanedValue);
scanedFormat = (TextView)findViewById(R.id.scanedFormat);
}
#Override
protected void onActivityResult(int pRequestCode, int pResultCode, Intent pData) {
try {
if (pRequestCode == SCAN_CODE_REQUEST_CODE) {
if (pResultCode == RESULT_OK) {
String result = pData.getStringExtra
(com.google.zxing.client.android.Intents.Scan.RESULT);
String format = pData.getStringExtra
(com.google.zxing.client.android.Intents.Scan.RESULT_FORMAT);
if (scanedValue != null) {
if (result != null &&
!result.trim().equals("")) {
scanedValue.setText(result);
//if(db != null){
//String valor= result ;
//}
} else {
scanedValue.setText(getString(R.string.title_scaned_value_empty));
}
}
if (scanedFormat != null) {
if (format != null &&
!format.trim().equals("")) {
scanedFormat.setText(format);
//if(db != null){
//String tipus = format;
//}
} else {
scanedFormat.setText(getString(R.string.title_scaned_value_empty));
}
}
} else {
if (scanedValue != null)
scanedValue.setText(getString(R.string.title_scaned_value_empty));
if (scanedFormat != null)
scanedFormat.setText(getString(R.string.title_scaned_value_empty));
}
}
//Insertamos los datos en la tabla Usuarios
// db.execSQL("INSERT INTO Productes (codi, tipus, valor) " +
// "VALUES (" + i + ", '" + tipus +"', '"+ valor +"')");
// db.close();
//i+=i;
} catch (Exception e) {
ExceptionHelper.manage(this, e);
}
}
public void commandScan(View pView) {
try {
Intent captureIntent = new Intent(this, CaptureActivity.class);
captureIntent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(captureIntent, SCAN_CODE_REQUEST_CODE);
} catch (Exception e) {
ExceptionHelper.manage(this, e);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_settings) {
Toast.makeText(this, "configuraciĆ³n pulsado"
, Toast.LENGTH_SHORT).show();
}
return true;
}
}

Creating a multi leveled listview application

So here is the code. Its pretty self explanatory. The only problem I am having is retaining the value for int level. Its lost every time. I need the value to be retained and it will work. This is a snapshot. It should be extensible to as many levels deep and as many items per level.
XML code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity" >
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
Java code:
package com.example.kjkjsdkjdsjkdfs;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends ListActivity {
String categoryselected = "main";
public int level = 0;
#SuppressWarnings("null")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] array;
Intent received = getIntent();
// Setup as main ListView
if (received == null || !received.hasExtra("array")) {
array = new String[] { "1", "2", "3" };
}
// Setup as sub ListView
else {
array = received.getStringArrayExtra("array");
}
if(received != null || !received.hasExtra("level")) {
level = received.getIntExtra("level", 0);
}
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
level = level + 1;
Intent starting = new Intent(MainActivity.this, MainActivity.class);
switch (level) {
case 1:
switch (position) {
case 0:
starting.putExtra("array", new String[] { "1a", "1b", "1c" });
starting.putExtra("level", level);
break;
case 1:
starting.putExtra("array", new String[] { "2a", "2b", "2c" });
starting.putExtra("level", level);
break;
case 2:
starting.putExtra("array", new String[] { "3a", "3b", "3c" });
starting.putExtra("level", level);
break;
}
break;
case 2:
switch (position) {
case 0:
starting.putExtra("array", new String[] { "1aa", "1ab" });
starting.putExtra("level", level);
break;
}
break;
case 3:
switch (position) {
case 0:
starting.putExtra("array", new String[] { "1aaa", "1aab" });
starting.putExtra("level", level);
break;
}
break;
}
startActivity(starting);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Update your code like this :
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ListItems extends ListActivity {
String categoryselected = "main";
public int level = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] array;
Intent received = getIntent();
// Setup as main ListView
if (received == null || !received.hasExtra("array")) {
array = new String[] { "1", "2", "3" };
}
// Setup as sub ListView
else {
array = received.getStringArrayExtra("array");
}
if(received != null || !received.hasExtra("level")) {
level = received.getIntExtra("level", 0);
}
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
level = level + 1;
Intent starting = new Intent(ListItems.this, ListItems.class);
switch (level) {
case 1:
switch (position) {
case 0:
starting.putExtra("array", new String[] { "1a", "1b", "1c" });
starting.putExtra("level", level);
break;
case 1:
starting.putExtra("array", new String[] { "2a", "2b", "2c" });
starting.putExtra("level", level);
break;
case 2:
starting.putExtra("array", new String[] { "3a", "3b", "3c" });
starting.putExtra("level", level);
break;
}
break;
case 2:
switch (position) {
case 0:
starting.putExtra("array", new String[] { "1aa", "1ab" });
starting.putExtra("level", level);
break;
}
break;
case 3:
switch (position) {
case 0:
starting.putExtra("array", new String[] { "1aaa", "1aab" });
starting.putExtra("level", level);
break;
}
break;
}
startActivity(starting);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

Categories

Resources