"Swipe Detection" attached to textview is malfunctioning - java

I am trying to detect "Left Swipe", "Right Swipe" and "Down Swipe".
Please have a look at the Following code
ParagraphReader.java
package k.k;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import android.os.Bundle;
import android.app.Activity;
import android.speech.tts.TextToSpeech;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class ParagraphReader extends Activity implements TextToSpeech.OnInitListener {
private TextView paraText;
private TextView paraListQuestionIndicator;
private ImageView speaker;
private DatabaseConnector database;
private List<String>paraList;
private int currentQuestion;
private TextToSpeech tts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paragraph_reader);
paraText = (TextView)findViewById(R.id.paragraph_reader_txt);
paraText.setOnTouchListener(paraSwiped);
paraListQuestionIndicator = (TextView)findViewById(R.id.paralist_question_indicator);
speaker = (ImageView)findViewById(R.id.speak);
speaker.setOnClickListener(new SpeakOutTheText());
paraList = new ArrayList<String>();
database = DatabaseHandler.getInstance(this);
tts = new TextToSpeech(this,this);
//Get the Paragraph list
int listNumber = getIntent().getIntExtra("PARAGRAPH_LIST", 0);
//Toast.makeText(this, "Selected Paragraph: "+listNumber, Toast.LENGTH_LONG).show();
paraList = database.getParagraphList(listNumber);
//Toast.makeText(this, "ParaList size "+paraList.size(), Toast.LENGTH_LONG).show();
//Toast.makeText(this, "Size: "+paraList.size(), Toast.LENGTH_LONG).show();
paraText.setText(paraList.get(0));
setParaListQuestionIndicator(currentQuestion);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.paragraph_reader, menu);
return true;
}
//The Event Handler for the Paragraph Text holder
OnTouchListener paraSwiped = new OnSwipeTouchListener()
{
public boolean onSwipeRight()
{
//Toast.makeText(ParagraphReader.this, "Right: "+paraList.size(), Toast.LENGTH_SHORT).show();
currentQuestion--;
if(currentQuestion<0)
{
currentQuestion = paraList.size()-1;
}
paraText.setText(paraList.get(currentQuestion));
setParaListQuestionIndicator(currentQuestion);
return true;
}
public boolean onSwipeLeft()
{
//Toast.makeText(ParagraphReader.this, "Left: "+paraList.size(), Toast.LENGTH_SHORT).show();
currentQuestion++;
if(currentQuestion>paraList.size()-1)
{
currentQuestion = 0;
}
paraText.setText(paraList.get(currentQuestion));
setParaListQuestionIndicator(currentQuestion);
return true;
}
public boolean onSwipeBottom()
{
return true;
}
};
private class SpeakOutTheText implements OnClickListener
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
speak(paraText.getText().toString());
}
}
private void setParaListQuestionIndicator(int number)
{
paraListQuestionIndicator.setText((number+1)+"/"+paraList.size());
}
#Override
public void onInit(int status)
{
// TODO Auto-generated method stub
if(status==TextToSpeech.SUCCESS)
{
int result = tts.setLanguage(Locale.UK);
if(result==TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED)
{
Toast.makeText(this, "Language Not Supported", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onDestroy()
{
if(tts!=null)
{
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
public void speak(String text)
{
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
ParagraphReader.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=".ParagraphReader" >
<ScrollView
android:id="#+id/paragraph_reader_scroll_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/paragraph_reader_txt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="200dp"
android:ems="30"
android:singleLine="false"
android:clickable="true"
>
</TextView>
</ScrollView>
<TextView
android:id="#+id/paralist_question_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageView
android:id="#+id/speak"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginRight="20dp"
android:src="#drawable/speaker2" />
</RelativeLayout>
And the Gesture detection code,
OnSwipeTouchListener.java
This code is from here
package k.k;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class OnSwipeTouchListener implements OnTouchListener {
private final GestureDetector gestureDetector = new GestureDetector(new GestureListener());
public boolean onTouch(final View v, final MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
private final class GestureListener extends SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
#Override
public boolean onDown(MotionEvent e) {
return super.onDown(e);
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
boolean result = false;
try {
float diffY = e2.getY() - e1.getY();
float diffX = e2.getX() - e1.getX();
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
result = onSwipeRight();
} else {
result = onSwipeLeft();
}
}
} else {
if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
if (diffY > 0) {
result = onSwipeBottom();
} else {
result = onSwipeTop();
}
}
}
} catch (Exception exception) {
exception.printStackTrace();
}
return result;
}
}
public boolean onSwipeRight() {
return false;
}
public boolean onSwipeLeft() {
return false;
}
public boolean onSwipeTop() {
return false;
}
public boolean onSwipeBottom() {
return false;
}
}
This code works fine as it should in Virtual Device, but to my surprise, it is not working on real device! I have Micromax Canvas2, and I tested with my phone and HP phone, in both this is not working.
Not working means, I think it do not identify any of the swipes properly. "Sometimes" it does swipe to left and right, but that is "sometimes" and for that also I had to drag it very hard 3-4 times.
What is wrong here? This is not working because I implemented the listener to a TextView?
PS: I posted the completed related classes here because last time it was impossible to get a suitable answer with code removed.

I found the answer. The case is, here what I have is a ScrollView which is by default responding to swipes and my text view was inside that. So, the only fix was taking the TextView out of the ScrollView.

Did you try to wrap the TextView in a container (Linear/RelativeLayout) and implement the listener to the container?
For example:
...
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/paragraph_reader_txt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="200dp"
android:ems="30"
android:singleLine="false"
android:clickable="true"
>
</TextView>
</LinearLayout>
...
and then:
LinearLayout parag = (LinearLayout)findViewById(R.id.container);
parag.setOnTouchListener(paraSwiped);
EDIT:
I used swipe like so:
parag.setOnTouchListener(new OnSwipeTouchListener(){
public boolean onSwipeRight(){
//your stuff
return true;
}
public boolean onSwipeLeft(){
//your stuff
return true;
}
...
});
It works for me

Related

Audio stops after startBluetoothSco in Android 11

The moment I bind an Android 11 device using startBluetoothSco I loose audio. It works fine till Android 10
Sample code I tried with below.
Audio works as it should when i do not bind using startBluetoothSco.
I also added queries tag in AndroidManifest.xml
android:name="android.intent.action.TTS_SERVICE"
That didn't help either!
package com.example.ttssample;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
public static final Integer RecordAudioRequestCode = 1;
Intent speechRecognizerIntent;
private EditText editText;
private TextToSpeech textToSpeech;
private EditText editText2;
private SpeechRecognizer speechRecognizer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
checkPermission();
}
editText = findViewById(R.id.editText);
textToSpeech = new TextToSpeech(getApplicationContext(), i -> textToSpeech.setLanguage(Locale.ENGLISH));
editText2 = findViewById(R.id.editTextRecord);
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
speechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
speechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
speechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
speechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
ArrayList<String> matches = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if (matches != null)
editText2.setText(matches.get(0));
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
findViewById(R.id.btnRecord).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_UP:
speechRecognizer.stopListening();
editText2.setHint("You will see the input here");
break;
case MotionEvent.ACTION_DOWN:
editText2.setText("");
editText2.setHint("Listening...");
speechRecognizer.startListening(speechRecognizerIntent);
break;
}
return false;
}
});
}
private void checkPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, RecordAudioRequestCode);
}
}
public void TextToSpeechButton(View view) {
textToSpeech.speak(editText.getText().toString(), TextToSpeech.QUEUE_FLUSH, null, null);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == RecordAudioRequestCode && grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
}
}
public void doBind(View view) {
redirectToBTHeadset();
}
private void redirectToBTHeadset() {
final AudioManager localAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (localAudioManager.isBluetoothScoOn())
return;
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
if (btAdapter != null && btAdapter.isEnabled() && btAdapter.getProfileConnectionState(BluetoothProfile.HEADSET) == BluetoothProfile.STATE_CONNECTED) {
if (localAudioManager.isBluetoothScoAvailableOffCall()) {
Bundle extrasBundle = registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int conState = intent.getExtras().getInt(AudioManager.EXTRA_SCO_AUDIO_STATE);
if (conState == AudioManager.SCO_AUDIO_STATE_CONNECTED) {
localAudioManager.setBluetoothScoOn(true);
context.unregisterReceiver(this);
} else {
if (conState == AudioManager.SCO_AUDIO_STATE_CONNECTING) {
System.out.println("Bluetooth Receiver :SCO Connecting....");
} else if (conState == AudioManager.SCO_AUDIO_STATE_ERROR) {
System.out.println("Bluetooth Receiver : SCO Error.");
context.unregisterReceiver(this);
} else if (conState == AudioManager.SCO_AUDIO_STATE_DISCONNECTED) {
System.out.println("Bluetooth Receiver :SCO Disconnected");
localAudioManager.setBluetoothScoOn(false);
}
}
}
}, new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED)).getExtras();
Iterator<String> iter = extrasBundle.keySet().iterator();
while (iter.hasNext()) {
String key = iter.next();
System.out.println("Bluetooth Receiver Key :" + key + ", value: " + extrasBundle.get(key));
}
if (extrasBundle.getInt(AudioManager.EXTRA_SCO_AUDIO_STATE) != 2) {
localAudioManager.setMode(AudioManager.MODE_IN_CALL);
localAudioManager.startBluetoothSco();
}
}
}
}
public void doUnBind(View view) {
stopBluetoothSco();
}
private void stopBluetoothSco() {
System.out.println("stopBluetoothSco called");
AudioManager localAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
localAudioManager.setMode(AudioManager.MODE_NORMAL);
localAudioManager.setSpeakerphoneOn(true);
localAudioManager.setBluetoothScoOn(false);
localAudioManager.stopBluetoothSco();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="120dp"
android:layout_marginTop="60dp"
android:onClick="TextToSpeechButton"
android:text="#string/text_to_speech" />
<EditText
android:id="#+id/editText"
android:layout_width="360dp"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="150dp"
android:ems="10"
android:gravity="start|top"
android:hint="#string/your_text_here"
android:text="Hello"
android:inputType="textMultiLine"
android:autofillHints="" />
<EditText
android:id="#+id/editTextRecord"
android:layout_width="360dp"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="300dp"
android:ems="10"
android:inputType="textPersonName" />
<Button
android:id="#+id/btnRecord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="120dp"
android:layout_marginTop="400dp"
android:text="Click to Record" />
<Button
android:id="#+id/btnBind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="120dp"
android:layout_marginTop="500dp"
android:onClick="doBind"
android:text="Bind" />
<Button
android:id="#+id/btnUnBind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="120dp"
android:layout_marginTop="600dp"
android:onClick="doUnBind"
android:text="Unbind" />
</RelativeLayout>
I was able to figure it out. I did try it once before, but didn't work then. Not sure why.
Document reference AudioManager#startBluetoothSco
public void TextToSpeechButton(View view) {
Bundle ttsBundle = new Bundle();
//Setting the stream to STREAM_VOICE_CALL was the key
ttsBundle.putInt(TextToSpeech.Engine.KEY_PARAM_STREAM, AudioManager.STREAM_VOICE_CALL);
textToSpeech.speak(editText.getText().toString(), TextToSpeech.QUEUE_FLUSH, ttsBundle, null);
}

display images in imageview on linear layout at the bottom of maps on mapclick

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.airbnb.android.airmapview.AirMapInterface;
import com.airbnb.android.airmapview.AirMapMarker;
import com.airbnb.android.airmapview.AirMapPolygon;
import com.airbnb.android.airmapview.AirMapPolyline;
import com.airbnb.android.airmapview.AirMapView;
import com.airbnb.android.airmapview.AirMapViewTypes;
import com.airbnb.android.airmapview.DefaultAirMapViewBuilder;
import com.airbnb.android.airmapview.GoogleChinaMapType;
import com.airbnb.android.airmapview.MapType;
import com.airbnb.android.airmapview.WebAirMapViewBuilder;
import com.airbnb.android.airmapview.listeners.OnCameraChangeListener;
import com.airbnb.android.airmapview.listeners.OnCameraMoveListener;
import com.airbnb.android.airmapview.listeners.OnInfoWindowClickListener;
import com.airbnb.android.airmapview.listeners.OnLatLngScreenLocationCallback;
import com.airbnb.android.airmapview.listeners.OnMapClickListener;
import com.airbnb.android.airmapview.listeners.OnMapInitializedListener;
import com.airbnb.android.airmapview.listeners.OnMapMarkerClickListener;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity
implements OnCameraChangeListener, OnMapInitializedListener,
OnMapClickListener, OnCameraMoveListener, OnMapMarkerClickListener,
OnInfoWindowClickListener, OnLatLngScreenLocationCallback {
Context context;
ImageView imageView;
int[] image = {
R.drawable.chopper,
R.drawable.cruise,
R.drawable.sport,
R.drawable.zx,
};
private AirMapView map;
private DefaultAirMapViewBuilder mapViewBuilder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapViewBuilder = new DefaultAirMapViewBuilder(this);
map = (AirMapView) findViewById(R.id.map);
imageView = (ImageView) findViewById(R.id.imageview);
Button btnMapTypeNormal = (Button) findViewById(R.id.btnMapTypeNormal);
Button btnMapTypeSattelite = (Button) findViewById(R.id.btnMapTypeSattelite);
Button btnMapTypeTerrain = (Button) findViewById(R.id.btnMapTypeTerrain);
btnMapTypeNormal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(#NonNull View v) {
map.setMapType(MapType.MAP_TYPE_NORMAL);
}
});
btnMapTypeSattelite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(#NonNull View v) {
map.setMapType(MapType.MAP_TYPE_SATELLITE);
}
});
btnMapTypeTerrain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(#NonNull View v) {
map.setMapType(MapType.MAP_TYPE_TERRAIN);
}
});
map.setOnMapClickListener(this);
map.setOnCameraChangeListener(this);
map.setOnCameraMoveListener(this);
map.setOnMarkerClickListener(this);
map.setOnMapInitializedListener(this);
map.setOnInfoWindowClickListener(this);
map.initialize(getSupportFragmentManager());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
AirMapInterface airMapInterface = null;
switch (id) {
case R.id.action_native_map:
try {
airMapInterface = mapViewBuilder.builder(AirMapViewTypes.NATIVE).build();
} catch (UnsupportedOperationException e) {
Toast.makeText(this, "Sorry, native Google Maps are not supported by this device. " +
"Please make sure you have Google Play Services installed.",
Toast.LENGTH_SHORT).show();
}
break;
case R.id.action_mapbox_map:
airMapInterface = mapViewBuilder.builder(AirMapViewTypes.WEB).build();
break;
case R.id.action_google_web_map:
// force Google Web maps since otherwise AirMapViewTypes.WEB returns MapBox by default.
airMapInterface = new WebAirMapViewBuilder().build();
break;
case R.id.action_google_china_web_map:
airMapInterface = new WebAirMapViewBuilder().withOptions(new GoogleChinaMapType()).build();
break;
case R.id.action_clear_logs:
Uri imgUri = Uri.parse("android.resource://com.airbnb.airmapview.sample/" + R.drawable.chopper);
Bitmap bitmap = BitmapFactory.decodeStream(imgUri);
imageView.setImageURI(null);
imageView.setImageURI(imgUri);
break;
default:
break;
}
if (airMapInterface != null) {
map.initialize(getSupportFragmentManager(), airMapInterface);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onCameraChanged(LatLng latLng, int zoom) {
// appendLog("Map onCameraChanged triggered with lat: " + latLng.latitude + ", lng: "
// + latLng.longitude);
}
#Override
public void onMapInitialized() {
appendLog("Map onMapInitialized triggered");
final LatLng airbnbLatLng = new LatLng(37.771883, -122.405224);
addMarker("Airbnb HQ", airbnbLatLng, 1);
addMarker("Performance Bikes", new LatLng(37.773975, -122.40205), 2);
addMarker("REI", new LatLng(37.772127, -122.404411), 3);
addMarker("Mapbox", new LatLng(37.77572, -122.41354), 4);
map.animateCenterZoom(airbnbLatLng, 10);
// Add Polylines
LatLng[] latLngs = {
new LatLng(37.77977, -122.38937),
new LatLng(37.77811, -122.39160),
new LatLng(37.77787, -122.38864)};
map.addPolyline(new AirMapPolyline(Arrays.asList(latLngs), 5));
// Add Polygons
LatLng[] polygonLatLngs = {
new LatLng(37.784, -122.405),
new LatLng(37.784, -122.406),
new LatLng(37.785, -122.406),
new LatLng(37.785, -122.405)
};
map.addPolygon(new AirMapPolygon.Builder().add(polygonLatLngs).strokeWidth(3.f).build());
// Add Circle
map.drawCircle(new LatLng(37.78443, -122.40805), 1000);
// enable my location
map.setMyLocationEnabled(true);
}
private void addMarker(String title, LatLng latLng, int id) {
map.addMarker(new AirMapMarker.Builder()
.id(id)
.position(latLng)
.title(title)
.iconId(R.mipmap.icon_location_pin)
.build());
}
#Override
public void onMapClick(LatLng latLng) {
if (latLng != null) {
appendLog(
"Map onMapClick triggered with lat: " + latLng.latitude + ", lng: "
+ latLng.longitude);
map.getMapInterface().getScreenLocation(latLng, this);
} else {
appendLog("Map onMapClick triggered with null latLng");
}
}
#Override
public void onCameraMove() {
appendLog("Map onCameraMove triggered");
}
private void appendLog(String msg) {
//imageView.setImageURI(imageView.getDrawable() + "\n" + msg);
}
#Override
public void onMapMarkerClick(long id) {
//appendLog("Map onMapMarkerClick triggered with id " + id);
}
#Override
public void onMapMarkerClick(Marker marker) {
//appendLog("Map onMapMarkerClick triggered with marker " + marker.getId());
}
#Override
public void onInfoWindowClick(long id) {
//appendLog("Map onInfoWindowClick triggered with id " + id);
}
#Override
public void onInfoWindowClick(Marker marker) {
//appendLog("Map onInfoWindowClick triggered with marker " + marker.getId());
}
#Override
public void onLatLngScreenLocationReady(Point point) {
//appendLog("LatLng location on screen (x,y): (" + point.x + "," + point.y + ")");
}
}
my xml code:
<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"
tools:context=".MainActivity">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<com.airbnb.android.airmapview.AirMapView
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom">
<Button
android:id="#+id/btnMapTypeNormal"
style="?android:attr/buttonBarButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Normal" />
<Button
android:id="#+id/btnMapTypeSattelite"
style="?android:attr/buttonBarButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sattelite" />
<Button
android:id="#+id/btnMapTypeTerrain"
style="?android:attr/buttonBarButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Terrain" />
</LinearLayout>
</FrameLayout>
<FrameLayout
android:id="#+id/logsScrollView"
android:layout_width="match_parent"
android:layout_height="100dp"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<ImageView
android:id="#+id/imageview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="0dp"
android:padding="0dp"
android:textSize="10sp"
/>
</FrameLayout>
</LinearLayout>

how to implement OnItemClickListener in this code?

I want to implement OnItemClickListener in this ListView ,But when i add code for this,my app will not work even there is no error. its closes automatically when I click on the Listview item. Please help me, I am a beginner in Android. I am adding my whole code here.
I am doing a bluetooth device connectivity code.
MainActivity.java
import java.util.ArrayList;
import java.util.Set;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.app.Activity;
import android.app.ProgressDialog;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
public class MainActivity extends Activity {
private TextView mStatusTv;
private Button mActivateBtn;
private Button mPairedBtn;
private Button mScanBtn;
private Button ledBtn;
private ProgressDialog mProgressDlg;
private ArrayList<BluetoothDevice> mDeviceList = new ArrayList<BluetoothDevice>();
private BluetoothAdapter mBluetoothAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStatusTv = (TextView) findViewById(R.id.tv_status);
mActivateBtn = (Button) findViewById(R.id.btn_enable);
mPairedBtn = (Button) findViewById(R.id.btn_view_paired);
mScanBtn = (Button) findViewById(R.id.btn_scan);
ledBtn = (Button) findViewById(R.id.led);
ledBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(getApplicationContext(),Ledbuttons.class);
startActivity(i);
}
});
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mProgressDlg = new ProgressDialog(this);
mProgressDlg.setMessage("Scanning...");
mProgressDlg.setCancelable(false);
mProgressDlg.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mBluetoothAdapter.cancelDiscovery();
}
});
if (mBluetoothAdapter == null) {
showUnsupported();
} else {
mPairedBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices == null || pairedDevices.size() == 0) {
showToast("No Paired Devices Found");
} else {
ArrayList<BluetoothDevice> list = new ArrayList<BluetoothDevice>();
list.addAll(pairedDevices);
Intent intent = new Intent(MainActivity.this, DeviceListActivity.class);
intent.putParcelableArrayListExtra("device.list", list);
startActivity(intent);
}
}
});
mScanBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mBluetoothAdapter.startDiscovery();
}
});
mActivateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
showDisabled();
} else {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1000);
}
}
});
if (mBluetoothAdapter.isEnabled()) {
showEnabled();
} else {
showDisabled();
}
}
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
}
#Override
public void onPause() {
if (mBluetoothAdapter != null) {
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
}
super.onPause();
}
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
private void showEnabled() {
mStatusTv.setText("Bluetooth is On");
mStatusTv.setTextColor(Color.BLUE);
mActivateBtn.setText("Disable");
mActivateBtn.setEnabled(true);
mPairedBtn.setEnabled(true);
mScanBtn.setEnabled(true);
ledBtn.setEnabled(true);
}
private void showDisabled() {
mStatusTv.setText("Bluetooth is Off");
mStatusTv.setTextColor(Color.RED);
mActivateBtn.setText("Enable");
mActivateBtn.setEnabled(true);
mPairedBtn.setEnabled(false);
mScanBtn.setEnabled(false);
ledBtn.setEnabled(false);
}
private void showUnsupported() {
mStatusTv.setText("Bluetooth is unsupported by this device");
mActivateBtn.setText("Enable");
mActivateBtn.setEnabled(false);
mPairedBtn.setEnabled(false);
mScanBtn.setEnabled(false);
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
if (state == BluetoothAdapter.STATE_ON) {
showToast("Enabled");
showEnabled();
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
mDeviceList = new ArrayList<BluetoothDevice>();
mProgressDlg.show();
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
mProgressDlg.dismiss();
Intent newIntent = new Intent(MainActivity.this, DeviceListActivity.class);
newIntent.putParcelableArrayListExtra("device.list", mDeviceList);
startActivity(newIntent);
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device);
showToast("Found device " + device.getName());
}
}
};
DeviceListActivity.java
import java.lang.reflect.Method;
import java.util.ArrayList;
import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
public class DeviceListActivity extends Activity {
private ListView mListView;
private DeviceListAdapter mAdapter;
private ArrayList<BluetoothDevice> mDeviceList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDeviceList = getIntent().getExtras().getParcelableArrayList("device.list");
mListView = (ListView) findViewById(R.id.lv_paired);
mAdapter = new DeviceListAdapter(this);
mAdapter.setData(mDeviceList);
mAdapter.setListener(new DeviceListAdapter.OnPairButtonClickListener() {
#Override
public void onPairButtonClick(int position) {
BluetoothDevice device = mDeviceList.get(position);
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
unpairDevice(device);
} else {
showToast("Pairing...");
pairDevice(device);
}
}
});
mListView.setAdapter(mAdapter);
registerReceiver(mPairReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
}
#Override
public void onDestroy() {
unregisterReceiver(mPairReceiver);
super.onDestroy();
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private void pairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private void unpairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
showToast("Paired");
} else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
showToast("Unpaired");
}
mAdapter.notifyDataSetChanged();
}
}
};
}
DeviceListAdapter.java
import java.util.List;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
public class DeviceListAdapter extends BaseAdapter{
private LayoutInflater mInflater;
private List<BluetoothDevice> mData;
private OnPairButtonClickListener mListener;
public DeviceListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public void setData(List<BluetoothDevice> data) {
mData = data;
}
public void setListener(OnPairButtonClickListener listener) {
mListener = listener;
}
public int getCount() {
return (mData == null) ? 0 : mData.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_device, null);
holder = new ViewHolder();
holder.nameTv = (TextView) convertView.findViewById(R.id.tv_name);
holder.addressTv = (TextView) convertView.findViewById(R.id.tv_address);
holder.pairBtn = (Button) convertView.findViewById(R.id.btn_pair);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
BluetoothDevice device = mData.get(position);
holder.nameTv.setText(device.getName());
holder.addressTv.setText(device.getAddress());
holder.pairBtn.setText((device.getBondState() == BluetoothDevice.BOND_BONDED) ? "Unpair" : "Pair");
holder.pairBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
mListener.onPairButtonClick(position);
}
}
});
return convertView;
}
static class ViewHolder {
TextView nameTv;
TextView addressTv;
TextView pairBtn;
}
public interface OnPairButtonClickListener {
public abstract void onPairButtonClick(int position);
}
}
activity_main.xml
<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:background="#060606"
android:orientation="vertical"
android:padding="#dimen/activity_vertical_margin" >
<TextView
android:id="#+id/tv_status"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/text_bluetooth_off"
android:textColor="#ff0000"
android:textSize="17sp" />
<Button
android:id="#+id/btn_enable"
android:layout_width="match_parent"
android:layout_height="33dp"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:background="#585858"
android:text="#string/text_enable" />
<Button
android:id="#+id/btn_view_paired"
android:layout_width="match_parent"
android:layout_height="33dp"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:background="#585858"
android:enabled="false"
android:text="#string/text_view_paired"
android:textColor="#FFFFFF" />
<Button
android:id="#+id/btn_scan"
android:layout_width="match_parent"
android:layout_height="33dp"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:background="#585858"
android:enabled="false"
android:text="#string/text_scan_devices"
android:textColor="#FFFFFF" />
<Button
android:id="#+id/led"
android:layout_width="match_parent"
android:layout_height="33dp"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:background="#585858"
android:enabled="false"
android:text="LEDS"
android:textColor="#FFFFFF" />
<TextView
android:id="#+id/TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="List Of Devices"
android:textColor="#ff0000"
android:textSize="15sp" />
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ScrollView>
<ListView
android:id="#+id/lv_paired"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
list_item_device.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="5dp"
android:paddingBottom="5dp">
<Button
android:id="#+id/btn_pair"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="Pair"
android:textColor="#ff4444" />
<TextView
android:id="#+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignTop="#+id/btn_pair"
android:layout_toLeftOf="#+id/btn_pair"
android:text="Galaxy Nexus"
android:textColor="#99cc00"
android:textSize="16sp" />
<TextView
android:id="#+id/tv_address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/btn_pair"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#+id/btn_pair"
android:text="000000000"
android:textColor="#ffbd21" />
</RelativeLayout>
My Problems that not solved are
The app is not working when I add an onItemclicklistener to the list view.
bluetooth search result is filling with the same device name.
I cannot access the buttons after viewing pairing devices and
scanned devices(it seems like that the same layout is popping to screen).
Anyone please help me to solve these issues.
Thanks in advance.
You can just do like this -
mListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(), " ITEM CLICKED POSITION = "+String.valueOf(position), Toast.LENGTH_SHORT).show();
}
});
You can add OnItemClickListener like this
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) { {
Toast.makeText(getApplicationContext(),String.valueOf(arg2), Toast.LENGTH_LONG).show();
}
});`
look at this code it contain how you set the list view listener with detect the clicked row and getting sub view in that row
ListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
View row= adapter.getView(position, view, parent);
CheckBox box=(CheckBox) row.findViewById(R.id.checkBox1);
box.performClick();
}
});
adapter is your list view adapter
hope it help

FrameLayout doesn't handle touch request correct when having 2 layers

I'm trying to extend FrameLayout to be capable to decide for which view to pass the touch event:
myApp is like this:
The dots are in horizontal scrollview, and the rectangle is just a view.
When you touch the dots area it's scrolls. I would like the rectangle to be draggable.
I can do that one at a time(I mean - if the frame has only one child). but not both.
I've figured I need to override: onInterceptTouchEvent but didn't manage to pass the event to the rectange View. here is my code:
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.example.trashproject.FrameWithTouchControl
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<View
android:id="#+id/selector"
android:layout_width="45dp"
android:layout_height="match_parent"
android:background="#33FF0000" >
</View>
<HorizontalScrollView
android:id="#+id/horizontalScroll"
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<TableLayout
android:id="#+id/table"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal" >
</TableLayout>
</HorizontalScrollView>
</com.example.trashproject.FrameWithTouchControl>
</LinearLayout>
FrameWithTouchControl.java:
package com.example.trashproject;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.FrameLayout;
public class FrameWithTouchControl extends FrameLayout {
private static final String TAG ="FrameWithTouchControl" ;
private float curSelectorPositionX1;
private float curSelectorPositionX2;
private boolean isDragging = false;
private View mSelector;
private int mTouchSlop;
public FrameWithTouchControl(Context context) {
super(context);
init();
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
initViewMembers();
}
public FrameWithTouchControl(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public FrameWithTouchControl(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
init();
}
private void initViewMembers() {
mSelector = this.findViewById(R.id.selector);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
final int action = ev.getAction();
// Always handle the case of the touch gesture being complete.
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
// Release the scroll.
isDragging = false;
return false; // Do not intercept touch event, let the child handle it
}
curSelectorPositionX1 = mSelector.getLeft();
curSelectorPositionX2 = mSelector.getRight();
float evX = ev.getX();
//if the touch is out of the selector's area
if (evX >= curSelectorPositionX2 || evX <= curSelectorPositionX1) {
return false;
}
switch (action) {
case MotionEvent.ACTION_MOVE:
if (isDragging) {
// We're currently dragging, so yes, intercept the
// touch event!
mSelector.onTouchEvent(ev);
return true;
}
mSelector.onTouchEvent(ev);
return true;
}//switch
return false;
}//onIntercept
}
MainActivity.java:
package com.example.trashproject;
import java.util.Calendar;
import java.util.Random;
import android.content.ClipData;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.DragEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnDragListener;
import android.view.View.OnTouchListener;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;
public class MainActivity extends FragmentActivity{
private static final int ROWS =8;
private static final int COLS = 100;
private static final String TAG = "MainActivity";
private TableLayout mTable;
private TextView[][] mCircles;
private boolean[][] mData;
private LayoutInflater mInflater;
private FrameLayout mFrame;
private View mSelector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mData = generateFakeGuestsTimes();
mInflater =(LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
makeTable();
mFrame = (FrameLayout) findViewById(R.id.frame);
mSelector = findViewById(R.id.selector);
mSelector.setOnTouchListener(new OnTouchListener() {
boolean isDragging;
#Override
public boolean onTouch(View v, MotionEvent event) {
Log.d(TAG, "selector touch triggered" );
Log.d(TAG, event.toString());
int action = event.getAction();
float deltaX = 0;
if (action==MotionEvent.ACTION_DOWN && !isDragging) {
isDragging = true;
deltaX = event.getX();
return true;
} else if (isDragging) {
if (action== MotionEvent.ACTION_MOVE) {
v.setX(v.getX() + event.getX() - deltaX);
} else if (action == MotionEvent.ACTION_CANCEL) {
isDragging = false;
return true;
} else if (action == MotionEvent.ACTION_UP) {
isDragging = false;
return false;
}
}
return false;
}
});
}
/**** NOT RELEVANT FROM HERE *******/
private boolean[][] generateFakeGuestsTimes() {
boolean[][] values = new boolean[ROWS][COLS];
Random rand = new Random();
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS ; j++) {
values[i][j] = rand.nextBoolean();
}
}
return values;
}
public void onClick(View view) {
Log.d(TAG, "numOfChildren" + mTable.getChildCount());
}
private void makeTable() {
mTable = (TableLayout) findViewById(R.id.table);
TableRow.LayoutParams rowParams = new TableRow.LayoutParams();
rowParams.width = LayoutParams.WRAP_CONTENT;
rowParams.height = 67;
mCircles = new TextView[ROWS][COLS];
final TableRow[] row = new TableRow[ROWS];
final TextView[] headerText = new TextView[ROWS];
long start = cal.getTimeInMillis();
for (int i = 0; i < ROWS; i++) {
row[i] = new TableRow(this);
row[i].setLayoutParams(rowParams);
for (int j = 0; j < COLS; j++) {
mCircles[i][j] = (TextView) mInflater.inflate(R.layout.calendar_month_grid, null);
if (mData[i][j]) {
mCircles[i][j].setBackgroundResource(R.drawable.small_circle);
} else {
mCircles[i][j].setBackgroundResource(R.drawable.small_circle_red);
}
row[i].addView(mCircles[i][j]);
}
mTable.addView(row[i]);
}//outer loop
long end = cal.getTimeInMillis();
Log.d(TAG, "time of operation=" + end + ", " + start + ", " + String.valueOf(end - start));
}
I resolved the issue by switching the order inside the FrameLayout.
apparently the framelayout set the layers in opposite order. i.e.:
<FrameLAyout>
<View1/>
<View2/>
</FrameLAyout>
View2 will be on the upper layer. View2 will first gets the touch callbacks, if it is not handling the touch, View1 will get a call.
I.e. It is the same as drawing. the bottom layer is View1, the upper is View2. make sense

android - Toolbar not displaying in activity

working on a wallpaper app and working on moving to API 21 and removing the ActionBar in favor of Toolbar. That being said, I am trying to use the v7-support library. What happens is basically there is a grey outline of where the toolbar should be, but it never appears.
WallpaperActivity.java:
package com.death2all110.blisspapers;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.koushikdutta.urlimageviewhelper.UrlImageViewCallback;
import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
public class WallpaperActivity extends ActionBarActivity {
public final String TAG = "BlissPapers";
protected static final String MANIFEST = "wallpaper_manifest.xml";
protected static final int THUMBS_TO_SHOW = 4;
/*
* pull the manifest from the web server specified in config.xml or pull
* wallpaper_manifest.xml from local assets/ folder for testing
*/
public static final boolean USE_LOCAL_MANIFEST = false;
ArrayList<WallpaperCategory> categories = null;
ProgressDialog mLoadingDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(getResources().getColor(R.color.primary_dark));
setContentView(R.layout.activity_wallpaper);
mLoadingDialog = new ProgressDialog(this);
mLoadingDialog.setCancelable(false);
mLoadingDialog.setIndeterminate(true);
mLoadingDialog.setMessage("Retreiving wallpapers from server...");
mLoadingDialog.show();
new LoadWallpaperManifest().execute();
Toolbar ab = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(ab);
getSupportActionBar().setTitle("Bliss Papers");
getSupportActionBar().setDisplayShowTitleEnabled(true);
UrlImageViewHelper.setErrorDrawable(getResources().getDrawable(com.death2all110.blisspapers.R.drawable.ic_error));
}
#Override
public void onResume() {
super.onResume();
Wallpaper.wallpapersCreated = 0;
}
protected void loadPreviewFragment() {
WallpaperPreviewFragment fragment = new WallpaperPreviewFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.add(android.R.id.content, fragment);
ft.commit();
}
public static class WallpaperPreviewFragment extends Fragment {
static final String TAG = "PreviewFragment";
WallpaperActivity mActivity;
View mView;
public int currentPage = -1;
public int highestExistingIndex = 0;
Button back;
Button next;
TextView pageNum;
ThumbnailView[] thumbs;
protected int selectedCategory = 0; // *should* be <ALL> wallpapers
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mActivity = (WallpaperActivity) getActivity();
next(); // load initial page
}
public void setCategory(int cat) {
selectedCategory = cat;
currentPage = -1;
next();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(com.death2all110.blisspapers.R.layout.activity_wallpaper, container, false);
back = (Button) mView.findViewById(com.death2all110.blisspapers.R.id.backButton);
next = (Button) mView.findViewById(com.death2all110.blisspapers.R.id.nextButton);
pageNum = (TextView) mView.findViewById(com.death2all110.blisspapers.R.id.textView1);
thumbs = new ThumbnailView[THUMBS_TO_SHOW];
thumbs[0] = (ThumbnailView) mView.findViewById(com.death2all110.blisspapers.R.id.imageView1);
thumbs[1] = (ThumbnailView) mView.findViewById(com.death2all110.blisspapers.R.id.imageView2);
thumbs[2] = (ThumbnailView) mView.findViewById(com.death2all110.blisspapers.R.id.imageView3);
thumbs[3] = (ThumbnailView) mView.findViewById(com.death2all110.blisspapers.R.id.imageView4);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
next();
}
});
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
previous();
}
});
return mView;
}
public ArrayList<WallpaperCategory> getCategories() {
return mActivity.categories;
}
protected Wallpaper getWallpaper(int realIndex) {
return getCategories().get(selectedCategory).getWallpapers().get(realIndex);
}
protected void setThumbs() {
for (ThumbnailView v : thumbs)
v.setVisibility(View.INVISIBLE);
final int numWallpapersInCategory = getCategories().get(selectedCategory)
.getWallpapers().size();
boolean enableForward = true;
for (int i = 0; i < thumbs.length; i++) {
final int realIndex = (currentPage * thumbs.length + i);
if (realIndex >= (numWallpapersInCategory - 1)) {
enableForward = false;
break;
}
Wallpaper w = getWallpaper(realIndex);
thumbs[i].setOnClickListener(null);
thumbs[i].getName().setText(w.getName());
thumbs[i].getAuthor().setText(w.getAuthor());
UrlImageViewHelper.setUrlDrawable(thumbs[i].getThumbnail(), w.getThumbUrl(),
com.death2all110.blisspapers.R.drawable.ic_placeholder, new ThumbnailCallBack(w, realIndex));
}
back.setEnabled(currentPage != 0);
next.setEnabled(enableForward);
}
public void next() {
getNextButton().setEnabled(false);
pageNum.setText(getResources().getString(com.death2all110.blisspapers.R.string.page) + " " + (++currentPage + 1));
setThumbs();
}
public void previous() {
pageNum.setText(getResources().getString(com.death2all110.blisspapers.R.string.page) + " " + (--currentPage + 1));
setThumbs();
}
protected void skipToPage(int page) {
if (page < currentPage) {
while (page < currentPage) {
previous(); // should subtract page
}
} else if (page > currentPage) {
while (page > currentPage) {
next();
}
}
}
public void jumpTo() {
// View view = getLayoutInflater().inflate(R.layout.dialog_jumpto,
// null);
// final EditText e = (EditText) view.findViewById(R.id.pageNumber);
// AlertDialog.Builder j = new AlertDialog.Builder(this);
// j.setTitle(R.string.jump2);
// j.setView(view);
// j.setPositiveButton(android.R.string.ok, new
// DialogInterface.OnClickListener() {
//
// public void onClick(DialogInterface dialog, int which) {
// skipToPage(Integer.parseInt(e.getText().toString()));
// }
// });
// j.setNegativeButton(android.R.string.no, new
// DialogInterface.OnClickListener() {
//
// public void onClick(DialogInterface dialog, int which) {
// dialog.cancel();
// }
// });
// j.create().show();
}
protected View getThumbView(int i) {
if (thumbs != null && thumbs.length > 0)
return thumbs[i];
else
return null;
}
protected Button getNextButton() {
return next;
}
protected Button getPreviousButton() {
return back;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case com.death2all110.blisspapers.R.id.jump:
jumpTo();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
class ThumbnailCallBack implements UrlImageViewCallback {
Wallpaper wall;
int index;
public ThumbnailCallBack(Wallpaper wall, int index) {
this.wall = wall;
this.index = index;
}
#Override
public void onLoaded(ImageView imageView, Drawable loadedDrawable, String url,
boolean loadedFromCache, boolean error) {
final int relativeIndex = index % 4;
if (!error) {
getThumbView(relativeIndex).setOnClickListener(
new ThumbnailClickListener(wall));
}
getThumbView(relativeIndex).setVisibility(View.VISIBLE);
if (relativeIndex == 3)
getNextButton().setEnabled(true);
}
}
class ThumbnailClickListener implements View.OnClickListener {
Wallpaper wall;
public ThumbnailClickListener(Wallpaper wallpaper) {
this.wall = wallpaper;
}
#Override
public void onClick(View v) {
Intent preview = new Intent(mActivity, Preview.class);
preview.putExtra("wp", wall.getUrl());
startActivity(preview);
}
}
}
public static String getDlDir(Context c) {
String configFolder = getResourceString(c, com.death2all110.blisspapers.R.string.config_wallpaper_download_loc);
if (configFolder != null && !configFolder.isEmpty()) {
return new File(Environment.getExternalStorageDirectory(), configFolder)
.getAbsolutePath() + "/";
} else {
return Environment.getExternalStorageDirectory().getAbsolutePath();
}
}
public static String getSvDir(Context c) {
String configFolder = getResourceString(c, com.death2all110.blisspapers.R.string.config_wallpaper_sdcard_dl_location);
if (configFolder != null && !configFolder.isEmpty()) {
return new File(Environment.getExternalStorageDirectory(), configFolder)
.getAbsolutePath() + "/";
} else {
return null;
}
}
protected String getWallpaperDestinationPath() {
String configFolder = getResourceString(com.death2all110.blisspapers.R.string.config_wallpaper_sdcard_dl_location);
if (configFolder != null && !configFolder.isEmpty()) {
return new File(Environment.getExternalStorageDirectory(), configFolder)
.getAbsolutePath();
}
// couldn't find resource?
return null;
}
protected String getResourceString(int stringId) {
return getApplicationContext().getResources().getString(stringId);
}
public static String getResourceString(Context c, int id) {
return c.getResources().getString(id);
}
private class LoadWallpaperManifest extends
AsyncTask<Void, Boolean, ArrayList<WallpaperCategory>> {
#Override
protected ArrayList<WallpaperCategory> doInBackground(Void... v) {
try {
InputStream input = null;
if (USE_LOCAL_MANIFEST) {
input = getApplicationContext().getAssets().open(MANIFEST);
} else {
URL url = new URL(getResourceString(com.death2all110.blisspapers.R.string.config_wallpaper_manifest_url));
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical
// 0-100%
// progress bar
int fileLength = connection.getContentLength();
// download the file
input = new BufferedInputStream(url.openStream());
}
OutputStream output = getApplicationContext().openFileOutput(
MANIFEST, MODE_PRIVATE);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
// file finished downloading, parse it!
ManifestXmlParser parser = new ManifestXmlParser();
return parser.parse(new File(getApplicationContext().getFilesDir(), MANIFEST),
getApplicationContext());
} catch (Exception e) {
Log.d(TAG, "Exception!", e);
}
return null;
}
#Override
protected void onPostExecute(ArrayList<WallpaperCategory> result) {
categories = result;
if (categories != null)
loadPreviewFragment();
mLoadingDialog.cancel();
super.onPostExecute(result);
}
}
}
Here is activity_wallpaper.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" >
<View
android:id="#+id/strut"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_centerHorizontal="true" />
<Button
android:id="#+id/backButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignRight="#id/strut"
android:layout_marginBottom="5dp"
android:text="#string/back" />
<Button
android:id="#+id/nextButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/strut"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="5dp"
android:text="#string/next" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/backButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="5dp"
android:text="#string/page" />
<LinearLayout
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/textView1"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="5dp"
android:orientation="vertical" >
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?android:attr/actionBarSize"
android:background="?android:attr/colorPrimary" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal" >
<com.death2all110.blisspapers.ThumbnailView
android:id="#+id/imageView1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:layout_weight="1" />
<com.death2all110.blisspapers.ThumbnailView
android:id="#+id/imageView2"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal" >
<com.death2all110.blisspapers.ThumbnailView
android:id="#+id/imageView3"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:layout_weight="1" />
<com.death2all110.blisspapers.ThumbnailView
android:id="#+id/imageView4"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
styles.xml:
<resources>
<style name="Theme.Bliss" parent="Theme.AppCompat.NoActionBar">
<!-- Main theme colors -->
<!-- your app branding color for the app bar -->
<item name="colorPrimary">#color/primary</item>
<!-- darker variant for the status bar and contextual app bars -->
<item name="colorPrimaryDark">#color/primary_dark</item>
<!-- theme UI controls like checkboxes and text fields -->
<item name="colorAccent">#color/accent</item>
</style>
</resources>
If I remove the setContentView from the onCreate method, I get an error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.support.v7.widget.Toolbar.getTitle()' on a null object reference
Any ideas on what I can do to correct this?
Screenshot:
You need to add a android.supprt.v7.widget.Toolbar to your layout and then do this in the onCreate method of your ActionBarActivity
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActitionBar(toolbar);
Also, make sure your theme uses Theme.AppCompat.NoActionBar (or Theme.AppCompat.Light.NoActionBar)
FWIW - i just retrofitted some ABS stuff to the newer Toolbar stuff that you are on and had some issues with the Title not showing up in all Frgments, activities.... Some worked some did not. Very frustrating to have varied outcomes. Had to replicate the following code in places where i did not think it should be needed due to inheritance and due to calls to 'super.onCreate()'..
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(true);
After populated the above code everywhere in those activities/frags where it did NOT show up, the issue resolved.
Really odd that ur title flashes up then disappear.. something is repainting the view!
I found out that I needed to
<include layout="#layout/toolbar_layout"/>
in my activity's layout file since I had my toolbar layout defined in its own xml file.

Categories