Android layout Not working - java

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>

Related

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.CardView.setVisibility(int)' on a null object reference

I am trying to animate a Cardview when FAB is pressed. I want to get circular animation. Initially Cardview is set to Invisible. But, it is trowing null object reference on CardView.setVisibility.
public class FeedFragment extends Fragment {
private FloatingActionButton floatingBtn;
private CardView cardView;
boolean flag = true;
public FeedFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_feed, container, false);
floatingBtn = view.findViewById(R.id.floatBtn);
cardView = view.findViewById(R.id.cardView);
floatingBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(flag) {
// Check if the runtime version is at least Lollipop
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
// get the center for the clipping circle
int cx = cardView.getWidth() / 2;
int cy = cardView.getHeight() / 2;
// get the final radius for the clipping circle
float finalRadius = (float) Math.hypot(cx, cy);
// create the animator for this view (the start radius is zero)
Animator anim =
ViewAnimationUtils.createCircularReveal(cardView, cx, cy, 0, finalRadius);
// make the view visible and start the animation
cardView.setVisibility(View.VISIBLE);
anim.start();
} else {
// set the view to visible without a circular reveal animation below Lollipop
cardView.setVisibility(View.VISIBLE);
}
flag = false;
} else {
// Check if the runtime version is at least Lollipop
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
// get the center for the clipping circle
int cx = cardView.getWidth() / 2;
int cy = cardView.getHeight() / 2;
// get the initial radius for the clipping circle
float initialRadius = (float) Math.hypot(cx, cy);
// create the animation (the final radius is zero)
Animator anim =
ViewAnimationUtils.createCircularReveal(cardView, cx, cy, initialRadius, 0);
// make the view invisible when the animation is done
anim.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
cardView.setVisibility(View.INVISIBLE);
}
});
// start the animation
anim.start();
} else {
// set the view to visible without a circular reveal animation below Lollipop
cardView.setVisibility(View.VISIBLE);
}
flag = true;
}
}
});
return view;
}
}
Here is the XML code
<FrameLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.authent.authentication.FeedFragment">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="bottom">
<android.support.v7.widget.CardView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="208dp"
android:layout_gravity="bottom"
android:layout_marginBottom="8dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_marginStart="16dp"
app:cardCornerRadius="20dp"
android:visibility="gone">
<LinearLayout
android:id="#+id/linearReveal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:visibility="gone">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/white"
android:text="Ask a Query"
android:textSize="24dp"
android:textAllCaps="false"
android:textColor="#00ccff"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray"/>
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/white"
android:text="Share Something"
android:textSize="24dp"
android:textAllCaps="false"
android:textColor="#ff3300"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray"/>
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/white"
android:text="Post an MCQ"
android:textSize="24dp"
android:textAllCaps="false"
android:textColor="#cc9900"/>
</LinearLayout>
</android.support.v7.widget.CardView>
<android.support.design.widget.FloatingActionButton
android:id="#+id/floatBtn"
android:layout_width="56dp"
android:layout_height="56dp"
android:layout_gravity="end"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:layout_marginRight="16dp"
android:src="#drawable/edit_nick_name" />
</LinearLayout>
Somebody help how to achieve circular animation. I am new to programming.
I also tried making LinearLayout INVISIBLE, it is also throwing NullPointerException on LinearLayout.setVisibility on a null object reference.
Thanks in advance.
Your CardView is null. Based on your code, you are trying to get the CardView from the View that received the onClick which is the FloatingButton.
Try calling the initialization outside just before the listener. Ideally on the same level as where you initialized the FloatingButton.
Intilaize cardview outside of the "clickListener".
You just need to remove this line cardView = view.findViewById(R.id.cardView);
and paste it before
floatingBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
return view;
}

App Crashes when using setVisibility

As the title says,
When using startLabel.setVisibility(View.GONE);
The app Crashes and I am not sure how to fix
The Java code below.
public class Main extends AppCompatActivity {
private TextView scoreLabel;
private TextView startLabel;
private ImageView box;
private ImageView orange;
private ImageView pink;
private ImageView black;
// Position
private int boxY;
private int boxX;
// Initialize Class
private Handler handler = new Handler();
private Timer timer = new Timer();
//Status Check
private boolean action_flg = false;
private boolean start_flg = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scoreLabel = (TextView) findViewById(R.id.scoreLabel);
scoreLabel = (TextView) findViewById(R.id.startLabel);
box = (ImageView) findViewById(R.id.box);
orange = (ImageView) findViewById(R.id.orange);
pink = (ImageView) findViewById(R.id.pink);
black = (ImageView) findViewById(R.id.black);
//Moves images to out of the screen
//orange.setX(-80.0f);
orange.setY(-80.0f);
// pink.setX(-80.0f);
pink.setY(-80.0f);
//black.setX(-80.0f);
black.setY(-80.0f);
boxY = 200;
}
public void changePos()
{
//Move box
if (action_flg == true)
{
// touching
boxY -= 20;
} else {
//released
boxY += 20;
}
box.setY(boxY);
}
public boolean onTouchEvent(MotionEvent me)
{
if (start_flg == false)
{
start_flg = true;
//Issue here with setting the visibility of the start
// startLabel.setVisibility(View.GONE);
timer.schedule(new TimerTask()
{
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
changePos();
}
});
}
// Changing these numbers slows down how fast the box moves.
}, 0, 100);
}else {
if(me.getAction() == MotionEvent.ACTION_DOWN)
{
action_flg = true;
}else if (me.getAction() == MotionEvent.ACTION_UP){
action_flg = false;
}
}
return true;
}
}
Here is the XML version of the code.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="me.scott.nathan.catchtheball.Main">
<TextView
android:id="#+id/scoreLabel"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="Score : 300"
android:textSize="18sp"
android:paddingLeft="10dp"
android:gravity="center_vertical">
</TextView>
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/startLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tap to Start"
android:textSize="30sp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="130dp"
/>
<ImageView
android:id="#+id/box"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/box"
android:layout_gravity="center_vertical"
/>
<ImageView
android:id="#+id/orange"
android:layout_width="20dp"
android:layout_height="20dp"
android:src="#drawable/orange" />
<ImageView
android:id="#+id/black"
android:layout_width="24dp"
android:layout_height="24dp"
android:src="#drawable/black" />
<ImageView
android:id="#+id/pink"
android:layout_width="16dp"
android:layout_height="16dp"
android:src="#drawable/pink" />
</FrameLayout>
<!--
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.22" />
-->
</LinearLayout>
Anyone help appreciated to fix this issue, Thanks
Your startLabel is null (copy paste problem?^^). Replace this:
scoreLabel = (TextView) findViewById(R.id.startLabel);
with this:
startLabel = (TextView) findViewById(R.id.startLabel);

Making button move on Touch at exact position where we touch

I have created an application in which there is a button which moves on touching it .
Now for onTouch I have implemented A different class.There are 2 classes one is main CircleMActivity.java and another for onTouch.
Now the app is running fine but there is one problem. When I am clicking on the button and moving it It is moving but there is a gap between the button and the screen touch.
What I want is to move it exactly where I touch it NOT at some distance later OR you can think that I want to move it at exact the cursor position.
How should I achieve it ?
Code:
CircleMActivity.java:
public class CircleMActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_circle_m);
Button b=(Button)findViewById(R.id.btn1);
MultiTouch mtb=new MultiTouch(this);
b.setOnTouchListener(mtb);
}
}
MultiTouch.java:
public class MultiTouch implements OnTouchListener{
float mPrevX,mPrevY;
CircleMActivity cm;
public MultiTouch(CircleMActivity circleMActivity) {
// TODO Auto-generated constructor stub
cm=circleMActivity;
}
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
float currentX,currentY;
int action=arg1.getAction();
switch(action){
case MotionEvent.ACTION_DOWN:
mPrevX = arg1.getX();
mPrevY = arg1.getY();
break;
case MotionEvent.ACTION_MOVE:
currentX = arg1.getRawX();
currentY = arg1.getRawY();
MarginLayoutParams marginParams = new MarginLayoutParams( arg0.getLayoutParams());
marginParams.setMargins((int)( currentX - mPrevX), (int)( currentY - mPrevY),0, 0);
LayoutParams layoutParams = new LinearLayout.LayoutParams(marginParams);
arg0.setLayoutParams(layoutParams);
break;
case MotionEvent.ACTION_CANCEL:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
}
activity_circle.xml:
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#000000"
android:weightSum="100">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="4.95"
android:background="#fff"
android:orientation="vertical" >
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="X coord"
android:textColor="#ff00ee"
android:inputType="number" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Y coord"
android:textColor="#ff00ee"
android:inputType="number" />
<EditText
android:id="#+id/editText3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Radius"
android:textColor="#ff00ee"
android:inputType="number" />
<EditText
android:id="#+id/editText4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:textColor="#ff00ee"
android:hint="Colour"
android:inputType="number" />
</LinearLayout>
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4.95"
android:background="#drawable/custom" />
"
</LinearLayout>
So how should I achieve it ?
It is a simple coordinates maths . In your
case MotionEvent.ACTION_DOWN:
mPrevX = arg1.getX();
mPrevY = arg1.getY();
break;
Make
mPrevY = arg1.getY()+250;
Well It will go out of the child linear layout but it is looking good !

Error in property animation

I'm creating a small application for practice some in Android programming. It's a kind of puzzle game like this:
Screen from application
I have a following issue: when I slide a button left or right in x property all is OK. I can move each button frequently left and right. The problem begins when I move the button down or up in y property. I can only move the button once and next it will be no longer available for the onTouchListener. It become immobile in any direction and any action isn't performed. Here is my java activity file and the layout xml.
MainActivity.java
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
class MyPoint{
private boolean canMove;
private View associatedView;
private int x;
private int y;
private MyPoint nord;
private MyPoint south;
private MyPoint est;
private MyPoint west;
MyPoint(int x, int y, View associatedView){
this.x = x;
this.y = y;
this.associatedView = associatedView;
canMove = false;
}
public MyPoint getEst() {
return est;
}
public MyPoint getNord() {
return nord;
}
public MyPoint getSouth() {
return south;
}
public MyPoint getWest() {
return west;
}
public void setNeighbors(MyPoint nord, MyPoint south, MyPoint west, MyPoint est){
this.nord = nord;
this.south = south;
this.est = est;
this.west = west;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public View getAssociatedView() {
return associatedView;
}
public void setAssociatedView(View associatedView) {
this.associatedView = associatedView;
}
public boolean isSpace(){
if(associatedView.getId() == R.id.space)
return true;
else
return false;
}
public void allowMovement(){
canMove = true;
}
public void denyMovement(){
canMove = false;
}
public void allowMovementNeighbords(){
nord.allowMovement();
south.allowMovement();
est.allowMovement();
west.allowMovement();
}
public boolean isMoveable(){
if(canMove) return true;
else return false;
}
}
public class MainActivity extends ActionBarActivity {
LinearLayout mainScreen;
MyPoint[] board = new MyPoint[16];
View[] views = new View[16];
View blank;
MyPoint blankPoint, associatedPoint;
int DX,DY;
private MyPoint findPointByView(View target){
MyPoint tempResult = blankPoint;
for(int i=0; i<16; i++)
if(board[i].getAssociatedView().getId() == target.getId())
tempResult = board[i];
return tempResult;
}
private MyPoint findSpace(){
MyPoint tempResult = blankPoint;
for(int i=0; i<16; i++)
if(board[i].isSpace()){
tempResult = board[i];
}
return tempResult;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainScreen = (LinearLayout) findViewById(R.id.main_screen);
blank = findViewById(R.id.blank);
blankPoint = new MyPoint(0,0,blank);
blankPoint.setNeighbors(blankPoint,blankPoint,blankPoint,blankPoint);
associatedPoint = blankPoint;
final View.OnTouchListener mTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event){
float x1=0, x2, y1=0, y2, dx, dy;
switch(event.getActionMasked()) {
case(MotionEvent.ACTION_DOWN):
associatedPoint = findPointByView(v);
x1 = event.getX();
y1 = event.getY();
break;
case(MotionEvent.ACTION_UP): {
x2 = event.getX();
y2 = event.getY();
dx = x2-x1;
dy = y2-y1;
if(associatedPoint.isMoveable()){
if(Math.abs(dx) > Math.abs(dy)) {
if(dx>0){
if(associatedPoint.getEst().isSpace()){
v.animate().xBy(DX);
associatedPoint.setAssociatedView(findViewById(R.id.space));
associatedPoint.getEst().setAssociatedView(v);
}
}
else{
if(associatedPoint.getWest().isSpace()){
v.animate().xBy(-DX);
associatedPoint.setAssociatedView(findViewById(R.id.space));
associatedPoint.getWest().setAssociatedView(v);
}
}
} else {
if(dy>0){
if(associatedPoint.getSouth().isSpace()){
v.animate().yBy(DY);
associatedPoint.setAssociatedView(findViewById(R.id.space));
associatedPoint.getSouth().setAssociatedView(v);
}
}
else{
if(associatedPoint.getNord().isSpace()){
v.animate().yBy(-DY);
associatedPoint.setAssociatedView(findViewById(R.id.space));
associatedPoint.getNord().setAssociatedView(v);
}
}
}
denyMovementAll();
findSpace().allowMovementNeighbords();
}
return true;
}
}
return false;
}
};
views[0] = findViewById(R.id.button1);
views[1] = findViewById(R.id.button2);
views[2] = findViewById(R.id.button3);
views[3] = findViewById(R.id.button4);
views[4] = findViewById(R.id.button5);
views[5] = findViewById(R.id.button6);
views[6] = findViewById(R.id.button7);
views[7] = findViewById(R.id.button8);
views[8] = findViewById(R.id.button9);
views[9] = findViewById(R.id.button10);
views[10] = findViewById(R.id.button11);
views[11] = findViewById(R.id.button12);
views[12] = findViewById(R.id.button13);
views[13] = findViewById(R.id.button14);
views[14] = findViewById(R.id.button15);
views[15] = findViewById(R.id.space);
for(int i=0; i<15; i++)
views[i].setOnTouchListener(mTouchListener);
}
private void denyMovementAll() {
for(int i=0; i<16; i++)
board[i].denyMovement();
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int offsetY = displayMetrics.heightPixels - mainScreen.getMeasuredHeight();
for (int i=0 ; i<16; i++){
int[] tempCoords = new int[2];
views[i].getLocationOnScreen(tempCoords);
int x = tempCoords[0];
int y = tempCoords[1] - offsetY;
board[i] = new MyPoint(x,y,views[i]);
}
board[0].setNeighbors(blankPoint,board[4],blankPoint,board[1]);
board[1].setNeighbors(blankPoint,board[5],board[0],board[2]);
board[2].setNeighbors(blankPoint,board[6],board[1],board[3]);
board[3].setNeighbors(blankPoint,board[7],board[2],blankPoint);
board[4].setNeighbors(board[0],board[8],blankPoint,board[5]);
board[5].setNeighbors(board[1],board[9],board[4],board[6]);
board[6].setNeighbors(board[2],board[10],board[5],board[7]);
board[7].setNeighbors(board[3],board[11],board[6],blankPoint);
board[8].setNeighbors(board[4],board[12],blankPoint,board[9]);
board[9].setNeighbors(board[5],board[13],board[8],board[10]);
board[10].setNeighbors(board[6],board[14],board[9],board[11]);
board[11].setNeighbors(board[7],board[15],board[10],blankPoint);
board[12].setNeighbors(board[8],blankPoint,blankPoint,board[13]);
board[13].setNeighbors(board[9],blankPoint,board[12],board[14]);
board[14].setNeighbors(board[10],blankPoint,board[13],board[15]);
board[15].setNeighbors(board[11],blankPoint,board[14],blankPoint);
DX = board[1].getX() - board[0].getX();
DY = board[4].getY() - board[0].getY();
denyMovementAll();
findSpace().allowMovementNeighbords();
}
}
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: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"
android:collapseColumns="4"
android:orientation="vertical"
android:clipChildren="false"
android:id="#+id/main_screen"
android:clipToPadding="false">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:clipChildren="false"
android:clipToPadding="false"
android:id="#+id/row1">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b1"
android:id="#+id/button1"
android:layout_weight="1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b2"
android:id="#+id/button2"
android:layout_weight="1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b3"
android:id="#+id/button3"
android:layout_weight="1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b4"
android:id="#+id/button4"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:clipChildren="false"
android:clipToPadding="false"
android:id="#+id/row2">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b5"
android:id="#+id/button5"
android:layout_weight="1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b6"
android:id="#+id/button6"
android:layout_weight="1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b7"
android:id="#+id/button7"
android:layout_weight="1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b8"
android:id="#+id/button8"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:clipChildren="false"
android:clipToPadding="false"
android:id="#+id/row3">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b9"
android:id="#+id/button9"
android:layout_weight="1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b10"
android:id="#+id/button10"
android:layout_weight="1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b11"
android:id="#+id/button11"
android:layout_weight="1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b12"
android:id="#+id/button12"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:clipChildren="false"
android:clipToPadding="false"
android:id="#+id/row4">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b13"
android:id="#+id/button13"
android:layout_weight="1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b14"
android:id="#+id/button14"
android:layout_weight="1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b15"
android:id="#+id/button15"
android:layout_weight="1" />
<Space
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="#+id/space"
android:visibility="invisible"/>
<Space
android:layout_width="0dp"
android:layout_height="0dp"
android:visibility="invisible"
android:id="#+id/blank"/>
</LinearLayout>
</LinearLayout>
I have really no idea what cause this problem. Please give me a small prompt on what may cause this issue. Thanks in advance
You should return true if the listener has consumed the event. Otherwise, it should return false as default.
View.OnTouchListener mTouchListener = new View.OnTouchListener() {
...
return false;
}
I changed my code following your tip :
View.OnTouchListener mTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event){
float x1=0, x2, y1=0, y2, dx, dy;
switch(event.getActionMasked()) {
case(MotionEvent.ACTION_DOWN):
x1 = event.getX();
y1 = event.getY();
break;
case(MotionEvent.ACTION_UP): {
x2 = event.getX();
y2 = event.getY();
dx = x2-x1;
dy = y2-y1;
if(Math.abs(dx) > Math.abs(dy)) {
if(dx>0){
v.animate().xBy(DX);
}
else{
v.animate().xBy(-DX);
}
} else {
if(dy>0){
v.animate().yBy(DY);
}
else{
v.animate().yBy(-DY);
}
}
return true;
}
}
return false;
}
};
Unfortunately, that doesn't solve my problem. Please, correct me if I made a mistake

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