I am building a password visibility toggle system (Without using TextInputLayout).
It is working, but I wan to change the icon when user clicks on the icon inside the EditText input field.
xml
<EditText
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="#+id/etPassword"
android:layout_marginRight="20dp"
android:inputType="textPassword"
android:layout_marginLeft="20dp"
android:layout_marginBottom="20dp"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:background="#drawable/input_border"
android:drawableRight="#drawable/eye_image"
android:hint="Your Password" />
eye_image.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:drawable="#drawable/eye_show"
android:width="25dp"
android:height="25dp"
/>
</layer-list>
java code
password.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
final int DRAWABLE_LEFT = 0;
final int DRAWABLE_TOP = 1;
final int DRAWABLE_RIGHT = 2;
final int DRAWABLE_BOTTOM = 3;
if(event.getAction() == MotionEvent.ACTION_UP) {
if(event.getRawX() >= (password.getRight() - password.getCompoundDrawables()
[DRAWABLE_RIGHT].getBounds().width())) {
// your action here
if(password.getTransformationMethod().equals(PasswordTransformationMethod.getInstance())){
//Show Password
((ImageView)(view)).setImageResource(R.drawable.eye_show);
password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
password.setSelection(password.getText().length());
}
else{
//Hide Password
((ImageView)(view)).setImageResource(R.drawable.eye_show);
password.setTransformationMethod(PasswordTransformationMethod.getInstance());
password.setSelection(password.getText().length());
}
}
}
return false;
}
});
I get this error - androidx.appcompat.widget.AppCompatEditText cannot be cast to android.widget.ImageView
I just want to make the image in the eye_image.xml drawable which is placed at the right of the editText to change to another image onClick
Found a way, This did the trick
editText.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.eye_image2, 0);
Related
I'm currently developing a simple Notes application where the user can input a title and the content of their note. What I am looking to achieve is that when the user clicks the note content (EditText) the soft keyboard comes up and only the note content EditText reduces in size (resizes) whilst everything else remains in the same position.
My current implementation can be seen below:
Manifest:
<activity android:theme="#style/AppTheme"
android:name=".AddActivity"
android:label="#string/add_record"
android:windowSoftInputMode="adjustResize"
android:parentActivityName=".MainActivity"
android:excludeFromRecents="true"/>
XML - Add Activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/add_record"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp">
<EditText
android:id="#+id/title_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/enter_title"
android:inputType="textCapSentences"
android:textColor="#color/fontPrimary"
android:theme="#style/EditTextCustomCursor">
<requestFocus />
</EditText>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/modify_scrollview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fitsSystemWindows="false"
android:isScrollContainer="false"
android:fillViewport="true">
<EditText
android:id="#+id/note_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#null"
android:ellipsize="end"
android:gravity="top|left"
android:hint="#string/enter_note"
android:inputType="textCapSentences|textMultiLine"
android:paddingLeft="5dp"
android:scrollHorizontally="false"
android:textColor="#color/fontPrimary"
android:theme="#style/EditTextCustomCursor" />
</ScrollView>
</LinearLayout>
Java - Add Activity
private int screenHeight;
private int actionBarHeight = 350;
private int keyboardHeight;
...
private void setupListeners() {
final LinearLayout layout = (LinearLayout) findViewById(R.id.add_record);
layout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
Rect r = new Rect();
layout.getWindowVisibleDisplayFrame(r);
screenHeight = layout.getRootView().getHeight();
keyboardHeight = screenHeight - (r.bottom - r.top);
Log.d("Keyboard Size", "Size: " + keyboardHeight);
}
});
KeyboardVisibilityEvent.setEventListener(
AddActivity.this,
new KeyboardVisibilityEventListener() {
#Override
public void onVisibilityChanged(boolean isOpen) {
if (isOpen) {
Log.d("KB", "openKeyboard");
scrollView.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT, screenHeight - actionBarHeight - keyboardHeight));
} else {
Log.d("KB", "closeKeyboard");
scrollView.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
}
}
});
}
This is using the Keyboard library (https://github.com/yshrsmz/KeyboardVisibilityEvent) to detect when the keyboard is opened or closed. This works perfectly and the height / layout is adjusted just how I want it to look but only if the user clicks at the top of the EditText. If the user clicks at the bottom of the EditText (if they have entered a long note) then the whole layout gets pushed up leaving a large gap at the bottom of the page.
Therefore, is there any way how wherever in the EditText / ScrollView the user clicks, for it to only adjust that one EditText in height and leave the other EditText in place at the top of the screen without pushing it and the SupportActionBar out of view? Also, the ScrollView is being used to achieve the vertical scrollbar on the right side of the screen - if this same behaviour can be achieved using just the EditText, then I would remove the ScrollView altogether.
EDIT - Add Photos
Image 1: Long note content (bottom of note content is at the bottom of the scrollView (which cannot be seen, until scrolled))
Image 2: Same note but clicking at the bottom, forces the top EditText and Support ActionBar out of view whilst leaving a gap at the bottom.
Explanation: Where the F is highlighted (in Image 2) that is the bottom of the EditText / ScrollView so you can see the large gap created between the top of the soft keyboard and the bottom of the EditText / ScrollView
Desired behaviour: Clicking anywhere in the bottom EditText should only resize that particular EditText to make room for the soft keyboard and ensure that this EditText is above the soft keyboard so the user can see what they are typing whilst the top EditText remains in the same position throughout.
Its because you're adding edittext in a scroll view. why do you even need scroll view? scroll view have a property of going to specific line when keyboard pop-up which is causing this behavior. if you really want to use scrollview, then add master layout as scrollview. add one direct child aka linear layout in there and add all the content in that linear layout.
I have managed to resolve most of this by doing the following:
Removing the ScrollView
Subclassing EditText (to receive the close keyboard button)
Adding a height-change listener
Adding the scroll bars property to the EditText
Manifest:
<activity android:theme="#style/AppTheme"
android:name=".AddActivity"
android:label="#string/add_record"
android:windowSoftInputMode="adjustNothing"
android:parentActivityName=".MainActivity"
android:excludeFromRecents="true"/>
XML - Add Activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/add_record"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp"
android:windowSoftInputMode="stateHidden">
<EditText
android:id="#+id/title_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/enter_title"
android:inputType="textCapSentences"
android:textColor="#color/fontPrimary"
android:theme="#style/EditTextCustomCursor">
<requestFocus />
</EditText>
<com.securenotes.ExtendedEditText
android:id="#+id/note_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#null"
android:ellipsize="end"
android:gravity="top|left"
android:hint="#string/enter_note"
android:inputType="textCapSentences|textMultiLine"
android:lines="50"
android:maxLines="20"
android:minLines="5"
android:paddingLeft="5dp"
android:scrollHorizontally="false"
android:scrollbars="vertical"
android:textColor="#color/fontPrimary"
android:theme="#style/EditTextCustomCursor" />
</LinearLayout>
Java - Add Activity:
private Boolean initialStart = true;
private Boolean isOpened = false;
...
private void setupListeners() {
final View activityRootView = getWindow().getDecorView().findViewById(android.R.id.content);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
Log.d("KB", "HeightDiff: " + heightDiff);
if (heightDiff > 100) { // 99% of the time the height diff will be due to a keyboard.
if (!isOpened && initialStart) {
Log.d("KB", "1) openKeyboard");
//Do two things, make the view top visible and the editText smaller
noteEditText.setLines(15);
noteEditText.requestLayout();
initialStart = false;
isOpened = true;
} else if (!isOpened && noteEditText.hasFocus()) {
Log.d("KB", "2) openKeyboard");
//Do two things, make the view top visible and the editText smaller
noteEditText.setLines(15);
noteEditText.requestLayout();
isOpened = true;
}
}
}
});
noteEditText.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("KB", "EditText onClick");
isOpened = false;
}
});
noteEditText.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
Log.d("KB", "closeKeyboard");
noteEditText.setLines(50);
noteEditText.requestLayout();
}
return false;
}
});
}
Java - Subclassed EditText:
public class ExtendedEditText extends EditText {
public ExtendedEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public ExtendedEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ExtendedEditText(Context context) {
super(context);
}
#Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
dispatchKeyEvent(event);
return false;
}
return super.onKeyPreIme(keyCode, event);
}
}
However, the one remaining issue is that if the user is scrolling the EditText, sometimes it detects it as a click rather than a scroll so the keyboard is then made visible and the layout (number of lines) is changed. I looked into the onScrollChangeListener but this requires API 23 and my current minimum is 15 - is there any way around this to tell the difference between a scroll and an actual click on the EditText?
I have a small Android Studio app to test the handling of keyboard inputs. It has an EditText field for a name, and a second EditText field for a decimal number. I am using setOnEditorActionListener to get the user input. I then store the entries in a string and double in a separate public class then attempt to display them in a TextView field when a button is clicked. I am concerned to ensure that I've actually definitely got the data in (so it can be used later by other activities).
In the public class, I initialize the string to "****" and the double to 0.0. But when I click the button to display the entered text, the four stars disappear and the field goes blank.
I haven't even tried displaying the entered number because the name text input and display are not working.
What am I doing wrong please? Any help would be much appreciated. Code follows.
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:hint="Name"
android:ems="10"
android:id="#+id/textin"
android:layout_marginTop="63dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:imeOptions="actionNext"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:hint= "Number"
android:ems="10"
android:id="#+id/numberin"
android:layout_below="#+id/textin"
android:layout_centerHorizontal="true"
android:imeOptions="actionDone"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="echo"
android:id="#+id/echo"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_below="#+id/echo"
android:layout_centerHorizontal="true"
android:layout_marginTop="42dp"/>
</RelativeLayout>
MainActivity.java
package com.example.owner.keyboardinput;
//imports here
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView echo = (TextView) findViewById(R.id.echo);
final Button button = (Button) findViewById(R.id.button);
final EditText textin = (EditText) findViewById(R.id.textin);
textin.setOnEditorActionListener(new TextView.OnEditorActionListener()
{
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
{
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_NEXT) {
String inputText1 = textin.getText().toString();
Common.str = inputText1; // Store in common public class
echo.setText(Common.str); // But input doesn't appear!
}
return handled;
}
});
final EditText numberin = (EditText) findViewById(R.id.numberin);
textin.setOnEditorActionListener(new TextView.OnEditorActionListener()
{
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
{
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_DONE) {
String inputText2 = numberin.getText().toString();
echo.setText(inputText2);
//Common.dbl = Double.valueOf(inputText);
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
handled = true;
}
return handled;
}
});
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
echo.setText(Common.str); // Field goes blank!
}
});
}
Common.java
package com.example.owner.keyboardinput;
/**
* Created by Owner on 13/11/2015.
*/
public class Common
{
public static String str = "****";
public static double dbl = 0.0;
}
You're calling setOnEditorActionListener() on the textin TextView twice. From your code, it looks like the second call should be on numberin.
...
final EditText numberin = (EditText) findViewById(R.id.numberin);
numberin.setOnEditorActionListener(new TextView.OnEditorActionListener()
...
You didn't use setOnEditorActionListener() for numberin, change one of textin.setOnEditorActionListener() to numberin.setOnEditorActionListener()
So, I have my buttons lined up like below:
Here's an image of what I'm trying to achieve:
In the image, the first row is just a row of buttons with no button pressed.
In the second row, only the first button is pressed. In the third row, I clicked on 4 and only the fourth button is pressed (not the first one anymore).
<RadioGroup
android:id="#+id/toggleGroup"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:useDefaultMargins="true"
android:layout_column="0"
android:columnCount="4"
android:rowCount="1"
android:orientation="horizontal"
>
<ToggleButton
android:id="#+id/number_zero"
android:layout_width="34sp"
android:layout_height="40sp"
android:textOn="#string/number_zero"
android:textOff="#string/number_zero"
android:onClick="onToggle"
android:checked="true"
android:background="#drawable/psc_number_color"
android:layout_margin="5sp"
/>
<ToggleButton
android:id="#+id/number_one"
android:layout_width="34sp"
android:layout_height="40sp"
android:textOn="#string/number_one"
android:textOff="#string/number_one"
android:onClick="onToggle"
android:checked="true"
android:background="#drawable/psc_number_color"
android:layout_margin="5sp"
/>
<ToggleButton
android:id="#+id/number_two"
android:layout_width="34sp"
android:layout_height="40sp"
android:textOn="#string/number_two"
android:textOff="#string/number_two"
android:background="#drawable/psc_number_color"
android:layout_margin="5sp"
/>
</RadioGroup>
I was wondering if it would be possible to toggle between these five buttons in such a way that if I pressed one down, the button would remain pressed. If I click on another button in that group, the button I clicked on before would depress and the new button I clicked on would be pressed down.
Trying to do this inside a pageradapter:
public void onToggle(View view) {
((RadioGroup)view.getParent()).check(view.getId());
// app specific stuff ..
}
public Object instantiateItem(ViewGroup parent, int position) {
one = (ToggleButton) view.findViewById(R.id.number_one);
two = (ToggleButton) view.findViewById(R.id.number_two);
three = (ToggleButton) view.findViewById(R.id.number_three);
four = (ToggleButton) view.findViewById(R.id.number_four);
final RadioGroup.OnCheckedChangeListener ToggleListener = new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(final RadioGroup radioGroup, final int i) {
for (int j = 0; j < radioGroup.getChildCount(); j++) {
final ToggleButton view = (ToggleButton) radioGroup.getChildAt(j);
view.setChecked(view.getId() == i);
}
}
};
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
one.toggle();
}
});
((RadioGroup) view.findViewById(R.id.toggleGroup)).setOnCheckedChangeListener(ToggleListener);
}
Try with this: I have done same things with Checkbox [ custom checkbox ].
#Override
public void onClick(View view) {
CheckBox cb = (CheckBox) view;
if(cb.isChecked()){
LinearLayout llLayout = (LinearLayout) cb.getParent();
for(int i=0; i<((ViewGroup)llLayout).getChildCount(); ++i) {
View nextChild = ((ViewGroup)llLayout).getChildAt(i);
if(nextChild instanceof CheckBox && nextChild.getId()==cb.getId() ){
}else if (nextChild instanceof CheckBox && nextChild.getId()!=cb.getId() ){
CheckBox cb2=(CheckBox) nextChild;
cb2.setChecked(false);
}
}
} else{
LinearLayout llLayout = (LinearLayout) cb.getParent();
for(int i=0; i<((ViewGroup)llLayout).getChildCount(); ++i) {
View nextChild = ((ViewGroup)llLayout).getChildAt(i);
if(nextChild instanceof CheckBox && nextChild.getId()==cb.getId() ){
CheckBox cb2=(CheckBox) nextChild;
cb2.setChecked(false);
}else if (nextChild instanceof CheckBox && nextChild.getId()!=cb.getId() ){
CheckBox cb2=(CheckBox) nextChild;
cb2.setChecked(false);
}
}
}
}
My XML:
<LinearLayout
android:id="#+id/llShift"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="4"
android:gravity="right"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/cbMorning"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="#drawable/custom_radio_button_morning"
android:paddingBottom="5dp"
android:paddingRight="3dp"
android:paddingTop="5dp" />
<CheckBox
android:id="#+id/cbEvning"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="#drawable/custom_radio_button_evening"
android:paddingBottom="5dp"
android:paddingRight="5dp"
android:paddingTop="5dp" />
</LinearLayout>
custom_radio_button_morning.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="#drawable/morning_chk"
android:state_checked="true"/>
<item
android:drawable="#drawable/morning_unchk"
android:state_checked="false"/>
</selector>
You should use custom toggle button - check this link here and here
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>
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.