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

自定义控件

2016-01-20 14:26 344 查看
自定义控件布局:一个textview跟一个ImageView组成。

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

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

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical" >

    <TextView

        android:id="@+id/text"

        android:text="ningshengcai"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"/>

    <ImageView

        android:id="@+id/imageview"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"/>

</LinearLayout>

自定义控件代码文件:

public class ImageBtnWithText extends LinearLayout {   
private TextView textone;
private ImageView imageview;
public ImageBtnWithText(Context context) {    
this(context, null);    
}    
   
public ImageBtnWithText(Context context, AttributeSet attrs) {    
super(context, attrs);    
//在构造函数中将Xml中定义的布局解析出来。   
LayoutInflater.from(context).inflate(R.layout.zidingyi, this, true); 
textone = (TextView)findViewById(R.id.text);
imageview = (ImageView)findViewById(R.id.imageview);
//imageview.setBackgroundResource(R.drawable.ic_launcher);
}    
 
public void setImageResource(int resId){
imageview.setBackgroundResource(resId);
}
 
public void setTextViewText(String text) { 
textone.setText(text);
}

 } 

获取自定义控件:包名+加载自定义控件的代码文件名称

 <com.example.music.ImageBtnWithText

        android:id="@+id/widgt"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        />

    

    <com.example.music.ImageBtnWithText

        android:id="@+id/aa"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        />

使用自定义控件:

public class MainActivity extends Activity {
private ImageBtnWithText widgt,aa; 
@Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        initUI();            
}
private void initUI() {
// TODO Auto-generated method stub
widgt = (ImageBtnWithText)findViewById(R.id.widgt);
widgt.setBackgroundResource(R.drawable.ic_launcher);

        widgt.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
widgt.setBackgroundResource(R.drawable.ds);
Toast.makeText(getBaseContext(), "dfasf", Toast.LENGTH_SHORT).show();
}
});

        aa = (ImageBtnWithText)findViewById(R.id.aa);

        aa.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
aa.setTextViewText("222");
Toast.makeText(getBaseContext(), "SDS", Toast.LENGTH_SHORT).show();
}
});
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息