Android 开发常用控件使用方法

0.CheckBox_theme

/values/styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="MYTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorControlNormal">@color/colorAccent2</item>
        <item name="colorControlActivated">@color/colorAccent1</item>
<!--        <item name="colorAccent">@color/colorAccent</item>-->
    </style>


</resources>

1、Swith开关


//oncreate中初始化
mSwitch = (Switch) findViewById(R.id.switch_); 
//设置监听器
mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {  
        @Override  
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {  
            if (isChecked){  
                mText.setText("开启");  
            }else {  
                mText.setText("关闭");  
            }  
        }  
    });

常用的属性

  • 属性名 作用 textOn 控件打开时显示的文字 textOff 控件关闭时显示的文字 thumb 控件开关的图片 track 控件开关的轨迹图片 typeface 设置字体类型 switchMinWidth 开关最小宽度 switchPadding 设置开关与文字的空白距离 switchTextAppearance 设置文本的风格 checked 设置初始选中状态 splitTrack 是否设置一个间隙,让滑块与底部图片分隔(API 21及以上) showText 设置是否显示开关上的文字(API 21及以上)

2、Tabhost

//源码
TabHost tabHost;
//oncreate
        tabHost = (TabHost) findViewById(R.id.tabhost);
        tabHost.setup();//初始化TabHost
        LayoutInflater.from(this).inflate(R.layout.tab3, tabHost.getTabContentView());
        LayoutInflater.from(this).inflate(R.layout.tab5, tabHost.getTabContentView());
  
   tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator("MQTT").setContent(R.id.tab3));
   tabHost.addTab(tabHost.newTabSpec("tab5").setIndicator("显示").setContent(R.id.tab5));
        updateTab(tabHost);
        //标签切换事件处理,setOnTabChangedListener
   tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener(){
            @Override
            // tabId是newTabSpec第一个参数设置的tab页名,并不是layout里面的标识符id
            public void onTabChanged(String tabId) {
                if (tabId.equals("tab3")) {   //第三个标签
                    updateTab(tabHost);
                }
                if (tabId.equals("tab5")) {   //第4个标签
                    updateTab(tabHost);
                }
            }
        });      
        
//
 private void updateTab(final TabHost tabHost) {//tab点击效果控制代码 用于更新点击后的界面
        for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
            View view = tabHost.getTabWidget().getChildAt(i);
            TextView tv = (TextView) tabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title);
            tv.setTextSize(10);
            tv.setTypeface(Typeface.SERIF, 2); // 设置字体微风格
            if (tabHost.getCurrentTab() == i) {//选中
                view.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_grey));//选中后的背景
                tv.setTextColor(this.getResources().getColorStateList(
                        android.R.color.black));
            } else {//不选中
                view.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_white));//非选择的背景
                tv.setTextColor(this.getResources().getColorStateList(
                        android.R.color.darker_gray));
            }
        }
    }        
        

//布局文件
<?xml version="1.0" encoding="utf-8"?>
<TabHost
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tabhost"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1">
    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:weightSum="1">

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0.99"></FrameLayout>

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="42dp"
            android:layout_alignParentBottom="true" />
    </LinearLayout>
    </RelativeLayout>
</TabHost>

3、Spinner控件

//

Spinner spinner_of_light;

//
 spinner_of_light=(Spinner)findViewById(R.id.spinner_of_light);
 //
spinner_of_light.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int pos, long id) {
                ch_mode = pos;
                if (ch_mode == 1) {
                    Toast.makeText(MainActivity.this, "红", Toast.LENGTH_SHORT).show();

                }else if (ch_mode == 2){
                   Toast.makeText(MainActivity.this, "绿", Toast.LENGTH_SHORT).show();

                }else if (ch_mode == 3){
                   Toast.makeText(MainActivity.this, "蓝", Toast.LENGTH_SHORT).show();

                }else if (ch_mode == 4){
                    Toast.makeText(MainActivity.this, "黄", Toast.LENGTH_SHORT).show();

                }else if (ch_mode == 5){
                    //Toast.makeText(MainActivity.this, "客户端模式", Toast.LENGTH_SHORT).show();

                }else if (ch_mode == 6){
                   // Toast.makeText(MainActivity.this, "客户端模式", Toast.LENGTH_SHORT).show();

                }else if (ch_mode == 7){
                    //Toast.makeText(MainActivity.this, "客户端模式", Toast.LENGTH_SHORT).show();

                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });
//
//布局文件
<Spinner
            android:id="@+id/spinner_of_light"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/textView_of_color"
            android:layout_toStartOf="@+id/switch_of_beem"
            android:entries="@array/mode" />//重点
//array.xml
    -<string-array name="mode">

        <item>选择颜色设置</item>

        <item>红</item>
        <item>绿</item>
        <item>蓝</item>
        <item>黄</item>


    </string-array>

4、textView-滚动显示

//的滚动效果设置
textView8.setMovementMethod(ScrollingMovementMethod.getInstance());
//使用下面方法更新消息 可以进行定位到最新行
 public void refreshLogView(String msg) {
        textView8.append(msg);
        int offset = textView8.getLineCount() * textView8.getLineHeight();
        if (offset > textView8.getHeight()) {
            textView8.scrollTo(0, offset - textView8.getHeight());
        }
    }

//控件设置
 <ScrollView
                android:layout_width="match_parent"
                android:layout_height="100dp"
                android:layout_above="@+id/tv_bottom"
                android:layout_marginRight="3.5dp"
                android:layout_marginBottom="6dp"
                android:background="@drawable/s1_1">

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

                    <TextView
                        android:id="@+id/textView5"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:fadeScrollbars="false"
                        android:scrollbars="vertical"
                        android:textColor="@android:color/background_dark" />

                </LinearLayout>

</ScrollView>
//ScrollView的大小固定 ,其他子控件大小跟随父控件

//结合 新的代码
    public void refreshLogView(String msg) {
        mReceiveDataShow.append(msg+"\r");
        int offset = mReceiveDataShow.getLineCount() * mReceiveDataShow.getLineHeight();
        if (offset > scrollView1.getHeight()) {
            scrollView1.scrollTo(0, offset - scrollView1.getHeight());
        }
    }
//其中mReceiveDataShow为textView控件  scrollView1为scrollview控件可实现滑动以及自动到新行
//但是说在滑动到底层后,若想每次数据更新滑动到最低层,应当手动拉到最底层一次即可。

5、ListView

ListView listView;
MyAdapter adapter;
private int[] imageIds = new int[]{
        R.drawable.ic_x,
        R.drawable.ic_y,
        R.drawable.ic_v,
        R.drawable.ic_angle,
        R.drawable.ic_fxp,
        R.drawable.my_pc,
};
private String[] Name1 = new String[]{"连接服务","方向控制","轨迹导入","备用"};
public float[] gain = new float[]{0,0,0,0,0,0};
//oncreate
listView=(ListView)findViewById(R.id.listview) ;
adapter = new MyAdapter(MainActivity.this,getdata());
listView.setAdapter(adapter);//列表视图的适配器
//调用方法
   private List<Map<String,Object>> getdata(){
    //ArrayList<HashMap<String,Object>> listItem = new ArrayList<HashMap<String, Object>>();
    List<Map<String,Object>> listItem = new ArrayList<Map<String,Object>>();
    for(int i=0;i<6;i++){
        HashMap<String,Object> map = new HashMap<String,Object>();
        map.put("icon",imageIds[i]);
        map.put("name",Name[i]);
        map.put("data",gain[i]);
        listItem.add(map);
    }
    return listItem;
}
//监听器
 listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                String result = adapterView.getItemAtPosition(i).toString();
                fragmentManager = getFragmentManager();
                transaction = fragmentManager.beginTransaction();
                if(result.equals("0")){

                    flag++;
                    if(flag==1) {
                      
                    }else if(flag==2){
                      
                    }
                }else if(result.equals("1")){
                    flag1++;
                    if(flag1==1){
                      

                    }else if(flag1==2){
                        flag1=0;
                        
                    }
                }else if(result.equals("2")){
                    flag2++;
                    if(flag2==1){
                        //flag=0;
                       

                    }else if(flag2==2){
                        flag2=0;
                       
                    }
                }
            }

        });
  listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id) {
//                HashMap<String, Object> user = users.get(position);
                if(position>=0)
                    Toast.makeText(getApplicationContext(),"你点击的是:" +position+"",Toast.LENGTH_SHORT).show();
            }
        });

//MyAdapter 适配器
public  class MyAdapter extends BaseAdapter {
    private LayoutInflater inflater;
   private List<Map<String, Object>> data;
    private Context mContext;
    public MyAdapter( Context mContext,List<Map<String, Object>> Datas) {
        this.data = Datas;
        this.inflater = LayoutInflater.from(mContext);
        this.mContext = mContext;
    }
    /**
     * 返回item的个数
     * @return
     */
    @Override
    public int getCount() {
        return data.size();
    }
    /**
     * 返回每一个item对象
     * @param i
     * @return
     */
    @Override
    public Object getItem(int i) {
        return null;
    }
    /**
     * 返回每一个item的id
     * @param i
     * @return
     */
    @Override
    public long getItemId(int i) {
        return i;
    }
    /**
     * 暂时不做优化处理,后面会专门整理BaseAdapter的优化
     * @param i
     * @param view
     * @param viewGroup
     * @return
     */
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder holder;
        if(view==null){
            holder=new ViewHolder();
            view = LayoutInflater.from(mContext).inflate(R.layout.list_item,viewGroup,false);
            holder.imageView = (ImageView) view.findViewById(R.id.image1);
            holder.textView1 = (TextView) view.findViewById(R.id.text1);
            holder.textView2 = (TextView) view.findViewById(R.id.text2);
            //TextView textView2 = (TextView) view.findViewById(R.id.text2);
            view.setTag(holder);
        }else {
            holder=(ViewHolder)view.getTag();
        }
        holder.imageView.setImageResource((int)data.get(i).get("icon"));
        holder.textView1.setText(data.get(i).get("name").toString());
        holder.textView2.setText(data.get(i).get("data").toString());
//        holder.imageView.setImageResource(Datas.get(i).getImageId());
//        holder.textView1.setText(Datas.get(i).getTheme());
//        holder.textView2.setText(Datas.get(i).getContent());
//        此处需要返回view 不能是view中某一个
        return view;

    }
    class ViewHolder{

        private ImageView imageView;
        private TextView textView1;
        private TextView textView2;
    }
}

//LISTVIew.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="1">

    <ImageView
        android:id="@+id/image1"
        android:layout_width="46dp"
        android:layout_height="34dp"
        app:srcCompat="@drawable/ic_f" />

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="32dp"
        android:text="TextView"
        android:textColor="@android:color/background_dark"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/text2"
        android:layout_width="wrap_content"
        android:layout_height="29dp"
        android:text="TextView"
        android:textColor="@android:color/background_dark"
        android:textSize="16sp" />

</LinearLayout>

6、SerVice


7、AndroidManifest.xml-包含了常用的各种权限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.john.myapplication">

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    //获取写入内存卡的权限
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    //允许设备获取电源锁、即在锁屏状态下仍可运行
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.DEVICE_POWER" />

    <!-- 解锁屏幕需要的权限 -->
    <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
    <uses-permission android:name="android.permission.WRITE_CALENDAR" />
    <!-- 开启悬浮窗功能 -->
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.SYSTEM_OVERLAY_WINDOW" />
    <!-- 前台权限权限 -->
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_l"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/StartTheme">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTask"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Main0Activity_login"
            android:label="@string/title_activity_main0_login"
            android:launchMode="singleTask"
            android:theme="@style/AppTheme1" />
    </application>

</manifest>

8、build.gradle-常用于新版本sdk与旧APP文件不兼容时设置

//noinspection GradleCompatible

apply plugin: 'com.android.application'

android {

  compileSdkVersion 27

  buildToolsVersion "25.0.0"

  defaultConfig {

    applicationId "com.john.myapplication"

    minSdkVersion 26

    targetSdkVersion 27

    versionCode 1

    versionName "1.0"

  }

  //这里是配置JNI的引用地址,也就是引用.so文件

  sourceSets {

    main {

      jniLibs.srcDirs = ['libs']

      jni.srcDirs = []

    }

  }

  buildTypes {

    release {

      minifyEnabled false

      proguardFiles getDefaultProguardFile('proguard-android.txt'), '[proguard-rules.pro](http://proguard-rules.pro)'

    }

    debug {

      jniDebuggable true

    }

  }

}

dependencies {

  compile fileTree(include: ['*.jar'], dir: 'libs')

  //implementation 'ru.alexbykov:nopermission:1.1.2'

  //compile 'libs/eventbus-3.0.0.jar'

  //compile 'com.android.support.constraint:constraint-layout:1.0.2'

  compile files('libs/org.eclipse.paho.client.mqttv3-1.2.0.jar')

  compile 'com.android.support:appcompat-v7:23.4.0'

  compile 'com.jakewharton:butterknife:7.0.0'

  compile 'com.android.support.constraint:constraint-layout:1.0.2'

  compile 'com.android.support:design:23.4.0'

  testCompile 'junit:junit:4.12'

  compile files('libs/org.eclipse.paho.android.service-1.1.1.jar')

}


9.broadcast

///
//接收广播的代码  动态注册无需在 7中声明
        receiver_broadcast=new BReceiver();
        intentFilter = new IntentFilter();
        intentFilter.addAction("S.Receivemessage");
        registerReceiver(receiver_broadcast,intentFilter);
///发送广播
Intent intent = new Intent();
intent.setAction("S.Receivemessage");
sendBroadcast(intent); //发送广播
///收到广播的动作响应
public class BReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        //拿到传来过来数据
        String action = intent.getAction();
        String msg = intent.getStringExtra("msg");
        //拿到锁屏管理者
        if (action.equals("S.Receivemessage")) {
            if(!isFront) {
                notify_not();
            }
        }
    }
}

10、notify

//create
NotificationManager manager;
PendingIntent pendingIntent;
//init
String channelId="chat";//信道的id
        String channelName="聊天消息";//信道名字
        int importance=NotificationManager.IMPORTANCE_HIGH;//高级别
        createNotificationChannel(channelId,channelName,importance);
//条件
notify_API26();
//public
                 //定义创建信道的方法
private void createNotificationChannel(String channelId, String channelName, int importance){
        NotificationChannel channel=new NotificationChannel(channelId,channelName,importance);//信道的id、信道的名字、信道的级别
        channel.setShowBadge(true);//是否显示角标
        NotificationManager notificationManager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(channel);
   }
public void notify_API26(){
    NotificationManager manager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    NotificationChannel channel = manager.getNotificationChannel("chat");
        Intent intent1 = new Intent();//这个intent会传给目标,可以使用getIntent来获取
        intent1.setClass(getApplicationContext(),MainActivity.class);
        pendingIntent = PendingIntent.getActivity(this,0,intent1,0);
    //检测用户是否关闭了通知,否则弹出设置界面然用户手动开启
    if (channel.getImportance() == NotificationManager.IMPORTANCE_NONE) {
        Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
        intent.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
        intent.putExtra(Settings.EXTRA_CHANNEL_ID, channel.getId());
        startActivity(intent);
        Toast.makeText(this, "请手动将通知打开", Toast.LENGTH_SHORT).show();
    }
    Notification notification= new Notification.Builder(getApplicationContext(),"chat")
            .setVisibility(Notification.VISIBILITY_PUBLIC)
                .setSmallIcon(R.mipmap.ic_l)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_l))
            //.setFullScreenIntent(pendingIntent, false)
                .setContentTitle("提醒")
                .setContentText("收到新消息,请及时查看")
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .build();
    manager.notify(13,notification);


}

11、file_read_write


12、EditText

//EditText中添加图标的简单方法
<EditText
                android:drawableLeft="@drawable/beijing1"
                android:id="@+id/name_et"
                android:layout_width="match_parent"
                android:layout_height="60dp"
                android:background="@drawable/edittext"
                android:hint="@string/inout_name"
                android:maxLength="15" />
//android:drawableLeft="@drawable/beijing1"//重点句


13、获取控件ID

           if(view.getId()==R.id.button_con){
                str = "as1";//发送消息1
                textView_tips.setText("操作提示:"+"\r\n"+"暂停接收数据");

            }else if(view.getId()==R.id.button_con1){
                str = "as2";//发送消息2
                textView_tips.setText("操作提示:"+"\r\n"+"恢复接收数据");
            }else if(view.getId()==R.id.button_con2){
                str = "as3";//发送消息3
                textView_tips.setText("操作提示:"+"\r\n"+"发送频率为每秒1次");
            }else if(view.getId()==R.id.button_con3){
                str = "as4";//发送消息4
                textView_tips.setText("操作提示:"+"\r\n"+"发送频率为2秒1次");
            }else{
                str = "";
                textView_tips.setText("操作提示:"+"\r\n"+"操作失败");
            }
 class sendButton_Click implements View.OnClickListener{
        @Override
        public void onClick(View view) {

            handler.sendEmptyMessage(1);
            String str;
            if(view.getId()==R.id.button_con){
                str = "as1";//发送消息1
                textView_tips.setText("操作提示:"+"\r\n"+"暂停接收数据");

            }else if(view.getId()==R.id.button_con1){
                str = "as2";//发送消息2
                textView_tips.setText("操作提示:"+"\r\n"+"恢复接收数据");
            }else if(view.getId()==R.id.button_con2){
                str = "as3";//发送消息3
                textView_tips.setText("操作提示:"+"\r\n"+"发送频率为每秒1次");
            }else if(view.getId()==R.id.button_con3){
                str = "as4";//发送消息4
                textView_tips.setText("操作提示:"+"\r\n"+"发送频率为2秒1次");
            }else{
                str = "";
                textView_tips.setText("操作提示:"+"\r\n"+"操作失败");
            }
            //String str = "1";//发送消息1
            send_buff=str.getBytes();
            send_len=str.length();
            new Publish_send_Thread().start();
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

UH_SZJ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值