本文实例为大家分享了Android猜拳小游戏,供大家参考,具体内容如下简单的 页面跳转 和 点击事件 的实现... --> AndroidManifest.xml<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.dragon.android.fight" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="15" android:targetSdkVersion="19" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.dragon.android.fight.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> <activity android:name="com.dragon.android.fight.OtherActivity"> </activity> </application></manifest>AndroidManifest--> strings.xml<?xml version="1.0" encoding="utf-8"?><resources> <string name="app_name">fight</string> <string name="hello_world">Hello world!</string> <string name="action_settings">Settings</string> <string name="player1">甲方</string> <string name="player2">乙方</string> <string name="choose1">石头</string> <string name="choose2">剪刀</string> <string name="choose3">布</string> <string name="sure">出拳</string> <string name="again">再来一局</string></resources>--> fragment_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:background="#ffffff" tools:context="com.dragon.android.fight.MainActivity$PlaceholderFragment" > <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="36dp" android:text="@string/player1" android:textSize="30sp" /> <RadioGroup android:id="@+id/radioGroup1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" > <RadioButton android:id="@+id/radio0" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" android:text="@string/choose1" /> <RadioButton android:id="@+id/radio1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/choose2" /> <RadioButton android:id="@+id/radio2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/choose3" /> </RadioGroup> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/radioGroup1" android:layout_below="@+id/radioGroup1" android:layout_marginTop="14dp" android:text="@string/sure" /> <ImageView android:id="@+id/imageView1" android:layout_width="120dp" android:layout_height="120dp" android:layout_above="@+id/radioGroup1" android:layout_below="@+id/textView1" android:layout_centerHorizontal="true" android:src="@drawable/b" /></RelativeLayout>--> activity_other.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:orientation="vertical" android:background="#ffffff" > <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="36dp" android:text="@string/player2" android:textSize="30sp" /> <RadioGroup android:id="@+id/radioGroup1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" > <RadioButton android:id="@+id/radio0" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" android:text="@string/choose1" /> <RadioButton android:id="@+id/radio1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/choose2" /> <RadioButton android:id="@+id/radio2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/choose3" /> </RadioGroup> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/radioGroup1" android:layout_below="@+id/radioGroup1" android:layout_marginTop="14dp" android:text="@string/sure" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView1" android:layout_below="@+id/button1" android:visibility="invisible" android:layout_marginTop="14dp"/> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView2" android:layout_centerHorizontal="true" android:visibility="invisible" android:text="@string/again" /> <ImageView android:id="@+id/imageView1" android:layout_width="120dp" android:layout_height="120dp" android:layout_above="@+id/radioGroup1" android:layout_below="@+id/textView1" android:layout_centerHorizontal="true" android:src="@drawable/a" /> </RelativeLayout>--> MainActivitypackage com.dragon.android.fight;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ImageView;import android.widget.RadioButton;import android.widget.RadioGroup;public class MainActivity extends Activity { // 设置一个静态变量,用于关闭Activity public static MainActivity instance = null; private RadioGroup radioGroup1; private Button button1; private ImageView imageView1; @Override protected void onCreate(Bundle savedInstanceState) { // 代表当前的Activity instance = this; super.onCreate(savedInstanceState); setContentView(R.layout.fragment_main); radioGroup1 = (RadioGroup) findViewById(R.id.radioGroup1); // 设置图片透明 // imageView1 = (ImageView) findViewById(R.id.imageView1); // imageView1.getBackground().setAlpha(100); button1 = (Button) findViewById(R.id.button1); button1.setOnClickListener(new MyButtonListener()); } class MyButtonListener implements OnClickListener { @Override public void onClick(View v) { // 得到选中的RadioButton RadioButton radioButton = (RadioButton) findViewById(radioGroup1 .getCheckedRadioButtonId()); String radioText = radioButton.getText().toString(); Intent intent = new Intent(); intent.putExtra("checked", radioText); intent.setClass(MainActivity.this, OtherActivity.class); startActivity(intent); } }}--> OtherActivitypackage com.dragon.android.fight;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.RadioButton;import android.widget.RadioGroup;import android.widget.TextView;public class OtherActivity extends Activity { private RadioGroup radioGroup1; private Button button1; private TextView textView2; private RadioButton radioButton; private Button button2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_other); radioGroup1 = (RadioGroup) findViewById(R.id.radioGroup1); button1 = (Button) findViewById(R.id.button1); textView2 = (TextView) findViewById(R.id.textView2); button2 = (Button) findViewById(R.id.button2); button1.setOnClickListener(new MyButtonListener()); button2.setOnClickListener(new MyButtonListener1()); } class MyButtonListener implements OnClickListener { @Override public void onClick(View v) { radioButton = (RadioButton) findViewById(radioGroup1 .getCheckedRadioButtonId()); String buttonText = radioButton.getText().toString(); Intent intent = getIntent(); String checked = intent.getStringExtra("checked"); // 设置View为可见 textView2.setVisibility(View.VISIBLE); button2.setVisibility(View.VISIBLE); String msg = "甲出:" + checked + "\n" + "乙出:" + buttonText + "\n"; if (buttonText.equals(checked)) { textView2.setText(msg + "平局"); } if (buttonText.equals("石头")) { if (checked.equals("剪刀")) { textView2.setText(msg + "乙方赢"); } else if (checked.equals("布")) { textView2.setText(msg + "甲方赢"); } } if (buttonText.equals("剪刀")) { if (checked.equals("布")) { textView2.setText(msg + "乙方赢"); } else if (checked.equals("石头")) { textView2.setText(msg + "甲方赢"); } } if (buttonText.equals("布")) { if (checked.equals("石头")) { textView2.setText(msg + "乙方赢"); } else if (checked.equals("剪刀")) { textView2.setText(msg + "甲方赢"); } } } } class MyButtonListener1 implements OnClickListener { @Override public void onClick(View arg0) { Intent intent = new Intent(); intent.setClass(OtherActivity.this, MainActivity.class); finish(); // 关闭指定Activity MainActivity.instance.finish(); startActivity(intent); } }}以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

页面拖动到最后一页 再向下滑动回复到 第一页,第一页向前滑动回到 最后一页同时,底部红色小圆点随着页面的滑动距离比例随时改变位置布局:<?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: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.lian.viewpagertest.MainActivity"> <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="match_parent" > </android.support.v4.view.ViewPager> <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="内容" android:textSize="25sp" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" /> <RelativeLayout android:id="@+id/rl_bottom" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginBottom="45dip" > <LinearLayout android:id="@+id/ll_points" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" > </LinearLayout> <View android:id="@+id/v_redpoint" android:layout_width="10dip" android:layout_height="10dip" android:background="@drawable/red_circle" /> </RelativeLayout> </RelativeLayout> 其中red_circle是用shape绘制的红色小圆点最后的LinearLayout实际上是灰色小圆点的容器,在代码中根据数据的长度动态确定数目代码:package com.lian.viewpagertest; import android.os.Bundle; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private ViewPager mViewPager; private TextView mTextView; private LinearLayout mLinearLayout; private View mView; private List<ImageView> mDataList; private int diatance; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initView(); initData(); initEvent(); } /** * 初始化数据 */ private void initData() { int[] sorce = new int[]{R.drawable.a,R.drawable.b,R.drawable.c,R.drawable.d,R.drawable.e}; mDataList = new ArrayList<ImageView>(); for (int i = 0;i < sorce.length;i ++){ ImageView img = new ImageView(getApplicationContext()); img.setImageResource(sorce[i]); mDataList.add(img); //添加底部灰点 View v = new View(getApplicationContext()); v.setBackgroundResource(R.drawable.gray_circle); //指定其大小 LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(20,20); if (i != 0) params.leftMargin = 20; v.setLayoutParams(params); mLinearLayout.addView(v); } mViewPager.setAdapter(new MyAdapter()); //设置每次加载时第一页在MAX_VALUE / 2 - Extra 页,造成用户无限轮播的错觉 int startPage = Integer.MAX_VALUE / 2; int extra = startPage % mDataList.size(); startPage = startPage - extra; mViewPager.setCurrentItem(startPage); } /** * ViewPager的容器 */ public class MyAdapter extends PagerAdapter{ @Override public int getCount() { //告诉容器我们的数据长度为Integer.MAX_VALUE,这样就可以一直滚动 return Integer.MAX_VALUE; } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Object instantiateItem(ViewGroup container, int position) { //若position超过mDataList.size(),会发生越界异常,所以这里每次超过size又从0开始计算位置 position = position % mDataList.size(); ImageView img = mDataList.get(position); container.addView(img); return img; } @Override public void destroyItem(ViewGroup container, int position, Object object) { position = position % mDataList.size(); container.removeView((View)object); // super.destroyItem(container, position, object); } } private void initEvent() { /** * 当底部红色小圆点加载完成时测出两个小灰点的距离,便于计算后面小红点动态移动的距离 */ mView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { diatance = mLinearLayout.getChildAt(1).getLeft() - mLinearLayout.getChildAt(0).getLeft(); Log.d("两点间距",diatance + "测出来了"); } }); mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { //测出页面滚动时小红点移动的距离,并通过setLayoutParams(params)不断更新其位置 position = position % mDataList.size(); float leftMargin = diatance * (position + positionOffset); RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mView.getLayoutParams(); params.leftMargin = Math.round(leftMargin); mView.setLayoutParams(params); Log.d("红点在这",leftMargin + ""); } @Override public void onPageSelected(int position) { } @Override public void onPageScrollStateChanged(int state) { } }); } private void initView() { setContentView(R.layout.activity_main); mViewPager = (ViewPager) findViewById(R.id.viewpager); mTextView = (TextView) findViewById(R.id.tv); mLinearLayout = (LinearLayout) findViewById(R.id.ll_points); mView = findViewById(R.id.v_redpoint); } } 以上就是本文的全部内容,希望对大家的学习有所帮助。

在项目开发中,层级列表经常遇到,简单点的二级列表利用UITableView的Header就可以实现,再简单点的三级列表通过对Cell高度进行调整也可以实现三级列表的效果。但遇到多级列表,尤其是层次不明的动态列表就比较麻烦了。原理层级列表和树形结构比较类似,不过不是二叉树,而是多叉树。每个节点只需要拥有指向父节点和子节点的两个指针,就能形成一颗树。我们将多级列表中每一级对象看作一个node,node拥有两个属性,分别为父节点和子节点的ID。每棵树有个一个虚拟的root节点,它的ID为rootID,所有节点中凡是父节点ID为rootID的便是第一级,对应树结构中的depth(深度)。这样每一个node对象就都拥有了parentID和childrenID, childrenID为node对象的ID。我们可以通过rootID查出第一级node,再根据第一级node的childrenID查出下一级,依次类推,确定所有节点的父子关系。同时也可以确定叶子节点和第一级节点,也可称为根节点。效果图1.一般多级列表2.记录节点历史状态的列表思路1.首先根据 rootID 获取所有第一级节点,并放入UITableView的数据源 dataSourceArr 中,展示初始化列表2. 展开: 点击节点cell,根据 childrenID 查找下一级nodes,并插入到 dataSourceArr 中currentNode的后面,刷新展示3. 收拢: 点击以打开节点cell,从 dataSourceArr 的CurrentIndex+1开始,如果该节点的level小于currentNode的level,则移除node,否则停止刷新列表。4.点击cell为叶子节点则不响应展开或收拢操作,并把节点信息通过返回。dataSourceArr中是这样的一种符合树层级结构的顺序:定义节点对象遇到问题1.局部刷新的问题每次展开或收拢以后刷新列表,一开始采用复制代码 代码如下:- (void)reloadSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation但会导致节目有整体闪烁的效果,体验不好。最后考虑采用局部刷新 insertRowsAtIndexPaths 和 deleteRowsAtIndexPaths 。但在刷新中会报错* Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to delete row 2 from section 0 which only contains 2 rows before the update'推测原因是 current Cell在刷新时的numberOfRowsInSection和刷新insert or del的cell时numberOfRowsInSection不一致导致 。然后尝试current cell和其他cell分别刷新,完美刷新。[_reloadArray removeAllObjects]; [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone]; if (currentNode.isExpand) { //expand [self expandNodesForParentID:currentNode.childrenID insertIndex:indexPath.row]; [tableView insertRowsAtIndexPaths:_reloadArray withRowAnimation:UITableViewRowAnimationNone]; }else{ //fold [self foldNodesForLevel:currentNode.level currentIndex:indexPath.row]; [tableView deleteRowsAtIndexPaths:_reloadArray withRowAnimation:UITableViewRowAnimationNone]; }2.怎么保存节点历史状态当文件级层比较多时,有时希望能关掉层级后再打开时还能保留子层级的打开状态。我们可以会给每一个node一个是否展开的属性,当fold时只修改currentNode的expand属性,expand时对子节点序isexpand=YES的进行遍历插入。//expand- (NSUInteger)expandNodesForParentID:(NSString*)parentID insertIndex:(NSUInteger)insertIndex{ for (int i = 0 ; i<_nodes.count;i++) { YKNodeModel *node = _nodes[i]; if ([node.parentID isEqualToString:parentID]) { if (!self.isPreservation) { node.expand = NO; } insertIndex++; [_tempNodes insertObject:node atIndex:insertIndex]; [_reloadArray addObject:[NSIndexPath indexPathForRow:insertIndex inSection:0]];//need reload nodes if (node.isExpand) { insertIndex = [self expandNodesForParentID:node.childrenID insertIndex:insertIndex]; } } } return insertIndex;}demo地址:https://github.com/YangKa/YKMutableLevelTableView.git以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

OkHttp是比较火的网络框架,它支持同步与异步请求,支持缓存,可以拦截,更方便下载大文件与上传文件的操作。下面我们用OkHttp来下载文件并带进度条!相关资料: 官网地址:http://square.github.io/okhttp/github源码地址:https://github.com/square/okhttp一、服务器端简单搭建可以参考搭建本地Tomcat服务器及相关配置 这篇文章。新建项目OkHttpServer,在WebContent目录下新建downloadfile目录,将要下载的jpg文件放在项目下。如下图: 启动服务器,文件下载地址为http://localhost:8080/OkHttpServer/download/2.jpg 。这样我们服务器就搭好了。二、Android端下面我们进入正题。1.build.gradle的dependencies配置如下compile 'com.android.support:appcompat-v7:24.1.1'compile 'com.squareup.okhttp3:okhttp:3.2.0'compile 'com.squareup.okio:okio:1.7.0'2.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: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.huang.myokhttp.MainActivity"> <Button android:id="@+id/ok_download" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="下载文件" /> <TextView android:id="@+id/download_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="0" /> <ProgressBar android:id="@+id/download_progress" style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:max="100" /></RelativeLayout>3.编写OkHttpUtil如下: private static OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(10000, TimeUnit.MILLISECONDS) .readTimeout(10000,TimeUnit.MILLISECONDS) .writeTimeout(10000,TimeUnit.MILLISECONDS).build(); //下载文件方法 public static void downloadFile(String url, final ProgressListener listener, Callback callback){ //增加拦截器 OkHttpClient client = okHttpClient.newBuilder().addNetworkInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Response response = chain.proceed(chain.request()); return response.newBuilder().body(new ProgressResponseBody(response.body(),listener)).build(); } }).build(); Request request = new Request.Builder().url(url).build(); client.newCall(request).enqueue(callback); }4.上面代码中的ProgressResponseBody是自己编写的类,ProgressListener 是监听的接口: ProgressListener 接口public interface ProgressListener {//已完成的 总的文件长度 是否完成 void onProgress(long currentBytes, long contentLength, boolean done);}ProgressResponseBody继承ResponseBody ,返回监听进度public class ProgressResponseBody extends ResponseBody { public static final int UPDATE = 0x01; public static final String TAG = ProgressResponseBody.class.getName(); private ResponseBody responseBody; private ProgressListener mListener; private BufferedSource bufferedSource; private Handler myHandler; public ProgressResponseBody(ResponseBody body, ProgressListener listener) { responseBody = body; mListener = listener; if (myHandler==null){ myHandler = new MyHandler(); } } /** * 将进度放到主线程中显示 */ class MyHandler extends Handler { public MyHandler() { super(Looper.getMainLooper()); } @Override public void handleMessage(Message msg) { switch (msg.what){ case UPDATE: ProgressModel progressModel = (ProgressModel) msg.obj; //接口返回 if (mListener!=null)mListener.onProgress(progressModel.getCurrentBytes(),progressModel.getContentLength(),progressModel.isDone()); break; } } } @Override public MediaType contentType() { return responseBody.contentType(); } @Override public long contentLength() { return responseBody.contentLength(); } @Override public BufferedSource source() { if (bufferedSource==null){ bufferedSource = Okio.buffer(mySource(responseBody.source())); } return bufferedSource; } private Source mySource(Source source) { return new ForwardingSource(source) { long totalBytesRead = 0L; @Override public long read(Buffer sink, long byteCount) throws IOException { long bytesRead = super.read(sink, byteCount); totalBytesRead +=bytesRead!=-1?bytesRead:0; //发送消息到主线程,ProgressModel为自定义实体类 Message msg = Message.obtain(); msg.what = UPDATE; msg.obj = new ProgressModel(totalBytesRead,contentLength(),totalBytesRead==contentLength()); myHandler.sendMessage(msg); return bytesRead; } }; }}5.MainActivity的代码:public class MainActivity extends AppCompatActivity implements View.OnClickListener{ public static final String TAG = MainActivity.class.getName(); private ProgressBar download_progress; private TextView download_text; public static String basePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/okhttp"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); download_progress = (ProgressBar) findViewById(R.id.download_progress); download_text = (TextView) findViewById(R.id.download_text); findViewById(R.id.ok_download).setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.ok_download: String url = "http://192.168.0.104:8080/OkHttpServer/download/2.jpg"; final String fileName = url.split("/")[url.split("/").length - 1]; Log.i(TAG, "fileName==" + fileName); OkHttpUtil.downloadFile(url, new ProgressListener() { @Override public void onProgress(long currentBytes, long contentLength, boolean done) { Log.i(TAG, "currentBytes==" + currentBytes + "==contentLength==" + contentLength + "==done==" + done); int progress = (int) (currentBytes * 100 / contentLength); download_progress.setProgress(progress); download_text.setText(progress + "%"); } }, new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { if (response != null) { InputStream is = response.body().byteStream(); FileOutputStream fos = new FileOutputStream(new File(basePath + "/" + fileName)); int len = 0; byte[] buffer = new byte[2048]; while (-1 != (len = is.read(buffer))) { fos.write(buffer, 0, len); } fos.flush(); fos.close(); is.close(); } } }); break; } }}6.最后不要忘了添加权限: <uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> 源码下载以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

这个方法是通用的,不仅仅适用于EditText,也适用于TextView、AutoCompleteTextView等控件。 Google官方API并没有给出一个直接的方法用来设置右边图片的点击事件,所以这里我们需要通过点击位置来判断点击事件,效果如图: 布局文件:<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.drablerighttest.MainActivity" > <EditText android:id="@+id/et" android:layout_width="350dp" android:layout_height="wrap_content" android:drawableRight="@drawable/search_clear_pressed" android:text="@string/hello_world" /></RelativeLayout>MainActivity.javapublic class MainActivity extends Activity { private EditText et; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et = (EditText) this.findViewById(R.id.et); et.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // et.getCompoundDrawables()得到一个长度为4的数组,分别表示左右上下四张图片 Drawable drawable = et.getCompoundDrawables()[2]; //如果右边没有图片,不再处理 if (drawable == null) return false; //如果不是按下事件,不再处理 if (event.getAction() != MotionEvent.ACTION_UP) return false; if (event.getX() > et.getWidth() - et.getPaddingRight() - drawable.getIntrinsicWidth()){ et.setText(""); } return false; } }); }}以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

分类:其它

时间:2016-06-08 07:11:54