TextView is not selectable with ontouchListener - java

I have implemented ontouchListener in my activity to detect swipes left and right. However, enabling this feature stopped me from being able to make my text selectable and accordingly getting the default android text selection cursor, menu.
After many trials, now i can perfectly call the onLongClick() method when long clicking the textView. However, still the text is not selectable. also, whenever I disable the swipe detection, the Text selection works perfectly.
public class PreviewActivity extends AppCompatActivity
{
TextView question;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preview);
question = (TextView)findViewById(R.id.question);
question.setTextSize(TextViewSize);
question.setTextIsSelectable(true);
question.setLongClickable(true);
question.setFocusableInTouchMode(true);
View prev_act = (View) findViewById(R.id.question);
prev_act.setOnTouchListener(new OnSwipeTouchListener(this) {
#Override public void onSwipeLeft() {
if(RowIndex>0){
Qtitle = ListItems.get(RowIndex-1);
Query();
//text = Query();
//question.setText(text);
questionSC.scrollTo(0,0);
RowIndex--;
}
}
#Override public void onSwipeRight() {
if(RowIndex<ListItems.size()-1){
Qtitle = ListItems.get(RowIndex+1);
Query();
//text = Query();
//question.setText(text);
questionSC.scrollTo(0,0);
RowIndex++;
}
}
#Override public void onLongClick() {
Log.v(this.toString(), "Long click.");
question.setCursorVisible(true);
question.performLongClick();
}
});
}
And the OnSwipeTouchListener class is as the following:
public class OnSwipeTouchListener implements OnTouchListener {
private final GestureDetector gestureDetector;
public OnSwipeTouchListener (Context ctx){
gestureDetector = new GestureDetector(ctx, new GestureListener());
}
#Override public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
private final class GestureListener extends SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 250;
private static final int SWIPE_VELOCITY_THRESHOLD = 200;
#Override
public void onLongPress(MotionEvent e) {
onLongClick();
super.onLongPress(e);
}
#Override
public boolean onDown(MotionEvent e) {
return true;
}
#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) {
onSwipeRight();
} else {
onSwipeLeft();
}
result = true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
public void onSwipeRight() {
}
public void onSwipeLeft() {
}
public void onSwipeTop() {
}
public void onSwipeBottom() {
}
public void onLongClick() {
}
}
I want to be able to select a portion (text) from the TextView and having the swipe detector along it.
Edited: added the XML file of the mentioned Activity
<?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:id="#+id/activity_preview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="50dp"
android:paddingRight="20dp"
android:paddingLeft="20dp"
android:paddingBottom="30dp"
android:background="#drawable/bg"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageButton
android:id="#+id/next"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:adjustViewBounds="true"
android:background="#0000"
android:scaleType="fitCenter"
android:src="#drawable/ic_navigate_before_black_24dp" />
<ImageButton
android:id="#+id/share"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:adjustViewBounds="true"
android:background="#0000"
android:padding="9dp"
android:scaleType="fitCenter"
android:src="#drawable/ic_share_black_24dp" />
<ImageButton
android:id="#+id/star"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:adjustViewBounds="true"
android:background="#0000"
android:padding="9dp"
android:scaleType="fitCenter"
android:src="#drawable/star_border" />
<ImageButton
android:id="#+id/copy"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:adjustViewBounds="true"
android:background="#0000"
android:padding="9dp"
android:scaleType="fitCenter"
android:src="#drawable/ic_content_copy_black_24dp" />
<ImageButton
android:id="#+id/previous"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:adjustViewBounds="true"
android:background="#0000"
android:scaleType="fitCenter"
android:src="#drawable/ic_navigate_next_black_24dp" />
</LinearLayout>
<ScrollView
android:id="#+id/questionSC"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="30dp"
android:layout_marginTop="50dp">
<LinearLayout
android:id="#+id/question_lo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/question"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fontFamily="#font/ge_thameen_book"
android:paddingBottom="20dp"
android:paddingTop="10dp"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="20dp"
android:autoLink="web"
/>
</LinearLayout>
</ScrollView>

After trying for a while this is what worked highlighting and selecting text enabling copy,paste,selectall ... etc
you will need to add onTouch snippet in the prev_act.setOnTouchListener(new OnSwipeTouchListener(this) {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == MotionEvent.ACTION_DOWN) {
//do stuff here
Log.i("clicking", "onActionDown");
}else if(event.getAction() == MotionEvent.ACTION_UP) {
question.performLongClick();
}
return false;
}
#Override public void onLongClick() {
}

The answer was very simple:
#Override
public boolean onDown(MotionEvent e) {
return false;
}
I had to set the onDown() to return false.

Related

Recorded file name is wrong

first of all, I'll explain the expected behavior of the App.
What does the App do?
When I run the App I see this view:
Now if you hit the "+" button you'll see this Dialog:
By clicking Add this entry will be added to a ListView. I added two items. This looks like this:
Expected Result
Now when I touch and hold the mic icon of the list items it should start recording audio through the device microphone and then save this recording with the name of the bold entry, that means e.g. the first recording will get the name A.3gp, the second one B.3gp and so on..
Actual Result (UPDATE 07.12.2017)
The current state is:
Every item in the list gets his "own" recording. That means if I touch and hold the microphone icon of the first item in the list, it is doing what it should do. The same goes for all other items on the list.
When I add the first item A, then touch its record icon, a file will be created with the name A.3gp (which is correct behavior).
When I add the second item B then do nothing and then add a third item C and touch the record icon for B, a file will be created with the name C.3gp (which is not a correct behavior, it should be B.3gp).
Now to the fun part.
Code (UPDATE 07.12.2017)
1. The Model
public class Word {
private String mForeignTranslation;
private String mDefaultTranslation;
private ImageView mRecordIconImageResourceId;
private MediaRecorder mMediaRecorder;
public Word(String foreignTranslation, String defaultTranslation, ImageView recordIconImageResourceId) {
this.mForeignTranslation = foreignTranslation;
this.mDefaultTranslation = defaultTranslation;
this.mRecordIconImageResourceId = recordIconImageResourceId;
}
public Word(String foreignTranslation, String defaultTranslation) {
this.mForeignTranslation = foreignTranslation;
this.mDefaultTranslation = defaultTranslation;
}
public String getDefaultTranslation() {
return mDefaultTranslation;
}
public String getForeignTranslation() {
return mForeignTranslation;
}
public ImageView getRecordIconImageResourceId() {
return mRecordIconImageResourceId;
}
public MediaRecorder getMediaRecorder() {
return mMediaRecorder;
}
public void setDefaultTranslation(String mDefaultTranslation) {
this.mDefaultTranslation = mDefaultTranslation;
}
public void setForeignTranslation(String mForeignTranslation) {
this.mForeignTranslation = mForeignTranslation;
}
public void setRecordIconImageResourceId(ImageView recordIconImageResourceId) {
this.mRecordIconImageResourceId = recordIconImageResourceId;
}
public void setMediaRecorder(MediaRecorder mMediaRecorder) {
this.mMediaRecorder = mMediaRecorder;
}
}
2. The Adapter
public class WordAdapter extends ArrayAdapter<Word> {
private ArrayList<Word> wordsArrayList = new ArrayList<>();
private MediaRecorder mediaRecorder = new MediaRecorder();
public WordAdapter(#NonNull Context context, ArrayList<Word> words) {
super(context, 0, words);
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.my_word_list_items,parent,false);
}
Word currentWord = getItem(position);
TextView foreignWord = listItemView.findViewById(R.id.myForeignWord);
foreignWord.setText(currentWord.getForeignTranslation());
TextView defaultWord = listItemView.findViewById(R.id.myDefaultWord);
defaultWord.setText(currentWord.getDefaultTranslation());
final ImageView recordIconImageView = listItemView.findViewById(R.id.recordIconImageView);
wordsArrayList = MyWordsActivity.getWordsArrayList();
recordIconImageView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN: {
recordIconImageView.setImageResource(R.drawable.mic_red);
startAudioRecording();
break;
}
case MotionEvent.ACTION_UP: {
recordIconImageView.setImageResource(R.drawable.mic_black);
stopAudioRecording();
break;
}
}
return true;
}
});
return listItemView;
}
private ArrayList<Word> getWordsArrayList() {
return wordsArrayList;
}
private void startAudioRecording() {
if (wordsArrayList != null) {
Log.i("ArrayListe", wordsArrayList.toArray().toString());
getMediaRecorderReady();
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
Toast.makeText(this.getContext(), "Recording started", Toast.LENGTH_SHORT).show();
}
}
private void stopAudioRecording() {
try {
mediaRecorder.stop();
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(this.getContext(), "Recording stopped", Toast.LENGTH_SHORT).show();
}
private void getMediaRecorderReady() {
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+"speakmylanguage"+"/"+MyWordsActivity.getForeignWord()+".3gp");
}
}
3. The Activity
public class MyWordsActivity extends AppCompatActivity {
private static String defaultWord, foreignWord;
private static ArrayList<Word> wordsArrayList = new ArrayList<>();
WordAdapter wordAdapter;
// Main Activity Views
TextView hintTextView;
ListView myWordsListView;
FloatingActionButton floatingButtonAddNewWord;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_words);
// Init Main Activity Views
hintTextView = findViewById(R.id.hintTextView);
myWordsListView = findViewById(R.id.myWordsList);
floatingButtonAddNewWord = findViewById(R.id.fabAddNewWord);
floatingButtonAddNewWord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Dialog addNewWordsDialog = new Dialog(MyWordsActivity.this);
addNewWordsDialog.setContentView(R.layout.activity_add_new_words);
final EditText addForeignWordEditText = addNewWordsDialog.findViewById(R.id.addForeignWordEditText);
final EditText addDefaultWordEditText = addNewWordsDialog.findViewById(R.id.addDefaultWordEditText);
final Button addNewWordButton = addNewWordsDialog.findViewById(R.id.addNewWordButton);
addNewWordsDialog.show();
addNewWordButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!addDefaultWordEditText.getText().toString().equals("") &&
!addForeignWordEditText.getText().toString().equals("")) {
foreignWord = addForeignWordEditText.getText().toString();
defaultWord = addDefaultWordEditText.getText().toString();
wordsArrayList.add(new Word(foreignWord, defaultWord));
hintTextView.setVisibility(View.GONE);
addNewWordsDialog.dismiss();
} else {
Toast.makeText(MyWordsActivity.this, "Please enter two words", Toast.LENGTH_SHORT).show();
}
}
});
wordAdapter = new WordAdapter(MyWordsActivity.this, getWordsArrayList());
myWordsListView.setAdapter(wordAdapter);
}
});
}
public static String getDefaultWord() {
return defaultWord;
}
public static void setDefaultWord(String defaultWord) {
MyWordsActivity.defaultWord = defaultWord;
}
public static String getForeignWord() {
return foreignWord;
}
public static void setForeignWord(String foreignWord) {
MyWordsActivity.foreignWord = foreignWord;
}
public static ArrayList<Word> getWordsArrayList() {
return wordsArrayList;
}
}
4. The Layouts
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/myRelativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:id="#+id/myWordsListItems"
android:layout_width="match_parent"
android:layout_height="88dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_marginStart="16dp"
android:orientation="vertical">
<TextView
android:id="#+id/myForeignWord"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="bottom"
android:textAppearance="?android:textAppearanceMedium"
android:textSize="24sp"
android:textStyle="bold"
tools:text="foreign word" />
<TextView
android:id="#+id/myDefaultWord"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="top"
android:textAppearance="?android:textAppearanceMedium"
android:textSize="24sp"
tools:text="default word" />
</LinearLayout>
<ImageView
android:id="#+id/playIconImageView"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_marginEnd="16dp"
android:clickable="true"
android:src="#drawable/play_icon" />
<ImageView
android:id="#+id/recordIconImageView"
android:layout_width="42dp"
android:layout_height="42dp"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_marginEnd="72dp"
android:clickable="true"
android:src="#drawable/mic_black" />
</RelativeLayout>
activity_my_words.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"
android:orientation="vertical"
tools:context="com.yousef.mustafa.speakmylanguage.View.MyWordsActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:title="#string/app_name"
app:titleTextColor="#color/colorWhite" />
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/myWordsList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar"
android:drawSelectorOnTop="true"
android:orientation="vertical"
tools:context=".View.MyWordsActivity" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fabAddNewWord"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_gravity="bottom|center"
android:layout_marginBottom="32dp"
android:tint="#color/colorWhite"
app:backgroundTint="#color/colorGrey"
app:srcCompat="#drawable/icon_add" />
<TextView
android:id="#+id/hintTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="155dp"
android:gravity="center"
android:text="#string/hint"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
activity_add_new_words.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:background="#color/colorDialogBackground">
<LinearLayout
android:id="#+id/addNewWordLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="8dp"
android:layout_marginTop="12dp"
android:text="#string/add_word_title"
android:textColor="#color/colorBlack"
android:textSize="24sp"
android:textStyle="bold" />
<EditText
android:id="#+id/addForeignWordEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="4dp"
android:layout_marginEnd="12dp"
android:layout_marginStart="12dp"
android:layout_weight="5"
android:gravity="center_horizontal"
android:hint="#string/enter_foreign_word"
android:inputType="textPersonName|textCapWords"
android:textSize="24sp" />
<EditText
android:id="#+id/addDefaultWordEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginEnd="12dp"
android:layout_marginStart="12dp"
android:layout_marginTop="4dp"
android:layout_weight="5"
android:gravity="center_horizontal"
android:hint="#string/enter_default_word"
android:inputType="textPersonName|textCapWords"
android:textSize="24sp" />
<Button
android:id="#+id/addNewWordButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginEnd="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="#string/button_add"
android:textAllCaps="false"
android:textSize="18sp" />
</LinearLayout>
</RelativeLayout>
I would appreciate any help. Thanks in advance.
In the startAudioRecording() method of the Activity, you set the output filename from the foreignWord field. The problem is that the foreignWord field is set to the most recently added foreign word each time the user submits a word pair in the Add Word dialog. Thus each time the user starts a recording, the name of the output file will be set to the last foreign word added.
Instead of using fields for recordingImageView, foreignWord, defaultWord, foreignWord, audioSavePath, and mediaRecorder, you should make them local variables, and pass them as parameters to your record(), startAudioRecording(), stopAudioRecording() methods with the following steps:
Just delete those fields from the beginning of the class so that you see some compilation errors where the fields were used.
Where you see an undefined variable on the left side of an assignment, make the variable local (Ctrl+V in Android Studio).
Where you see an undefined variable elsewhere, make the variable a parameter of the method (Ctrl+P).
It should work after those changes.
`
Kindly move this snippet :
recordingImageView.setOnTouchListener(new View.OnTouchListener()
{
#Override public boolean onTouch(View view, MotionEvent motionEvent)
{
switch (motionEvent.getAction())
{
case MotionEvent.ACTION_DOWN:
{ recordingImageView.setImageResource(g startAudioRecording(position);
break;
}
case MotionEvent.ACTION_UP:
{
recordingImageView.setImageResource(R.drawable.mic_black);
stopAudioRecording();
break;
}
}
return true;
}
});
In Adapter , getView(...) Below accessing recordImageView.
And put startAudioRecording() , stopAudioRecording() in same adapter or all relevant method for recording is to be in Adapter.
So by this you will get click on in each individual image view. Previously when you are fetching it will only take instance of any one image view.
Now update code on "startAudioRecording()" as:
private void startAudioRecording()
{
if (checkPermission())
{
if (wordsArrayList != null)
{
audioSavePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + wordsArrayList.get(position) + ".3gp";
getMediaRecorderReady();
}
}
}
Now your second point, saving its name by any name. Will cover by above code.
Thanks and happy coding

ListActivity not loading adapters style, loading white screen

I am working in android studio with GSON and Retrofit 1, which is stable. I am in need to find out why non of the information is showing, the GSON should be putting the JSON information in the model class of getters/setters. I am making a Movie App using the imdb api, I can share my code here if you would like to review the project as a whole, but otherwise below is some of the code:
GitHub Project
This is the detail item xml I am trying to populate then put in the list in the main 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:paddingRight="0dp"
android:paddingBottom="0dp"
android:paddingTop="0dp"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.evanglazer.moviezone.MainActivity"
android:id="#+id/top">
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:id="#+id/movieView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="IMDB Rating:"
android:id="#+id/imdbText"
android:padding="10dp"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/movieView"
android:layout_toEndOf="#+id/movieView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/imdbRatingText"
android:padding="10dp"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/imdbText"
android:layout_toEndOf="#+id/imdbText"
android:singleLine="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="UserBase Vote:"
android:id="#+id/userText"
android:padding="10dp"
android:layout_centerInParent="#+id/imdbText"
android:layout_below="#+id/imdbText"
android:layout_alignRight="#+id/releaseDateText"
android:layout_alignEnd="#+id/releaseDateText" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/userRatingText"
android:padding="10dp"
android:layout_below="#+id/imdbText"
android:layout_toRightOf="#+id/imdbText"
android:layout_toEndOf="#+id/imdbText"
android:singleLine="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Release Date:"
android:id="#+id/releaseText"
android:padding="10dp"
android:layout_below="#+id/userText"
android:layout_toLeftOf="#+id/userRatingText"
android:layout_toStartOf="#+id/userRatingText"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/releaseDateText"
android:layout_below="#+id/releaseText"
android:layout_alignRight="#+id/releaseText"
android:layout_alignEnd="#+id/releaseText" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/middle">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Trailer 1"
android:id="#+id/trailer1"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Trailer 2"
android:id="#+id/trailer2"
android:layout_below="#+id/trailer1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="100dp"
android:id="#+id/editText"
android:layout_below="#+id/trailer2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
</RelativeLayout>
Here is the detail main:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/main2"
android:layout_height="match_parent">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true">
</ListView>
</RelativeLayout>
Here is the detail activity:
public class DetailActivity extends ListActivity{
public static final String URL_IMAGE_ENDPOINT = "http://image.tmdb.org";
public static final String URL_API_ENDPOINT = "http://api.themoviedb.org";
FragmentManager fm = getFragmentManager();
List<MovieDetail> details;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_main);
//fm.beginTransaction().replace(R.id.main2, new Detail()).commit();
//fm.beginTransaction().replace(R.id.main2, new NavBar()).commit();
if (isOnline()) {
requestData();
} else {
Toast.makeText(this, "Network isn't available", Toast.LENGTH_LONG).show();
}
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
private void requestData()
{
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(URL_API_ENDPOINT)
.build();
MovieAPI api = adapter.create(MovieAPI.class);
api.getMovieDetails(new Callback<List<MovieDetail>>() {
#Override
public void success(List<MovieDetail> movieDetails, Response response) {
details = movieDetails;
// update display
updateDisplay();
}
#Override
public void failure(RetrofitError arg0) {
// TODO Auto-generated method stub
}
});
}
protected void updateDisplay() {
//Use FlowerAdapter to display data
MovieDetailAdapter adapter = new MovieDetailAdapter(this, R.layout.movie_detail_fragment, details);
setListAdapter(adapter);
}
#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) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this,SettingActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is how I am api through retrofit:
public interface MovieAPI {
#GET("/3/movie/273248?api_key=ea8f68dc2c7b43a3df248b9a638f5fb4")
void getMovieDetails(Callback<List<MovieDetail>> callback);
#GET("3/movie/5493/movie/549")
void getPopularMovies(Callback<List<MovieDetail>> response);
}
Here is the model for the objects I am trying to read in from the callback:
public class MovieDetail {
private String poster_path;
private String release_date;
private int id;
private String original_title;
private double vote_average;
private int gridPos;
private Bitmap bitmap;
public int getGridPos() {
return gridPos;
}
public void setGridPos(int gridPos) {
this.gridPos = gridPos;
}
public String getPoster_path() {
return poster_path;
}
public void setPoster_path(String poster_path) {
this.poster_path = poster_path;
}
public String getRelease_date() {
return release_date;
}
public void setRelease_date(String release_date) {
this.release_date = release_date;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getOriginal_title() {
return original_title;
}
public void setOriginal_title(String original_title) {
this.original_title = original_title;
}
public double getVote_average() {
return vote_average;
}
public void setVote_average(double vote_average) {
this.vote_average = vote_average;
}
public Bitmap getBitmap() {
return bitmap;
}
public void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}

How to hide part of layout when editText is selected

Is there a way how to hide some buttons when i click on EditText and keybord shows?
I have this layout
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/InnerRelativeLayout">
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1"
android:id="#+id/table">
<TableRow
android:id="#+id/tariffRow">
<TextView
android:layout_column="1"
android:text="Název"
android:padding="3dip" />
<EditText
android:id="#+id/tariffName"
android:gravity="right"
android:padding="3dip" />
</TableRow>
</TableLayout>
</ScrollView>
<LinearLayout android:id="#+id/InnerRelativeLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_alignParentBottom="true">
<Button android:id="#+id/okBtn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="Ok"/>
<Button android:id="#+id/stornoBtn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="Storno" />
</LinearLayout>
Now when the editText is clicked to type some value i need to hide that linearLayout android:id="#+id/InnerRelativeLayout" because otherwise it is still visible above the keyboard.
Need to set a FocusChangeListener to the EditText which triggers whenever focus changes on that EditText as follow:
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
// hide relative layout
} else {
// show relative layout
}
}
});
It is not actually that simple, here is my solution how I got it working.
First Need to create MyEditText.java
public class MyEditText extends EditText {
private KeyImeChange keyImeChangeListener;
public MyEditText(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
public void setKeyImeChangeListener(KeyImeChange keyImeChange){
keyImeChangeListener = keyImeChange;
}
public interface KeyImeChange {
public boolean onKeyIme(int keyCode, KeyEvent keyEvent);
}
#Override
public boolean onKeyPreIme (int keyCode, KeyEvent keyEvent){
if(keyImeChangeListener != null){
return keyImeChangeListener.onKeyIme(keyCode, keyEvent);
}
return false;
}
}
Then layout.xml, change following
<EditText
android:id="#+id/tariffName"
android:gravity="right"
android:padding="3dip" />
Into
<!-- change yourapp -->
<com.yourapp.MyEditText
android:id="#+id/tariffName"
android:gravity="right"
android:padding="3dip" />
Add also android:focusable="true" to your LinearLayout
<LinearLayout android:id="#+id/InnerRelativeLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_alignParentBottom="true"
android:focusable="true">
Then put into your activity like MainActivity.java,
import fi.hgs.apps.MyEditText.KeyImeChange;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
removeFocus();
MyEditText myEditText = (MyEditText) findViewById(R.id.tariffName);
myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus) {
showLinearLayout();
} else {
hideLinearLayout();
}
}
});
myEditText.setKeyImeChangeListener(new KeyImeChange() {
#Override
public boolean onKeyIme(int keyCode, KeyEvent event) {
if (KeyEvent.KEYCODE_BACK == event.getKeyCode()) {
removeFocus();
}
return false;
}
});
}
Add also these to do the actual job.
public void removeFocus() {
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.InnerRelativeLayout);
linearLayout.requestFocus();
}
public void showLinearLayout() {
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.InnerRelativeLayout);
linearLayout.setVisibility(View.VISIBLE);
}
public void hideLinearLayout() {
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.InnerRelativeLayout);
linearLayout.setVisibility(View.INVISIBLE);
}

Android layout Not working

Hii i made a simple layout in which i use 3 image views and i make the center one movable.
Her is my layout class main.xml:-
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<view class="com.example.screenlock.MainActivity$IV"
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="center"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom|fill_horizontal"
android:background="#60000000"
android:orientation="horizontal"
android:padding="7dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:scaleType="fitXY"
android:layout_alignParentLeft="true"
android:src="#drawable/browser1" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/circle" />
<ImageView
android:id="#+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|fill_vertical"
android:layout_weight="0"
android:scaleType="fitXY"
android:src="#drawable/lock" />
</LinearLayout>
</FrameLayout>
and My MainActivity.java class is as follows:-
public class MainActivity extends Activity {
private ImageView imageView1, imageView2;
public static class IV extends ImageView {
private MainActivity mActivity;
public IV(Context context) {
super(context);
}
public IV(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setActivity(MainActivity act) {
mActivity = act;
}
public void onSystemUiVisibilityChanged(int visibility) {
mActivity.getState().onSystemUiVisibilityChanged(visibility);
}
}
private interface State {
void apply();
State next();
void onSystemUiVisibilityChanged(int visibility);
}
State getState() {
return mState;
}
static int TOAST_LENGTH = 500;
IV mImage;
TextView mText1, mText2;
State mState;
public MainActivity() {
// TODO Auto-generated constructor stub
}
#Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED|WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
startService(new Intent(this, MyLockService.class));
System.out.println(R.id.image);
imageView2 = (ImageView)findViewById(R.id.imageView2);
imageView2.setOnTouchListener(new OnTouchListener()
{
float lastX;
PointF DownPT = new PointF(); // Record Mouse Position When Pressed Down
PointF StartPT = new PointF(); // Record Start Position of 'img'
#SuppressLint("NewApi")
#Override
public boolean onTouch(View v, MotionEvent event)
{
int eid = event.getAction();
switch (eid)
{
case MotionEvent.ACTION_MOVE :
PointF mv = new PointF( event.getX() - DownPT.x, event.getY() - DownPT.y);
if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD){
v.scrollBy((int) (event.getX()-lastX), 0);
lastX = event.getX();
if(lastX >= 170){
MarginLayoutParams lp = (MarginLayoutParams) imageView2.getLayoutParams();
lp.setMargins(178, 0, 0, 0);
imageView2.setLayoutParams(lp);
}
if(lastX <= 25){
MarginLayoutParams lp = (MarginLayoutParams) imageView2.getLayoutParams();
lp.setMargins(0, -16, 0, 0);
imageView2.setLayoutParams(lp);
}
System.out.println("XXXXXXX "+lastX);
}
else{
imageView2.setX((int)(StartPT.x+mv.x));
imageView2.setY((int)(StartPT.y+mv.y));
StartPT = new PointF( imageView2.getX(), imageView2.getY() );
//System.out.println("X: "+imageView2.getX()+"Y: "+imageView2.getY());
if(imageView2.getX() < -70)
{
imageView2.setX(-103);
imageView2.setY(6);
//System.out.println("--------------------------------------");
}
else if(imageView2.getX() > 260)
{
imageView2.setX(270);
imageView2.setY(8);
finish();
}
}
break;
case MotionEvent.ACTION_DOWN :
if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD){
lastX = event.getX();
}
else{
DownPT.x = event.getX();
DownPT.y = event.getY();
StartPT = new PointF( imageView2.getX(), imageView2.getY() );
}
break;
case MotionEvent.ACTION_UP :
v.scrollTo(0, 0);
break;
default :
break;
}
return true;
}
});
}
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
// Use onWindowFocusChanged to get the placement of
// the image because we have to wait until the image
// has actually been placed on the screen before we
// get the coordinates. That makes it impossible to
// do in onCreate, that would just give us (0, 0).
imageView1 = (ImageView) findViewById(R.id.imageView1);
int[] a = new int[2];
imageView1.getLocationInWindow(a);
int x = a[0];
int y = a[1];
System.out.println("X "+x+" Y "+y);
}
}
#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;
}
}
I am executing this code on pre-honeycomb emulator. But when i move the center image it gets hides behind the left and right images respectively.
I want center image to shown on the rest of two images and also want to show that two images also.
Basically, the center image is a circle and rest two images are browser and lock images and i want that circle to overlaps that images.
I am working on a lock screen.
Please help in my layout problem and how i can solve this problem?????
You can try changing your layout as follows...
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<view
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.example.screenlock.MainActivity$IV"
android:scaleType="center" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom|fill_horizontal" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#60000000"
android:orientation="horizontal"
android:padding="7dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:scaleType="fitXY"
android:src="#drawable/ic_launcher" />
<View
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1" />
<ImageView
android:id="#+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|fill_vertical"
android:layout_weight="0"
android:scaleType="fitXY"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:src="#drawable/ic_launcher" />
</FrameLayout>
</FrameLayout>

How to scroll an image horizontally?

I have a problem with horizontal scroll view.
This is my XML code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/relative_layout_id"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/home_title_id"
android:text="#string/home_title"
android:layout_marginTop="#dimen/forty_text_size"
android:textColor="#android:color/white"
android:layout_centerHorizontal="true"
android:gravity="center"
android:textSize="#dimen/forty_text_size" />
<LinearLayout
android:id="#+id/linear_layout_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/home_title_id">
<HorizontalScrollView
android:id="#+id/horizontal_view_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/home_image_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/abc" />
</HorizontalScrollView>
</LinearLayout>
</RelativeLayout>
In my Java class, extending activity I have declared all the widgets, then i created a class scrollview, extending horizontal scroll view.
The Java code is as follows:
class scrollview extends HorizontalScrollView
{
private static final int SWIPE_MIN_DISTANCE = 5;
private static final int SWIPE_THRESHOLD_VELOCITY = 300;
private ArrayList mItems = null;
private GestureDetector mGestureDetector;
private int mActiveFeature = 0;
public scrollview(Context context)
{
super(context);
}
public void setFeatureItems(ArrayList items)
{
LinearLayout internalWrapper = new LinearLayout(getContext());
internalWrapper.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
internalWrapper.setOrientation(LinearLayout.HORIZONTAL);
addView(internalWrapper);
this.mItems = items;
for(int i = 0; i< items.size();i++)
{
LinearLayout featureLayout = (LinearLayout) View.inflate(this.getContext(),R.layout.activity_main,null);
//...
//Create the view for each screen in the scroll view
//...
internalWrapper.addView(featureLayout);
}
setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
//If the user swipes
if (mGestureDetector.onTouchEvent(event))
{
return true;
}
else if(event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL )
{
int scrollX = getScrollX();
int featureWidth = v.getMeasuredWidth();
mActiveFeature = ((scrollX + (featureWidth/2))/featureWidth);
int scrollTo = mActiveFeature*featureWidth;
smoothScrollTo(scrollTo, 0);
return true;
}
else
{
return false;
}
}
});
mGestureDetector = new GestureDetector(new MyGestureDetector());
}
class MyGestureDetector extends SimpleOnGestureListener
{
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
{
try
{
//right to left
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY)
{
int featureWidth = getMeasuredWidth();
mActiveFeature = (mActiveFeature < (mItems.size() - 1))? mActiveFeature + 1:mItems.size() -1;
smoothScrollTo(mActiveFeature*featureWidth, 0);
return true;
}
//left to right
else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY)
{
int featureWidth = getMeasuredWidth();
mActiveFeature = (mActiveFeature > 0)? mActiveFeature - 1:0;
smoothScrollTo(mActiveFeature*featureWidth, 0);
return true;
}
} catch (Exception e) {
Log.e("Fling", "There was an error processing the Fling event:" + e.getMessage());
}
return false;
}
}
}
But nothing happens, please help.
ORWILL IT BE BETTER TO HAVE THE SCROLL CLASS IN THE ONTOUCH LISTNER FUNCTION???
Wrong tag placement in your layout.xml file i think. Place LinearLayout having ImageView in HorizontalScrollView instead of HorizontalScrollView in LinearLayout as below:
<HorizontalScrollView
android:id="#+id/horizontal_view_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/home_title_id" >
<LinearLayout
android:id="#+id/linear_layout_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/home_image_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/abc" />
</LinearLayout>
</HorizontalScrollView>
there is no need for java coding here. this java coding is required only for SWIPE functionality
the XML coding alone is enough!!!but, in the following format
<HorizontalScrollView
android:id="#+id/horizontal_view_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/home_title_id" >
<LinearLayout
android:id="#+id/linear_layout_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/home_image_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/abc" />
</LinearLayout>
</HorizontalScrollView>
as horizontal scroll can hold only one child node.

Categories