首页 > 编程技术 > android

android设置全屏与取消全屏方法

发布时间:2016-9-20 19:59

在android开发中设置全屏有常用的两种方法,一种是通过程序设置,另一种是在配置文件里修改(AndroidManifest.xml)下面我来介绍一下。

android提供了两种方式来实现无标题栏和全屏效果,即通过xml文件声明的方式或在程序中动态控制的方式。

android设置全屏方法

一、通过程序设置:

 代码如下 复制代码

    package com.hhh.changeimage;
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.Window;
    import android.view.WindowManager;
    public class ChangeImage extends Activity
    {
    public void onCreate(Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    //无title
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams. FLAG_FULLSCREEN);
    setContentView(R.layout.main);
    }
    }

注:无title和全屏段代码必须在setContentView(R.layout.main) 之前,不然会报错。

二、在配置文件里修改(AndroidManifest.xml)

 代码如下 复制代码

    <activity android:name=".ChangeImage"
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
    android:label="@string/app_name">
    <intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    </activity>

下面我们结合上面的实例作一个Android全屏设置及取消全屏设置


•1、//在onCreat方法中setContentView()之前插入

 代码如下 复制代码
•requestWindowFeature(Window.FEATURE_NO_TITLE);//取消标题栏
•getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,
•              WindowManager.LayoutParams. FLAG_FULLSCREEN);//全屏

•注:这种方法在启动activity时会闪现状态栏之后再全屏
•2、在manifest里面配置:<activity android:theme="@android:style/Theme.NoTitleBar.Fullscreen" />只在当前Activity内显示全屏
•<application  android:theme="@android:style/Theme.NoTitleBar.Fullscreen"  />为整个应用配置全屏显示
•3、/**
• * 全屏切换
• */

 代码如下 复制代码
•public void fullScreenChange() {
•SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
•boolean fullScreen = mPreferences.getBoolean("fullScreen", false);
•WindowManager.LayoutParams attrs = getWindow().getAttributes();
•System.out.println("fullScreen的值:" + fullScreen);
•if (fullScreen) {
•attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
•getWindow().setAttributes(attrs);
•//取消全屏设置
•getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
•mPreferences.edit().putBoolean("fullScreen", false).commit() ;
•} else {
•attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
•getWindow().setAttributes(attrs);
•getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
•mPreferences.edit().putBoolean("fullScreen", true).commit();
•}
•}
自己第一次接触android开发,于时先测试一个标题了与hello word了,结果不成呀,于是搜索了一个和我一样入门实例,下面和大家一起来看看。

第一步,向实现自定义标题栏,需要在onCreate方法里这样写

requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); 

setContentView(R.layout.main); 

getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar); 

注意:
requestWindowFeature要在setContentView之前
getWindow().setFeatureInit最好在setContentView之后

 


第二步,就是写好自己的布局文件,实现标题栏的自定义。

不过我们会遇到一些问题,就是标题栏的高度不能自定义~下面就是解决办法~

下面通过实例来看一下如何实现。

1、 在layout下创建一个titlebtn.xml文件,内容如下:

 代码如下 复制代码

xml version="1.0" encoding="utf-8"?>

<<>RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

   android:layout_width="fill_parent"

   android:layout_height="fill_parent"

   android:orientation="horizontal">

 


<<>ImageButton

       android:id="@+id/imageButton1"

       android:layout_width="wrap_content"

       android:layout_height="wrap_content"

       android:layout_alignParentLeft="true"

       android:layout_centerVertical="true"

       android:background="#00000000"

       android:src="@drawable/prv"/>

 


<<>TextView

       android:layout_width="wrap_content"

       android:layout_height="wrap_content"

       android:layout_centerInParent="true"

       android:text="标题栏"/>

 


<<>ImageButton

       android:id="@+id/imageButton1"

       android:layout_width="wrap_content"

       android:layout_height="wrap_content"

       android:layout_alignParentRight="true"

       android:layout_centerInParent="true"

       android:background="#00000000"

       android:src="@drawable/next"/>
<RelativeLayout>


修改style.xml文件

加入下面代码

 代码如下 复制代码

name="CustomWindowTitleBackground">

name="android:background">#00cc00

name="test"parent="android:Theme">

name="android:windowTitleSize">50dp

name="android:windowTitleBackgroundStyle">@style/CustomWindowTitleBackground

加入到AndroidManifest

 代码如下 复制代码


android:name=".CustomTitileBarActivity"
android:label="@string/app_name"android:theme="@style/test">
android:name="android.intent.action.MAIN"/>
 android:name="android.intent.category.LAUNCHER"/>

本文章来给各位同学介绍Android中TextView文字居中与垂直靠左居中设置方法,如果你还是入门级别的androider不防进入参考一下。

有2种方法可以设置TextView文字居中:

一:在xml文件设置:android:gravity="center"

二:在程序中设置:m_TxtTitle.setGravity(Gravity.CENTER);

 
备注:android:gravity和android:layout_gravity的区别在于前者对控件内部操作,后者是对整个控件操作。

例如:

 代码如下 复制代码

android:gravity="center"是对textView中文字居中

android:layout_gravity="center"是对textview控件在整个布局中居中

其实很容易理解,出现"layout"就是控件对整个布局的操作


TextView文字垂直靠左居中,


设置android:gravity="center_vertical|left"。


android:gravity="center", 垂直水平居中

LinearLayout有两个非常相似的属性:android:gravity与android:layout_gravity。他们的区别在于:android:gravity用于设置View组件的对齐方式,而android:layout_gravity用于设置Container组件的对齐方式。

举个例子,我们可以通过设置android:gravity="center"来让EditText中的文字在EditText组件中居中显示;同时我们设置EditText的android:layout_gravity="right"来让EditText组件在LinearLayout中居中显示。

 代码如下 复制代码

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="40sp"
    android:gravity="center_vertical|left"
    android:text="@string/hello_world" />

做一个输入框时发现android中ditView的默认焦点了,这种问题如果是在输入框还好,但在搜索页面或浏览页面这样就会影响用户体验了,那要如何取消EditView的默认焦点呢,下面我们来看看。

在网上找了好久,有点 监听软键盘事件,有点 调用 clearFouse()方法,但是测试了都没有! xml中也找不到相应的属性可以关闭这个默认行为

解决之道:在EditText的父级控件中找一个,设置成

 代码如下 复制代码

android:focusable="true"
android:focusableInTouchMode="true"

这样,就把EditText默认的行为截断了!

 代码如下 复制代码

<LinearLayout
style="@style/FillWrapWidgetStyle"
android:orientation="vertical"
android:background="@color/black"
android:gravity="center_horizontal"
android:focusable="true"
android:focusableInTouchMode="true"
>
<ImageView
android:id="@+id/logo"
style="@style/WrapContentWidgetStyle"
android:background="@drawable/dream_dictionary_logo"
/>
<RelativeLayout
style="@style/FillWrapWidgetStyle"
android:background="@drawable/searchbar_bg"
android:gravity="center_vertical"
>
<EditText
android:id="@+id/searchEditText"
style="@style/WrapContentWidgetStyle"
android:background="@null"
android:hint="Search"
android:layout_marginLeft="40dp"
android:singleLine="true"
/>
</RelativeLayout>
</LinearLayout>

查阅了很多资料后,发现以下方法最简单:

在xml中,在EditText控件之前
加入

 代码如下 复制代码

<LinearLayout
    android:id="@+id/linearLayout_focus"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:layout_width="0px"
    android:layout_height="0px"/>

这是一个虚假的LinearLayout,不会显示的,但是会抢走焦点

现在几乎所有app应用都可以调用手机的照相功能了,但我在开始时碰到一个问题就是拍照之后在系统相册中找不到我拍照的照片怎么办?下面我来给各位同学一并分享一下。

系统已经有的东西,如果我们没有新的需求的话,直接调用是最直接的。下面讲讲调用系统相机拍照并保存图片和如何调用系统相册的方法。

首先看看调用系统相机的核心方法:

 代码如下 复制代码
Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
 startActivityForResult(camera, CAMERA);

相机返回的数据通过下面的回调方法取得,并处理:

 代码如下 复制代码

@Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
 
  if(requestCode == CAMERA && resultCode == Activity.RESULT_OK && null != data){
   String sdState=Environment.getExternalStorageState();
   if(!sdState.equals(Environment.MEDIA_MOUNTED)){
    GameLog.log(Tag, "sd card unmount");
    return;
   }
   new DateFormat();
   String name= DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))+".jpg";
   Bundle bundle = data.getExtras();
   //获取相机返回的数据,并转换为图片格式
   Bitmap bitmap = (Bitmap)bundle.get("data");
   FileOutputStream fout = null;
   File file = new File("/sdcard/pintu/");
   file.mkdirs();
   String filename=file.getPath()+name;
   try {
    fout = new FileOutputStream(filename);
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
   } catch (FileNotFoundException e) {
    e.printStackTrace();
   }finally{
    try {
     fout.flush();
     fout.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
   //显示图片
  
  }

}

 

下面是调用系统相册并取得照片的方法:

 代码如下 复制代码
Intent picture = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(picture, PICTURE);

下面是相应的回调方法:

 

 代码如下 复制代码

@Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
 
  if(requestCode == CAMERA && resultCode == Activity.RESULT_OK && null != data){
 

   Uri selectedImage = data.getData();
   String[] filePathColumns={MediaStore.Images.Media.DATA};
   Cursor c = this.getContentResolver().query(selectedImage, filePathColumns, null,null, null);
   c.moveToFirst();
   int columnIndex = c.getColumnIndex(filePathColumns[0]);
   String picturePath= c.getString(columnIndex);
   c.close();
   //获取图片并显示

  
  }


 
这样就完成了系统调用,很简单,但是有些朋友会碰到照片拍好了,在手机相册中发现照片不显示呀。


解决Android拍照保存在系统相册不显示的问题

MediaStore.Images.Media.insertImage(getContentResolver(), mBitmap, "", "");通过上面的那句代码就能插入到系统图库,这时候有一个问题,就是我们不能指定插入照片的名字,而是系统给了我们一个当前时间的毫秒数为名字,有一个问题郁闷了很久,我还是先把insertImage的源码贴出来吧

 代码如下 复制代码

 

 /**
             * Insert an image and create a thumbnail for it.
             *
             * @param cr The content resolver to use
             * @param source The stream to use for the image
             * @param title The name of the image
             * @param description The description of the image
             * @return The URL to the newly created image, or <code>null</code> if the image failed to be stored
             *              for any reason.
             */
            public static final String insertImage(ContentResolver cr, Bitmap source,
                                                   String title, String description) {
                ContentValues values = new ContentValues();
                values.put(Images.Media.TITLE, title);
                values.put(Images.Media.DESCRIPTION, description);
                values.put(Images.Media.MIME_TYPE, "image/jpeg");

                Uri url = null;
                String stringUrl = null;    /* value to be returned */

                try {
                    url = cr.insert(EXTERNAL_CONTENT_URI, values);

                    if (source != null) {
                        OutputStream imageOut = cr.openOutputStream(url);
                        try {
                            source.compress(Bitmap.CompressFormat.JPEG, 50, imageOut);
                        } finally {
                            imageOut.close();
                        }

                        long id = ContentUris.parseId(url);
                        // Wait until MINI_KIND thumbnail is generated.
                        Bitmap miniThumb = Images.Thumbnails.getThumbnail(cr, id,
                                Images.Thumbnails.MINI_KIND, null);
                        // This is for backward compatibility.
                        Bitmap microThumb = StoreThumbnail(cr, miniThumb, id, 50F, 50F,
                                Images.Thumbnails.MICRO_KIND);
                    } else {
                        Log.e(TAG, "Failed to create thumbnail, removing original");
                        cr.delete(url, null, null);
                        url = null;
                    }
                } catch (Exception e) {
                    Log.e(TAG, "Failed to insert image", e);
                    if (url != null) {
                        cr.delete(url, null, null);
                        url = null;
                    }
                }

                if (url != null) {
                    stringUrl = url.toString();
                }

                return stringUrl;
            }


上面方法里面有一个title,我刚以为是可以设置图片的名字,设置一下,原来不是,郁闷,哪位高手知道title这个字段是干嘛的,告诉下小弟,不胜感激!

当然Android还提供了一个插入系统相册的方法,可以指定保存图片的名字,我把源码贴出来吧

 

 代码如下 复制代码

   /**
             * Insert an image and create a thumbnail for it.
             *
             * @param cr The content resolver to use
             * @param imagePath The path to the image to insert
             * @param name The name of the image
             * @param description The description of the image
             * @return The URL to the newly created image
             * @throws FileNotFoundException
             */
            public static final String insertImage(ContentResolver cr, String imagePath,
                    String name, String description) throws FileNotFoundException {
                // Check if file exists with a FileInputStream
                FileInputStream stream = new FileInputStream(imagePath);
                try {
                    Bitmap bm = BitmapFactory.decodeFile(imagePath);
                    String ret = insertImage(cr, bm, name, description);
                    bm.recycle();
                    return ret;
                } finally {
                    try {
                        stream.close();
                    } catch (IOException e) {
                    }
                }
            }


啊啊,贴完源码我才发现,这个方法调用了第一个方法,这个name就是上面方法的title,晕死,这下更加郁闷了,反正我设置title无效果,求高手为小弟解答,先不管了,我们继续往下说

上面那段代码插入到系统相册之后还需要发条广播

 代码如下 复制代码

 

sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory()))); 


上面那条广播是扫描整个sd卡的广播,如果你sd卡里面东西很多会扫描很久,在扫描当中我们是不能访问sd卡,所以这样子用户体现很不好,用过微信的朋友都知道,微信保存图片到系统相册并没有扫描整个SD卡,所以我们用到下面的方法

 

 代码如下 复制代码

Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);  
 Uri uri = Uri.fromFile(new File("/sdcard/image.jpg"));  
 intent.setData(uri);  
 mContext.sendBroadcast(intent); 


或者用MediaScannerConnection

 

 代码如下 复制代码

 

final MediaScannerConnection msc = new MediaScannerConnection(mContext, new MediaScannerConnectionClient() {  
  public void onMediaScannerConnected() {  
   msc.scanFile("/sdcard/image.jpg", "image/jpeg");  
  }  
  public void onScanCompleted(String path, Uri uri) {  
   Log.v(TAG, "scan completed");  
   msc.disconnect();  
  }  
 });  


也行你会问我,怎么获取到我们刚刚插入的图片的路径?呵呵,这个自有方法获取,insertImage(ContentResolver cr, Bitmap source,String title, String description),这个方法给我们返回的就是插入图片的Uri,我们根据这个Uri就能获取到图片的绝对路径

 

 代码如下 复制代码

private  String getFilePathByContentResolver(Context context, Uri uri) {
  if (null == uri) {
   return null;
  }
        Cursor c = context.getContentResolver().query(uri, null, null, null, null);
        String filePath  = null;
        if (null == c) {
            throw new IllegalArgumentException(
                    "Query on " + uri + " returns null result.");
        }
        try {
            if ((c.getCount() != 1) || !c.moveToFirst()) {
            } else {
             filePath = c.getString(
               c.getColumnIndexOrThrow(MediaColumns.DATA));
            }
        } finally {
            c.close();
        }
        return filePath;
    }

根据上面的那个方法获取到的就是图片的绝对路径

标签:[!--infotagslink--]

您可能感兴趣的文章: