Android Emulator Response:Unfortunately HelloWorld has stopped - java

I am following an online tutorial on Udemy. I created the default hello world app, but it would not load when I tried to run it! I decided to go to the next video and created a simple project that should display the text "Hello, World!" when a button is pressed, but I get this message on the emulator when I run the project:
Unfortunately Hello World has stopped.
I have been trying for hours searching multiple threads, but none seem to give me a solution. I am using the latest adt bundle (API 20) version 23. Here are the two files:
MainActivity.java
package com.ebook.helloworld;
import android.app.Activity;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onBtnTouch(View v){
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText("Hello, World!");
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.ebook.helloworld.MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:onClick="onBtnTouch"
android:text="Say Hi" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="93dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>

Where did you set up the button?
You should put in the onCreate:
Button button1 = (Button)this.findViewById (R.id.button1);
And then you can:
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//do what you want to do...
}
});

Related

Android App doesn't respond when clicking on the back-arrow button

Hello Fellow developers!
I have developed an Android App that uses the Flickr API to display any image upon users request. I am the final step of the development. Everything is looking great, except for when you click on any image to expand it in detail view & when you click the return arrow to go back - DOES NOT respond...
Any help would be greatly appreciated:)
ViewPhotoDetails.java:
package com.example.flickrbrowser;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import androidx.annotation.RequiresApi;
public class ViewPhotoDetailsActivity extends BaseActivity {
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photo_details);
activateToolbarWithHomeEnabled();
Intent intent = getIntent();
Photo photo = (Photo) intent.getSerializableExtra(PHOTO_TRANSFER);
TextView photoTitle = (TextView) findViewById(R.id.photo_title);
photoTitle.setText("Title: " + photo.getTitle());
TextView photoTags = (TextView) findViewById(R.id.photo_tags);
photoTags.setText("Tags: " + photo.getTags());
TextView photoAuthor = (TextView) findViewById(R.id.photo_author);
photoAuthor.setText(photo.getAuthor());
ImageView photoImage = (ImageView) findViewById(R.id.photo_image);
Picasso.with(this).load(photo.getLink())
.error(R.drawable.placeholder)
.placeholder(R.drawable.placeholder)
.into(photoImage);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_photo_details, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return false;
}
}
photo_details.xml:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:flickr="http://schemas.android.com/apk/res-auto"
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.flickrbrowser.ViewPhotoDetailsActivity"
tools:showIn="#layout/photo_details">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="#+id/app_bar"
layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize" />
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="16dp"
flickr:cardBackgroundColor="?colorPrimary"
flickr:cardCornerRadius="8dp"
flickr:cardPreventCornerOverlap="false"
flickr:contentPaddingTop="16dp"
flickr:contentPaddingBottom="16dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/photo_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:scaleType="centerCrop"
android:src="#drawable/placeholder" />
<TextView
android:id="#+id/photo_author"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|center"
android:paddingTop="8dp"
android:textColor="#color/flickrSecondaryTextColor"
android:textSize="14sp" />
</FrameLayout>
<TextView
android:id="#+id/photo_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:textColor="#color/flickrPrimaryTextColor"
android:textSize="14sp" />
<TextView
android:id="#+id/photo_tags"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:textColor="#color/flickrPrimaryTextColor"
android:textSize="10sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
</ScrollView>
Source Code on GitHub
App UI
Back button has id: android.R.id.home. So you can handle it as
if (item?.itemId == android.R.id.home) {
finish()
}
or just modify your
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (item.itemId == R.id.action_settings) {
// TODO - handle 'settings' click
}
return super.onOptionsItemSelected(item)
}
instead of returning just true/false so home button will be handled by super method.
Just as #Boken said, the back (also called the "up") button is a menu button which has id android.R.id.home so when that button is clicked you can handle the click like so:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
//You can also use if-else statements instead of switch (switch is a better option)
case R.id.action_settings:
return true;
case android.R.id.home: //when the back button is clicked
// handle this action here
return true;
default:
return super.onOptionsItemSelected(item);
}
}
if you want to return to the previous screen you use onBackPressed() like so:
case android.R.id.home: //when the back button is clicked
onBackPressed();
return true;
(More Direct Answer) Was not checking for that menu item. Had to change onOptionsItemSelected (in ViewPhotoDetailsActivity.java) to
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
} else if (id == android.R.id.home) {
finish();
}
return false;
}

Can anyone explain me how the execution process runs in this java code for Fragments in Android Studio [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I wrote this code according to the video tutorial found here
about Android Fragments, but I can't understand how the flow of execution runs through these codes. As in the tutorial I have made two fragments alone with the Main Activity. The whole program works fine, but I can't understand how the execution flow goes. Please be kind enough to explain me. Here are my source codes, I am
really sorry as they are too long, I posted all of my code. This is the Main Activity.java
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity implements top_layout_fragment.TopSelectionListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//overiding the method from the interface
#Override
public void createMeme(String top, String bottom) {
bottom_layout_fragment bottomLayoutFragment = (bottom_layout_fragment) getSupportFragmentManager().findFragmentById(R.id.fragment2);
bottomLayoutFragment.setText(top, bottom);
}
#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) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
this is the activity_main.xml
<?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: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">
<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="com.example.kasun.fragments.top_layout_fragment"
android:id="#+id/fragment"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
tools:layout="#layout/top_layout_fragment" />
<fragment
android:layout_width="320dp"
android:layout_height="320dp"
android:name="com.example.kasun.fragments.bottom_layout_fragment"
android:id="#+id/fragment2"
tools:layout="#layout/bottum_layout_fragment"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
this is the top_layout_fragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Button;
import android.app.Activity;
import java.util.ServiceConfigurationError;
public class top_layout_fragment extends Fragment {
private static EditText firstText, secondText;
TopSelectionListener activityCommand;
public interface TopSelectionListener {
public void createMeme(String top, String bottom);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
activityCommand = (TopSelectionListener) activity;
}
catch(ClassCastException e){
throw new ClassCastException (activity.toString());
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.top_layout_fragment, container, false);
firstText = (EditText) view.findViewById(R.id.firstText);
secondText = (EditText) view.findViewById(R.id.secondText);
final Button button = (Button) view.findViewById(R.id.button);
button.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
buttonClicked(v);
}
}
);
return view;
}
public void buttonClicked(View view) {
activityCommand.createMeme(firstText.getText().toString(), secondText.getText().toString());
}
}
this is top_layout_fragment.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">
<EditText
android:id="#+id/firstText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="320dp"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
/>
<EditText
android:id="#+id/secondText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="320dp"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/firstText"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#+id/secondText"
android:layout_marginTop="20dp"
android:text="#string/button_Texg"
android:id="#+id/button" />
</RelativeLayout>
this is the bottom_layout_fragment.java
package com.example.kasun.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.TextView;
public class bottom_layout_fragment extends Fragment {
private TextView topText,bottomText;
// need to overide the onCreateViewMethod
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.bottum_layout_fragment,container,false);
topText=(TextView)view.findViewById(R.id.topText);
bottomText=(TextView)view.findViewById(R.id.bottomText);
return view;
}
public void setText(String topText,String bottomText){
this.topText.setText(topText);
this.bottomText.setText(bottomText);
}
}
this is the bottom_layout_fragment.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="#drawable/image1">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/topText"
android:layout_marginTop="34dp"
android:textColor="#FFF"
android:gravity="center_horizontal"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/bottomText"
android:layout_alignParentBottom="true"
android:layout_alignLeft="#+id/topText"
android:layout_alignStart="#+id/topText"
android:layout_marginBottom="35dp"
android:textColor="#FFF"
android:gravity="center_horizontal" />
</RelativeLayout>
This is set up so you have one activity displaying two fragments. You can see both fragments are included in the activities layout file.
The top fragment needs to communicate with the bottom one to update its text and does so through an interface called TopSelectionListener. You will notice that your activity implements that interface. The other important part is the top fragment keeps a reference to your activity using the interface. You can see that in the top fragment's onAttach method. The activity displaying this fragment must implement the TopSelectionListener interface or else you will get a ClassCastException and your application will crash.
activityCommand = (TopSelectionListener) activity;
When the button is clicked in the top fragment it will call activityCommand.createMeme(...) which calls the createMeme method in your activity.
The createMeme method then looks up a reference to your bottom Fragment and calls the setText method on it to update the text it shows.
There is another example how this works in the Android documentation.

Why can't my android application find Text View or Buttons declared in the XML file?

I was following the tutorials online on Android Programming using Eclipse by New Boston and I am stuck at a particular point. So,everything was working fine, I had a button and a TextView in my GUI interface. Now, when i went to my java file and tried to locate it by using the R.Id..... it can't recognize the Button id or TextView Id declared in the XML file. Why am i getting this error? Can someone please correct my mistake. I am using Minimum SDK - API8- Android 2.2 ,Target SDK-API 13-Android 3.2 and Compiling with SDK- API 19- Android 4.4.
I checked the following article on Stack Overflow My Android application cannot find buttons declared in the XML file. As per the solution, I should delete the imports android.R from my java file and i dont have that import at all. So, i am kind of confused.
Main Activity.java
package com.example.androidprogram1;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
TextView display;
Button show;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show = (Button)findViewById(R.id.button1);
display = (TextView)findViewById(R.id.textView1);
//Error message:- Create field Button1 in type id (Suggestions) /create Constant TextView1 in type id.....This is the error i get. It seems that the id of the button and textView is not adding to the R.java file
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/tvView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.androidprogram1.MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_marginTop="65dp"
android:layout_toRightOf="#+id/textView1"
android:text="#string/hello_world" />
</RelativeLayout>
Thanks a lot.!!
You need to instantiate the TextView and Button
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show = (Button) findViewById(R.id.button1);
display = (TextView) findViewById(R.id.textView1);
}
Edit: Your error message seems to be an Eclipse problem, rather than something you've done, unless you went in and made changes to R.java, which you shouldn't do. Save your project, close it, re-open and re-build it. Also, if you happen to have import android.R in your class, remove it.

Starting another activity - application crash

At the beginning I notice that I'm novice at Android development.
I made application from http://developer.android.com/training/basics/firstapp/starting-activity.html and it worked well (second activity too). I want to make small change: in second activity I want to display "Your message:" text and below message from input from first activity. I did it my way and now when I tap Send button I have an application crash.
My second activity xml code:
<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="com.example.lislav.firstandroidapp.DisplayMessageActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/header_my_message"
android:textSize="40px"/>
<TextView
android:id="#+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="70px"/>
</RelativeLayout>
and second activity java code:
package com.example.lislav.firstandroidapp;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class DisplayMessageActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textViewMessage = (TextView) findViewById(R.id.message);
textViewMessage.setText(message);
setContentView(R.layout.activity_display_message);
}
#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) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I think it's something wrong with onCreate function.. But I don't know what. Sorry, if there are any obvious mistakes..
You must call findViewById method only after calling setContentView. Just put setContentView right after calling of super.onCreate.
By the way read about logcat tool. This is logger which you should use always facing any problem.

how to place the textview exactly where the user Long Presses in Eclipse for Android

I am learning to code in Eclipse for Android. I googled and understood that View.OnLongClickListener can be used to call a method when the user long presses in the application. However, I am stuck at coming at a solution to make the TextView to shift it based on the exact location where the user long presses.
I have implemented the condition to check for a long press from the user. Any idea on how to make the TextVIew appear where the user long presses? I want the TextView to appear exactly where the user long presses.
findViewById(R.id.myimage).setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
showNameInCustomPosition();// Method to call to when user long presses
return false;
}
});
Update: I am not getting the text to move, but when I click on the edge of the screen, the text is partially displayed that it goes outside the scope of the screen. Can anyone suggest how to avoid this? This is my Layout properties now.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/myimage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#drawable/shrinivas"
android:onClick="onClick"
android:clickable="true"
tools:context="com.example.hello.MainActivity" >
<TextView
android:id="#+id/shownamecenter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/my_text2" />
<TextView
android:id="#+id/shownamecustom"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_gravity="fill"
android:text="#string/my_text" />
</RelativeLayout>
The one with id shownamecustom is the one causing provblems.
Try this, below code is MainActivity which implements OnTouchListener
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends Activity implements OnTouchListener {
TextView move_textview;
RelativeLayout mainLayout;
int x,y; //used to get coordinates
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainLayout = (RelativeLayout)findViewById(R.id.mainlayout);
move_textview = (TextView)findViewById(R.id.textView1);
mainLayout.setOnTouchListener(this);//listener to get touch coordinates
mainLayout.setOnLongClickListener(new OnLongClickListener() { //listen when user long click
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
setAbsoluteLocation(move_textview,x,y); //passing textview, x & y param to the method where the textview wanna move
return false;
}
});
}
//methode use to move the text view
private void setAbsoluteLocation(TextView tview, int x, int y)
{
RelativeLayout.LayoutParams alp = (RelativeLayout.LayoutParams) tview.getLayoutParams();
alp.leftMargin = x-50;
alp.topMargin = y-50;
tview.setLayoutParams(alp);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//Overide onTouch method used to get touch coordinates
#Override
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
x = (int)event.getRawX();
y = (int)event.getRawY();
return false;
}
}
activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/mainlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.sample.MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="86dp"
android:layout_marginTop="171dp"
android:text="Movable" />
</RelativeLayout>

Categories

Resources