栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Android自定义PreferenceScreen的Layout布局,并获取控件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android自定义PreferenceScreen的Layout布局,并获取控件

先说一下需求,要在里添加一个自定义的Layout,实现如下效果:

操作步骤:

1、在res/layout目录创建一个xml文件,名为my_preference_layout.xml,代码如下:



    
        
        
        

2、创建一个自定义控件myPreference.java,继承自android.preference.Preference,代码如下:

package net.zy13.skhelper.view;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import net.zy13.skhelper.MainApplication;
import net.zy13.skhelper.R;
import net.zy13.skhelper.utils.PreferenceUtil;

public class MyPreference extends Preference {

    private Context mContext;
    private TextView mTextViewMobileid;
    private Button mButtonCopyMobileid;

    public MyPreference(Context context) {
        this(context, null);
    }
    public MyPreference(Context context, AttributeSet attrs) {
        //这里构造方法也很重要,不加这个很多属性不能再XML里面定义
        this(context, attrs, android.R.attr.editTextStyle);
    }

    public MyPreference(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        //获取上下文
        mContext=context;
    }

    protected View onCreateView(ViewGroup parent) {
        // TODO Auto-generated method stub
        super.onCreateView(parent);
        LayoutInflater inflater=(LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.preference_mobileid_layout, null);
        //获取控件
        mButtonCopyMobileid=view.findViewById(R.id.btnCopyMobileid);
        mTextViewMobileid = (TextView)view.findViewById(R.id.mobileid);
        //监听点击事件(匿名类方式,或叫内部类方式)
        mButtonCopyMobileid.setonClickListener(new View.onClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

            }

        });
        return view;
    }
}
我们创建这个myPreference.java自定义控件的作用:
  • 用来读取我们添加layout布局文件my_preference_layout.xml,同时操作布局里的控件;
  • 这个myPreference.java类最重要的就是重写父类的onCreateView方法;

3、在PreferenceScreen的xml里使用我们自定义的控件,如下图:

 具体代码:



    
        
        
        
        
    

 这样就ok了,网上有很多类似的教程,但是都不详细,所以我写了一个完整的分享给大家。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/531449.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号