您的位置:首页 > 移动开发 > Android开发

实现在ScrollView中拖动控件与按图片比例动态控制布局大小

2014-08-01 11:55 316 查看
以下贴出源代码

主文件:

package com.example.test3;

import java.io.IOException;
import java.io.InputStream;

import com.example.test3.MainActivity;
import com.example.test3.R;

import android.support.v7.app.ActionBarActivity;
import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
double HW;
double screenHeight;
double screenWidth;
TextView tv1;
SharedPreferences sp;

final String IMAGE_TYPE = "image/*";

final int IMAGE_CODE = 0; //这里的IMAGE_CODE是自己任意定义的

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button addPic=(Button) findViewById(R.id.button1);
addPic.setOnClickListener(listener);

screenHeight = this.getWindowManager().getDefaultDisplay()
.getHeight();
screenWidth = this.getWindowManager().getDefaultDisplay()
.getWidth();

//增加可拖动控件
tv1 = ( TextView ) findViewById(R.id.textView11);
MoveWidget(tv1);
}

private OnClickListener listener=new OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

Button btn=(Button) v;

switch(btn.getId()){

case R.id.button1:
setImage();
break;

}

}

private void setImage() {
// TODO Auto-generated method stub
//使用intent调用系统提供的相册功能,使用startActivityForResult是为了获取用户选择的图片

Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);

getAlbum.setType(IMAGE_TYPE);

startActivityForResult(getAlbum, IMAGE_CODE);

}};

@SuppressLint("NewApi") protected void onActivityResult(int requestCode, int resultCode, Intent data){

if (resultCode != RESULT_OK) { //此处的 RESULT_OK 是系统自定义得一个常量

Log.e("TAG->onresult","ActivityResult resultCode error");

return;

}

Bitmap bm = null;

//外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口

ContentResolver resolver = getContentResolver();

//此处的用于判断接收的Activity是不是你想要的那个

if (requestCode == IMAGE_CODE) {

try {

Uri originalUri = data.getData(); //获得图片的uri

bm = MediaStore.Images.Media.getBitmap(resolver, originalUri);
// 这里开始的第二部分,获取图片的路径:

String[] proj = {MediaStore.Images.Media.DATA};

//好像是android多媒体数据库的封装接口,具体的看Android文档

Cursor cursor = managedQuery(originalUri, proj, null, null, null);

//按我个人理解 这个是获得用户选择的图片的索引值

int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

//将光标移至开头 ,这个很重要,不小心很容易引起越界

cursor.moveToFirst();

//最后根据索引值获取图片路径

String path = cursor.getString(column_index);
//设置各个布局大小适应手机屏幕

HW=(1f*bm.getHeight())/(1f*bm.getWidth());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
(int) (this.screenWidth* 1f + 0.5f),
//这里用宽去乘HW得到的不知道为什么是错误数值,对JAVA浮点运算不了解
(int) (this.screenWidth*HW * 1f + 0.5f));
LinearLayout ll=(LinearLayout)findViewById(R.id.LinearLayout1);
ll.setLayoutParams(params);
//这里有BUG,华为机子用setBackground代替setBackgroundDrawable直接掉线
ll.setBackgroundDrawable(Drawable.createFromPath(path));//
Toast.makeText(this, ""+bm.getWidth()+bm.getHeight()+HW, Toast.LENGTH_LONG).show();

}catch (IOException e) {

Log.e("TAG-->Error",e.toString());

}
}

}

//移动控件函数
void MoveWidget(final TextView tv){
sp = getSharedPreferences( "config" , Context.MODE_PRIVATE );

int lastx = sp.getInt( "lastx" , 0 );
int lasty = sp.getInt( "lasty" , 0 );

tv.setOnTouchListener( new View.OnTouchListener(){
int startX;
int startY;

@Override
public boolean onTouch( View v, MotionEvent event ) {
MyScrollView sv=(MyScrollView) findViewById(R.id.scrollView1);
switch ( event.getAction() ) {
case MotionEvent.ACTION_DOWN:
sv.requestDisallowInterceptTouchEvent(true);
this.startX = ( int ) event.getRawX();
this.startY = ( int ) event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
sv.requestDisallowInterceptTouchEvent(true);
int newX = ( int ) event.getRawX();
int newY = ( int ) event.getRawY();

int dx = newX - this.startX;
int dy = newY - this.startY;

int l = tv.getLeft();
int r = tv.getRight();
int t = tv.getTop();
int b = tv.getBottom();

int newt = t + dy;
int newb = b + dy;
int newl = l + dx;
int newr = r + dx;

if ( ( newl < 0 ) || ( newt < 0 )
|| ( newr > screenWidth )
|| ( newb > screenHeight ) ) {
break;
}

tv.layout( newl , newt , newr , newb );
this.startX = ( int ) event.getRawX();
this.startY = ( int ) event.getRawY();

break;
case MotionEvent.ACTION_UP:
int lastx = tv.getLeft();
int lasty = tv.getTop();
Editor editor = sp.edit();
editor.putInt( "lastx" , lastx );
editor.putInt( "lasty" , lasty );
editor.commit();
break;
case MotionEvent.ACTION_CANCEL:
sv.requestDisallowInterceptTouchEvent(true);
}
return true;
}
} );
}

@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);
}
}
4000


自己重写的ScrollView(便于之后扩展功能):
package com.example.test3;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ScrollView;
//重写ScrollView方法
public class MyScrollView extends ScrollView{

public MyScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}

public MyScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}

public MyScrollView(Context context) {
super(context);
}
}

最后是XML布局文件:
<com.example.test3.MyScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.test3.MainActivity" >

<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="vertical" >

<LinearLayout
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/personphoto"
android:orientation="vertical" >

<TextView
android:id="@+id/textView11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="25dp" />
</LinearLayout>

<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />

<TextView
android:id="@+id/TextView01"
android:layout_width="fill_parent"
android:layout_height="50px"
android:gravity="center"
android:text="This is textView." >
</TextView>
</LinearLayout>
</com.example.test3.MyScrollView>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  JAVA android