How to add more views, buttons to activity - android

I have a problem. I make a class DrawingView with button etc. and on activity i call it
public class PaintActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DrawingView view=new DrawingView(this);
setContentView(view);
addContentView(view.btnEraseAll, view.params);
}
and here is my configuration
class DrawingView extends View {
private Paint brush = new Paint();
private Path path = new Path();
public Button btnEraseAll, btnAccept, btnBack;
public ViewGroup.LayoutParams params;
public DrawingView(Context context) {
super(context);
brush.setAntiAlias(true);
brush.setColor(Color.BLACK);
brush.setStyle(Paint.Style.STROKE);
brush.setStrokeJoin(Paint.Join.ROUND);
brush.setStrokeWidth(22f);
btnEraseAll = new Button(context);
btnEraseAll.setText("Clear");
btnAccept = new Button(context);
btnAccept.setText("Accept");
btnBack = new Button(context);
btnBack.setText("Back");
params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
btnEraseAll.setLayoutParams(params);
btnAccept.setLayoutParams(params);
btnBack.setLayoutParams(params);
btnEraseAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
path.reset();
postInvalidate();
}
});
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, brush);
}
public boolean onTouchEvent(MotionEvent event) {
float pointX = event.getX();
float pointY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(pointX, pointY);
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(pointX, pointY);
break;
default:
return false;
}
postInvalidate();
return false;
}
}
but how i can add more buttons(i have 3) to activity main?
here i add button
addContentView(view.btnEraseAll, view.params);
But i want add this buttons too
btnAccept, btnBack;
can anyone help me? I want to add 3 buttons in view.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/monitor"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/MyCustomActionBar">
<activity
android:name=".MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".WiFiServiceDiscoveryActivity" />
<activity android:name=".PaintActivity" />
</application>
</manifest>

I refactored some of your code to make it easier to undertand.
I also extracted the buttons in .xml instead of creating them programmatically because it is much easier. I also extracted the DrawingView to a separate class. I also tested it so it works for sure.
public class PaintActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paint);
final DrawingView drawingView = (DrawingView) findViewById(R.id.drawing_canvas);
View clearBtn = findViewById(R.id.btn_clear);
clearBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
drawingView.reset();
}
});
}
}
class DrawingView extends View {
private Paint brush = new Paint();
private Path path = new Path();
public DrawingView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
brush.setAntiAlias(true);
brush.setColor(Color.BLACK);
brush.setStyle(Paint.Style.STROKE);
brush.setStrokeJoin(Paint.Join.ROUND);
brush.setStrokeWidth(22f);
}
public void reset() {
path.reset();
postInvalidate();
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, brush);
}
public boolean onTouchEvent(MotionEvent event) {
float pointX = event.getX();
float pointY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(pointX, pointY);
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(pointX, pointY);
break;
default:
return false;
}
postInvalidate();
return false;
}
}
activity_paint.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">
<com.example.myapplication.DrawingView
android:id="#+id/drawing_canvas"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<Button
android:id="#+id/btn_clear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:text="Clear"/>
<Button
android:id="#+id/btn_accept"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Accept"/>
<Button
android:id="#+id/btn_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="Back"/>
</RelativeLayout>
ids.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="btn_clear" type="id"/>
<item name="btn_accept" type="id"/>
<item name="btn_back" type="id"/>
</resources>
You can also download the entire project from here: http://expirebox.com/download/130bc35765d0d4704c0e105627077281.html

Related

unable to use ScaleGestureDetector for Pinch Zoom

I have a class that simply displays an image. And I want to implement zoom in/out effect by pinch, so I refer to the code here.
public class FullScreenImageActivity extends AppCompatActivity {
public static final String IMAGE = "IMAGE";
public static Bitmap image;
private float mScaleFactor = 1.0f;
private ScaleGestureDetector mScaleGestureDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_screen_image);
ConstraintLayout fullscreen_background = findViewById(R.id.fullscreen_background);
fullscreen_background.setOnClickListener(v -> finish());
ImageView fullscreen_image = findViewById(R.id.fullscreen_image);
mScaleGestureDetector = new ScaleGestureDetector(this, new ScaleGestureDetector.OnScaleGestureListener() {
#Override
public void onScaleEnd(ScaleGestureDetector detector) {
Log.d("fuck", "onScaleEnd");
}
#Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
Log.d("fuck", "onScaleBegin");
return true;
}
#Override
public boolean onScale(ScaleGestureDetector detector) {
Log.d("fuck", "onScale");
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor * detector.getScaleFactor(), 10.0f));
fullscreen_image.setScaleX(mScaleFactor);
fullscreen_image.setScaleY(mScaleFactor);
return true;
}
});
if (image == null) Helper.LoadImage(Glide.with(this), getIntent().getStringExtra(IMAGE), fullscreen_image);
else fullscreen_image.setImageBitmap(image);
}
#Override
public boolean onTouchEvent(MotionEvent motionEvent) {
Log.d("fuck", "onTouchEvent");
return mScaleGestureDetector.onTouchEvent(motionEvent);
}
#Override
public void finish() {
super.finish();
image = null;
}
}
But my code doesn't seem to work. None of the logs is printed out. Any ideas?
I also have another question, how can I finish this activity only when not tapping on the image?
This is the layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/fullscreen_background"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/black">
<ImageView
android:id="#+id/fullscreen_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerInside"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/food_image_place_holder" />
</android.support.constraint.ConstraintLayout>
My project is here.
Try using this custom image view i have created to handle pinch and drag operaions on image.
ZoomDragImageView

Setting OnClick within class extending ImageView

I have a class called examplecanvas.java that extends ImageView. The class is called by a custom view in an XML. In that XML there is a button for which I want to set an OnClick in examplecanvas.java.
I have put the OnClickListener in the OnTouchEvent, but it does not work. Here is my code:
examplecanvas.java (extending ImageView):
public class examplecanvas extends ImageView {
float xPos, yPos;
private PointF point;
public examplecanvas(Context context) {
super(context);
}
public examplecanvas(Context context, AttributeSet attrs) {
super(context, attrs);
}
public examplecanvas(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
public boolean onTouchEvent(#NonNull MotionEvent event) {
Button savepoints = (Button) findViewById(R.id.btnpdf );
savepoints public void onClick(View ImageView) {
Toast.makeText(getContext(), "points saved", Toast.LENGTH_SHORT).show();
}
});
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
point = new PointF(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
point.set(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
point.set(x, y);
invalidate();
break;
case MotionEvent.ACTION_CANCEL:
point.set(x, y);
invalidate();
break;
}
return true;
}
#Override
protected void onDraw(#NonNull Canvas canvas) {
super.onDraw(canvas);
float flat = (float)doublelat;
float flon = (float)doublelon;
canvas.drawCircle(flat, flon, 100, paint);
if (point != null) {
canvas.drawCircle(point.x, point.y, 100, paint);
canvas.save();
}
}
}
The XML:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.joanzapata.pdfview.PDFView
android:id="#+id/pdfView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<view
class="com.myapp.trial10.examplecanvas"
android:layout_gravity="center"
android:id="#+id/yourID2"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:text="save"
android:id="#+id/btnpdf"
android:layout_gravity="center_horizontal|bottom" />
</FrameLayout>
The Activity:
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import com.joanzapata.pdfview.PDFView;
public class pdfview3 extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdfview3);
String assetFileName = "proposed.pdf"; //The name of the asset to open
int pageNumber = 0; //Start at the first page
PDFView pdfView = (PDFView) findViewById(R.id.pdfView); //Fetch the view
pdfView.fromAsset(assetFileName) //Fill it with data
.defaultPage(pageNumber) //Set default page number
.onPageChange(null) //PageChangeListener
.enableSwipe(false)
.load();
}
}
So you want to add onClickListener for the ImageView?
-add setOnClickListener(this); in on create
-make class implement OnClickListener
-implement onClick method
-rename view in xml with View(or put directly package.examplecanvas instead of view and remove class=...)

How to trigger Wallpaperservice.enigine class using alarm manager. (I don't want to use RTC_Wakeup)

I am developing a wallpaper app. Which create a folder in external storage if that folder don't exist. User set time interval. Then app will set wallpaper (if not empty) from that folder in interval provided by user.
File dir= new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+"imagesWallpaper");
if(!dir.isDirectory())
dir.mkdirs();
It is not creating folder i exteral memory don,t know why
2.I triggered wallpaper service but i don,t know why it is not starting WallpaperEngine class .please help.
WallpaperMainActivity:
public class WallpaperMainActivity extends Activity {
private RadioGroup radioGroup;
public long interval = 0;
File[] wallpaperImages = null;
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wall_paper_manager);
File dir= new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+"imagesWallpaper");
if(!dir.isDirectory())
dir.mkdirs();
radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
long time =Integer.valueOf((String) findViewById(checkedId).getTag());
interval = time*60000;
scheduleAlarm();
}
});
}
public void scheduleAlarm()
{
Intent intent = new Intent(WallpaperMainActivity.this, WallpaperSrvc.class);
PendingIntent pintent = PendingIntent.getService(WallpaperMainActivity.this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC, 10*1000, interval, pintent);
}
}
WallpaperSrvc and WallpaperEngine classes:
public class WallpaperSrvc extends WallpaperService {
File[] wallpaperImages = null;
int count = 0;
Bitmap tmp = null;
//Drawable drawable;
#Override
public Engine onCreateEngine() {
return new WallpaperEngine();
}
public class WallpaperEngine extends Engine {
private boolean mVisible = true;
#Override
public void onVisibilityChanged(boolean visible) {
mVisible = visible;
if (visible)
{
getImage();
draw();
}
else
{
stopSelf();// stop the wallpaper
}
super.onVisibilityChanged(visible);
}
#Override
public void onOffsetsChanged(float xOffset, float yOffset,
float xOffsetStep, float yOffsetStep, int xPixelOffset,
int yPixelOffset) {
draw();
super.onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep,
xPixelOffset, yPixelOffset);
}
#Override
public void onSurfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
super.onSurfaceChanged(holder, format, width, height);
}
#Override
public void onSurfaceCreated(SurfaceHolder holder) {
getImage();
super.onSurfaceCreated(holder);
}
#Override
public void onSurfaceDestroyed(SurfaceHolder holder) {
super.onSurfaceDestroyed(holder);
mVisible = false;
stopSelf();
// stop the wallaperservice
}
}
public void getImage()
{
File dir= new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+"imagesWallpaper");
if(!dir.exists())
dir.mkdir();
else
wallpaperImages = dir. listFiles();
if(count < wallpaperImages.length)
{
this.tmp = BitmapFactory.decodeFile(wallpaperImages[count].getAbsolutePath());
count++;
}
else
{
count = 0;
this.tmp = BitmapFactory.decodeFile(wallpaperImages[count].getAbsolutePath());
}
};
public void draw() {
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try
{
//Bitmap wallpaper = ((BitmapDrawable) drawable).getBitmap();
myWallpaperManager.setBitmap(tmp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}
Manifest:
<uses-sdk
android:minSdkVersion="17"
android:targetSdkVersion="21" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<service
android:name=".WallpaperSrvc"
android:enabled="true"
android:label="wallpaper_service"
android:icon="#drawable/ic_launcher"
android:permission="android.permission.BIND_WALLPAPER" >
<intent-filter>
<action android:name="android.service.wallpaper.WallpaperService" >
</action>
</intent-filter>
<meta-data
android:name="android.service.wallpaper"
android:resource="#xml/mywallpaper" >
</meta-data>
</service>
<activity
android:name=".WallpaperMainActivity"
android:exported="true"
android:label="#string/app_name"
android:theme="#android:style/Theme.Light.WallpaperSettings" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".WallpaperSrvc"/>
</application>
</manifest>
Main Activity Layout:
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="0dp"
android:orientation="horizontal"
android:text="#string/Discription"
android:textAppearance="?android:attr/textAppearanceLarge" />
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checkedButton="#+id/one_day"
android:clickable="true"
android:orientation="vertical"
android:scrollbars="vertical" >
<RadioButton
android:id="#+id/oneminute"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1 minute"
android:tag="1"/>
<RadioButton
android:id="#+id/thirty_minutes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="30 minutes"
android:tag="30"/>
<RadioButton
android:id="#+id/one_hour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1 hour"
android:tag="60"/>
<RadioButton
android:id="#+id/two_hours"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2 hours"
android:tag="120"/>
<RadioButton
android:id="#+id/six_hours"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="6 hours"
android:tag="360"/>
<RadioButton
android:id="#+id/tvlv_hours"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="12 hours"
android:tag="720"/>
<RadioButton
android:id="#+id/one_day"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1 day"
android:tag="1440"/>
<RadioButton
android:id="#+id/three_days"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3 days"
android:tag="4320"/>
<RadioButton
android:id="#+id/oneweek"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="week"
android:tag="10080"/>
</RadioGroup>
</LinearLayout>
</LinearLayout>
res/xml/mywallpaper.xml:
<?xml version="1.0" encoding="UTF-8"?>
<wallpaper
xmlns:android="http://schemas.android.com/apk/res/android"
android:thumbnail="#drawable/ic_launcher"
android:description="#string/wallpaper_description"
android:settingsActivity="com.wallpaper.WallpaperMainActivity"/>
you have to use write external storage permission. thats why its not creating your directory.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
add this along with your Alarm and Wallpaper persmissions in your manifest

Chat-Heads-Like Popup window

I searched the web for how to make a popup window like Facebook's Chat Heads.
I found the following code: http://www.piwai.info/chatheads-basics/
public class ChatHeadService extends Service {
private WindowManager windowManager;
private ImageView chatHead;
#Override public IBinder onBind(Intent intent) {
// Not used
return null;
}
#Override public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
chatHead = new ImageView(this);
chatHead.setImageResource(R.drawable.ic_launcher);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 0;
params.y = 100;
windowManager.addView(chatHead, params);
}
#Override
public void onDestroy() {
super.onDestroy();
if (chatHead != null) windowManager.removeView(chatHead);
}
}
In my Main Activity:
startService(new Intent(context, ChatHeadService.class));
And I use the permission:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
But I don't get the popup notification. Not even his icon.
Can you help me an say what's wrong?
Thanks.
Check if you have added your service to AndroidManifest.xml
<service android:name=".ChatHeadService" ></service>
Try Copy/Paste this in your project or you can create a new project and copy/paste this into it(with the required imports).
MainActivity.class
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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);
}
// Method to start the service
public void startService(View view) {
startService(new Intent(getBaseContext(), ChatHeadService.class));
}
// Method to stop the service
public void stopService(View view) {
stopService(new Intent(getBaseContext(), ChatHeadService.class));
}
}
ChatHeadService.class
public class CloseChatHead extends Service {
private WindowManager windowManager;
private ImageView close;
#Override
public IBinder onBind(Intent intent) {
// Not used
return null;
}
WindowManager.LayoutParams mParams;
public WindowManager.LayoutParams getParams(){
return mParams;
}
#Override
public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
close = new ImageView(this);
close.setImageResource(R.drawable.circle_close);
final WindowManager.LayoutParams params1 = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params1.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
//params1.x = 0;
//params1.y = 100;
mParams=params1;
close.setOnTouchListener(new View.OnTouchListener() {
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Toast.makeText(getApplicationContext(),"ACTION_DOWN 2",Toast.LENGTH_SHORT).show();
initialX = params1.x;
initialY = params1.y;
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
return true;
case MotionEvent.ACTION_UP:
return true;
case MotionEvent.ACTION_MOVE:
params1.x = initialX
+ (int) (event.getRawX() - initialTouchX);
params1.y = initialY
+ (int) (event.getRawY() - initialTouchY);
windowManager.updateViewLayout(close, params1);
return true;
}
return false;
}
});
windowManager.addView(close, params1);
}
#Override
public void onDestroy() {
super.onDestroy();
if (close != null)
windowManager.removeView(close);
}
}
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.example.chathead.MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btnStartService"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="startService"
android:text="start_service" />
<Button
android:id="#+id/btnStopService"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="stopService"
android:text="stop_service" />
</LinearLayout>
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.chathead"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".ChatHeadService" />
<service android:name=".CloseChatHead" />
</application>
</manifest>
Reference for the same: http://www.piwai.info/chatheads-basics/

how can i make menubar on top of all activity (like GameCIH)

im new in android.
here is the deal. i want make my activity be like GameCih menubar (like on top of all activity and i can go around apps and do whatever i want and menubar still on top)
but what i want to do is not exactly same with GameCIH . i want music player so i can play songs and show album art and moving player menu around of screen by touch.
here is my main activity :
public class MainActivity extends Activity implements OnTouchListener{
RelativeLayout rel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
rel = (RelativeLayout) findViewById(R.id.myactivity);
rel.setOnTouchListener(this);
this.setFinishOnTouchOutside(false);
this.getWindow().setBackgroundDrawable(new ColorDrawable(0));
Window dialogWindow = this.getWindow();
// Make the dialog possible to be outside touch
dialogWindow.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
dialogWindow.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
Button btn =(Button)findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
Thread th = new Thread(){
public void run (){
try {
while(true){
Thread.sleep(10000);
try{
Intent i=new Intent(getApplicationContext(),MainActivity.class);
//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
}catch(Exception ex){
Log.d("X",ex.getMessage());
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
th.start();
}
#Override
public void onBackPressed() {
// Do Here what ever you want do on back press;
}
#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 onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
if(rel==arg0){
switch(arg1.getAction())
{
case MotionEvent.ACTION_MOVE:
{
WindowManager.LayoutParams layoutParams = this.getWindow().getAttributes();
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
layoutParams.x = ((int) arg1.getRawX()-400);
layoutParams.y = ((int) arg1.getRawY()-200);
this.getWindow().setAttributes(layoutParams);
return true;
}
case MotionEvent.ACTION_UP:
{
WindowManager.LayoutParams layoutParams = this.getWindow().getAttributes();
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
layoutParams.x = ((int) arg1.getRawX()-400);
layoutParams.y = ((int) arg1.getRawY()-200);
this.getWindow().setAttributes(layoutParams);
return true;
}
case MotionEvent.ACTION_DOWN:
{
WindowManager.LayoutParams layoutParams = this.getWindow().getAttributes();
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
layoutParams.x = ((int) arg1.getRawX()-400);
layoutParams.y = ((int) arg1.getRawY()-200);
this.getWindow().setAttributes(layoutParams);
return true;
}
}
}
return false;
}
}
and xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/myactivity"
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=".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"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView1"
android:text="End" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button1"
android:layout_alignBottom="#+id/button1"
android:layout_alignLeft="#+id/textView1"
android:ems="10" >
<requestFocus />
</EditText>
</RelativeLayout>
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.dialogtest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.dialogtest.MainActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme.Holo.Dialog">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
gamecih
http://i.stack.imgur.com/RgivT.jpg
my app
http://i.stack.imgur.com/VvPcP.jpg
my problem is:
1 i cant get activitiy on top
2 can touch outside but in some application whene i touch nothing will happen
3 i used startActivity(i); to get activity on forground but it will restart and same issue in 2
your help is highly appreciated

Categories

Resources