android控件---自定义带文本的ImageButton
生活随笔
收集整理的這篇文章主要介紹了
android控件---自定义带文本的ImageButton
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
由于SDK提供的ImageButton只能添加圖片,不能添加文字;而Button控件添加的文字只能顯示在圖片內部;當我們需要添加文字在圖片外部時就不能滿足我們的需求了,顧只能自己寫個自定義ImageButton。說是ImageButton,其實并不是繼承于ImageButton,而是從LinearLayout繼承,由于LinearLayout是線性排列,通過setOrientation(LinearLayout.VERTICAL)的方式達到View垂直排列的目的,所以很簡單,只需要添加兩個View:一個ImageView和一個TextView即可。代碼如下:
package com.example.adtest;import android.content.Context; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView;public class ImageButtonEx extends LinearLayout {private ImageView _imageView = null;private TextView _textView = null;public ImageButtonEx(Context context){super(context);}public ImageButtonEx(Context context, int imageResId, int textResId) {super(context);// TODO Auto-generated constructor stub _imageView = new ImageView(context);_textView = new TextView(context);_imageView.setImageResource(imageResId);_textView.setText(textResId);_imageView.setPadding(0, 0, 0, 0);_textView.setPadding(0, 0, 0, 0);setClickable(true);setFocusable(true);setBackgroundResource(android.R.drawable.btn_default);setOrientation(LinearLayout.VERTICAL);addView(_imageView);addView(_textView);}public void setBtnText(CharSequence text){_textView.setText(text);}}添加一個LinearLayout作為ImageButtonEx的容器。
<LinearLayoutandroid:id="@+id/llImageBtnEx"android:layout_width="wrap_content"android:layout_height="wrap_content"android:orientation="vertical"/>然后再Activity中添加調用代碼:
package com.example.adtest;import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.LinearLayout;public class MainActivity extends ActionBarActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);final ImageButtonEx imageBtnEx = new ImageButtonEx(this, R.drawable.icon, R.string.hello_world);imageBtnEx.setOnClickListener(new Button.OnClickListener(){@Overridepublic void onClick(View v) {// TODO Auto-generated method stubimageBtnEx.setBtnText("已經點擊過了");}});LinearLayout llimageBtnEx = (LinearLayout)findViewById(R.id.llImageBtnEx);llimageBtnEx.addView(imageBtnEx);} }?
轉載于:https://www.cnblogs.com/atomgame/p/3910031.html
總結
以上是生活随笔為你收集整理的android控件---自定义带文本的ImageButton的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LUA学习之路--初识LUA
- 下一篇: How your face shapes