How do I render single view Instance in XML with different Images - android

My XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="1" >
<LinearLayout
android:id="#+id/leftLayout"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".5"
android:orientation="vertical"
android:weightSum="1" >
<LinearLayout
android:id="#+id/firstProblem"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".5"
android:weightSum="1" >
<com.student.spelling.SpellViewFirst
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="3dp"
android:background="#android:color/black" />
<LinearLayout
android:id="#+id/secondProblem"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".5"
android:weightSum="1" >
<com.student.spelling.SpellViewFirst
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</LinearLayout>
<View
android:layout_width="3dp"
android:layout_height="fill_parent"
android:background="#android:color/black" />
<LinearLayout
android:id="#+id/rightLayout"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".5"
android:orientation="vertical"
android:weightSum="1" >
<LinearLayout
android:id="#+id/thirdProblem"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".5"
android:weightSum="1" >
<com.student.spelling.SpellViewFirst
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="3dp"
android:background="#android:color/black" />
<LinearLayout
android:id="#+id/fourthProblem"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".5"
android:weightSum="1" >
<com.student.spelling.SpellViewFirst
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
My View Class :
public class SpellViewFirst extends View {
private StartActivity studentActivity;
private int screenWidth;
private int screenHeight;
private Bitmap imageBitmap;
private ArrayList<Character> charList;
List<SpellObjects> spellObjectsList;
private String word;
int placeHolderHeight;
private ArrayList<Integer> dragable_id_object_list;
private Bitmap placeHolderBitmap;
Point placeHolderPoints;
Point alphabetPoints;
private int indexOfCurrentObject;
private int offsetX;
private int offsetY;
public SpellViewFirst(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
studentActivity = (StartActivity)context;
}
#Override
protected void onSizeChanged(int width, int height, int oldwidth, int oldheight) {
// TODO Auto-generated method stub
super.onSizeChanged(width, height, oldwidth, oldheight);
screenWidth = width;
screenHeight = height;
assignCoordinatesToImages();
}
private void assignCoordinatesToImages() {
// TODO Auto-generated method stub
Bitmap bm=BitmapFactory.decodeFile("/mnt/sdcard/resources/images/spelling/ques.png");
dragable_id_object_list=new ArrayList<Integer>() ;
spellObjectsList=new ArrayList<SpellObjects>();
SpellObjects curentObjects;
placeHolderHeight=bm.getHeight();
word=studentActivity.correctWordsArray[0];
imageBitmap=BitmapFactory.decodeFile("/mnt/sdcard/resources/images/spelling/"+word+".png");
placeHolderBitmap=Bitmap.createScaledBitmap(bm, screenWidth/word.length(), screenWidth/word.length(),true);
charList=new ArrayList<Character>();
placeHolderPoints=new Point();
for (int i = 0; i < word.length(); i++) {
charList.add(word.charAt(i));
}
for (int i = 0; i < charList.size(); i++) {
placeHolderPoints.y=screenHeight/2;
curentObjects=new SpellObjects(placeHolderPoints, placeHolderBitmap, -1,charList.get(i), null, placeHolderBitmap.getHeight(), screenWidth/word.length(), true);
placeHolderPoints.x=placeHolderPoints.x+screenWidth/word.length();
spellObjectsList.add(curentObjects);
}
Collections.shuffle(charList);
alphabetPoints=new Point();
alphabetPoints.x=imageBitmap.getWidth();
for (int i = 0; i < charList.size(); i++) {
Bitmap bitmap= BitmapFactory.decodeFile("/mnt/sdcard/resources/images/spelling/"+charList.get(i)+".png");
curentObjects=new SpellObjects(alphabetPoints,bitmap, i,charList.get(i), null, placeHolderBitmap.getHeight(), screenWidth/word.length(), true);
alphabetPoints.x=alphabetPoints.x+bitmap.getWidth();
spellObjectsList.add(curentObjects);
dragable_id_object_list.add(i, i);
}
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
canvas.drawBitmap(imageBitmap, 0, 0, null);
for(SpellObjects currentObjects :spellObjectsList ){
if(currentObjects.getIsCorrectlyPlaced())
canvas.drawBitmap(currentObjects.getobjectBitmap(), currentObjects.getCurrentPoint().x,currentObjects.getCurrentPoint().y, null);
}
}
}
I want to render like cake,duck and good in other three quadrants.Actually this is spelling app for kids where they can drag and drop alphabets to respective positions.Please help me out I am stuck.

I want to render like cake,duck and good in other three quadrants.
To set different images for your custom View you'll need to add a custom attribute for your custom layout to signal the desired image(or an id, or something to uniquely identify the view). Something like this(in attr.xml):
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomAttr">
<attr name="pictureName" format="string" />
</declare-styleable>
</resources>
This attribute will be used in the layout like this:
<com.student.spelling.SpellViewFirst
android:layout_width="match_parent"
android:layout_height="match_parent"
newtag:pictureName="one_of_your_picture_names_here"/>
Don't forget to set the newtag namespace in the root of your xml layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:newtag="http://schemas.android.com/apk/res/your.package.here"
// ...
Then you'll use that attribute to make the SpellViewFirst use the targeted image:
public SpellViewFirst(Context context, AttributeSet attrs) {
super(context, attrs);
studentActivity = (StartActivity)context;
if (attrs != null) {
TypedArray ta = context.obtainStyledAttributes(attrs,
R.styleable.CustomAttr, 0, 0);
word = ta.getString();// this is what you use to get the picture name, right?
ta.recycle();
}
}
Then you could use the word variable to get the desired Bitmap in assignCoordinatesToImages(). Don't forget to test word for null(meaning a picture name wasn't set in the layout) and show a default image instead.

Related

error after add relativelayout inside linearlayout?

I want to display the video thumbnails in listview, I use images instead of thumbnails and add ImageView (image play button) on the front but failed my xml code like this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/txttgl"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:paddingLeft="10dip"
android:gravity="center_horizontal"/>
<TextView
android:id="#+id/tv_batas_unread"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:paddingLeft="12dip"
android:background="#drawable/counter_shape_birudonker"
android:visibility="gone"
android:gravity="center_horizontal"/>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/ll_chat_item"
android:orientation="horizontal" >
<com.ltvie.chatkrawala.ImageViewRounded
android:id="#+id/img_photo_pp_chatbox"
android:layout_width="50dp"
android:layout_height="50dp"
android:paddingBottom="0dp"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:adjustViewBounds="true"
android:paddingTop="0dp"
android:layout_marginTop="5dp"
android:layout_marginLeft="3dp"
android:src="#drawable/gada_photo"
android:scaleType="fitXY" />
<LinearLayout
android:id="#+id/wrapper"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="left"
android:orientation="vertical"
android:layout_marginBottom="12dp"
android:layout_weight="1"
android:cacheColorHint="#android:color/transparent"
>
<TextView
android:id="#+id/txtKodeGbr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"/>
<TextView
android:id="#+id/txtPesan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"/>
<TextView
android:id="#+id/comment"
android:layout_marginTop="9dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/buble_kiri"
android:text="Bismillahirohmanirrohim"
android:textColor="#000"
android:textSize="15sp" />
<LinearLayout
android:id="#+id/rowFile"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RelativeLayout
android:layout_height="match_parent"
android:layout_width="wrap_content"
>
<ImageView
android:id="#+id/img_dilvChat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="3dp"
android:contentDescription="#string/descGambar"
android:background="#drawable/buble_kanan"
android:src="#drawable/gada_photo"
/>
<ImageView
android:id="#+id/img_btn_play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/descGambar"
android:layout_centerInParent="true"
android:src="#drawable/play_icon"
/>
<ProgressBar
android:id="#+id/chatBox_progress_img"
style="?android:attr/progressBarStyleSmallInverse"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
<LinearLayout
android:id="#+id/rowFileDesc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_gravity="bottom"
android:orientation="vertical">
<TextView
android:id="#+id/txtFileName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dip"
android:gravity="left"
android:text="Nama File : test.zip"
android:textSize="12sp" />
<TextView
android:id="#+id/txtFileSize"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dip"
android:gravity="left"
android:text="Ukuran : 2324342 bytes"
android:textSize="12sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/img_statusBaca"
android:layout_marginTop="2dip"
android:layout_width="15dip"
android:layout_height="15dip"
android:layout_marginRight="1dip"
android:background="#drawable/indicator_sending"
android:contentDescription="#string/descGambar"
/>
<TextView
android:id="#+id/txtjamchatMasuk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dip"
android:gravity="left"
android:text="setatus baca"
android:textSize="12sp" />
<TextView
android:id="#+id/txtKiriKanan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="5dip"
android:paddingRight="5dip"
android:text="right"
android:visibility="gone"
/>
</LinearLayout>
</LinearLayout>
<ImageView
android:id="#+id/imgselected"
android:layout_width="20dp"
android:layout_height="20dp"
android:contentDescription="#string/kosongan"
android:src="#drawable/ico_member" />
</LinearLayout>
</LinearLayout>
my java code
public class ChatboxArrayAdapter extends ArrayAdapter<OneComment> implements SectionIndexer{
private TextView countryName;
private LinearLayout wrapper,rowFileDesc,ll_chat_item;
private TextView TanggalMasuk,txtKodeGbr,txtPesan,txtJam,txtKiriKanan,txtUkuranFile;
private ImageView img_upload,img_statusbaca,imgPp_round;
ImageView imgPhoto,imgCheck,imgBtnPlay;
String namafileGambar,strPath,varStsBaca,tampilTgl;
public CacheImageLoader imageLoader;
Context ctx;
Options opts = new BitmapFactory.Options();
String TAG="chatboxArrayAdapter";
File dir = new File(Environment.getExternalStorageDirectory()+"");
File dirImage=new File(dir+"/a");
File dirVideo=new File(dir+"/a");
List<OneComment> countries;
#Override
public void add(OneComment object) {
countries.add(object);
super.add(object);
}
public void hapus_semua(){
countries.clear();
}
public void hapus_item(int nomerx){
countries.remove(nomerx);
notifyDataSetChanged();
}
public void refresh_lv(){
notifyDataSetChanged();
Log.d("notify", "datachange");
}
public ChatboxArrayAdapter(Context context, int textViewResourceId, List<OneComment> datanya) {
super(context, textViewResourceId);
this.countries=datanya;
this.ctx=context;
imageLoader=new CacheImageLoader(context.getApplicationContext());
}
public int getCount() {
return this.countries.size();
}
#Override
public OneComment getItem(int index) {
return this.countries.get(index);
}
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
try{
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.chatbox_detail, parent, false);
}
OneComment isiOneComen = getItem(position);
wrapper = (LinearLayout) row.findViewById(R.id.wrapper);
rowFileDesc=(LinearLayout) row.findViewById(R.id.rowFileDesc);
ll_chat_item=(LinearLayout) row.findViewById(R.id.ll_chat_item);
imgPhoto = (ImageView) row.findViewById(R.id.img_dilvChat);
countryName = (TextView) row.findViewById(R.id.comment);
txtKiriKanan = (TextView) row.findViewById(R.id.txtKiriKanan); //isi dari coment untuk menentukan letak buble di kiri ato dikanan,hanya untuk buble file untuk menentukan filenya masih di server apa sudah di downloa
TanggalMasuk= (TextView) row.findViewById(R.id.txttgl);
img_upload=(ImageView) row.findViewById(R.id.img_dilvChat);
txtKodeGbr = (TextView) row.findViewById(R.id.txtKodeGbr);
txtPesan=(TextView) row.findViewById(R.id.txtPesan);
txtJam=(TextView) row.findViewById(R.id.txtjamchatMasuk);
txtUkuranFile=(TextView) row.findViewById(R.id.txtFileSize);
imgCheck=(ImageView) row.findViewById(R.id.imgselected);
img_statusbaca=(ImageView) row.findViewById(R.id.img_statusBaca);
imgPp_round=(ImageView) row.findViewById(R.id.img_photo_pp_chatbox);
imgBtnPlay=(ImageView) row.findViewById(R.id.img_btn_play);
txtPesan.setVisibility(View.GONE);
txtKodeGbr.setVisibility(View.GONE);
img_upload.setVisibility(View.GONE);
rowFileDesc.setVisibility(View.GONE);
if(isiOneComen.comment.trim().equalsIgnoreCase("video")){
//error goes here
countryName.setVisibility(View.GONE);
Log.d("fileDesc", isiOneComen.Filedesc);
//strPath = namafileGambar;
strPath = moduleGlobal.dirImageSent+"/"+isiOneComen.Filedesc;
imgPhoto.setImageBitmap(changeSize(strPath));
scaleImage(imgPhoto, ((int) isiOneComen.lebarScreen)-((int) isiOneComen.lebarScreen/4));
imgBtnPlay.setVisibility(View.VISIBLE);
}else{ //run work well
countryName.setVisibility(View.VISIBLE);
try{
countryName.setText(getSmiledText(getContext(),isiOneComen.comment.toString()));
}catch (Exception e) {
// TODO: handle exception
Log.e("addsmiley", e.toString());
}
countryName.setBackgroundResource(isiOneComen.left ? R.drawable.buble_kiri : R.drawable.buble_kanan);
}
}catch (Exception ez) {
ll_chat_item.setVisibility(View.GONE);
Log.e(TAG, ez.toString());
}
return row;
}
private Bitmap changeSize(String path){
opts.inSampleSize = 1;
Bitmap bm = BitmapFactory.decodeFile(path);
if (bm.getHeight() > 150 || bm.getWidth() > 150) {
final int halfHeight = bm.getHeight() / 2;
final int halfWidth = bm.getWidth() / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / opts.inSampleSize) > 150
&& (halfWidth / opts.inSampleSize) > 150) {
opts.inSampleSize *= 2;
}
}
bm = BitmapFactory.decodeFile(path,opts); // this bitmap will be 1/8 the size of the original
return bm;
}
private void scaleImage(ImageView view, int boundBoxInDp)
{
// Get the ImageView and its bitmap
Drawable drawing = view.getDrawable();
Bitmap bitmap = ((BitmapDrawable)drawing).getBitmap();
// Get current dimensions
int width = bitmap.getWidth();
int height = bitmap.getHeight();
// Determine how much to scale: the dimension requiring less scaling is
// closer to the its side. This way the image always stays inside your
// bounding box AND either x/y axis touches it.
float xScale = ((float) boundBoxInDp) / width;
float yScale = ((float) boundBoxInDp) / height;
float scale = (xScale <= yScale) ? xScale : yScale;
// Create a matrix for the scaling and add the scaling data
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
// Create a new bitmap and convert it to a format understood by the ImageView
Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
#SuppressWarnings("deprecation")
BitmapDrawable result = new BitmapDrawable(scaledBitmap);
width = scaledBitmap.getWidth();
height = scaledBitmap.getHeight();
// Apply the scaled bitmap
view.setImageDrawable(result);
// Now change ImageView's dimensions to match the scaled image
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
params.width = width;
params.height = height;
view.setLayoutParams(params);
}
public Bitmap decodeToBitmap(byte[] decodedByte) {
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}
/**tambah smiley
*
*/
private static final HashMap<String, Integer> emoticons = new HashMap<String, Integer>();
static {
emoticons.put(":)", R.drawable.s1);
emoticons.put(":D", R.drawable.s2);
emoticons.put(":(", R.drawable.s3);
emoticons.put("8o|", R.drawable.s16);
emoticons.put(":/", R.drawable.s17);
}
// Get image for each text smiles
public static Spannable getSmiledText(Context context, String text) {
SpannableStringBuilder builder = new SpannableStringBuilder(text);
int index;
for (index = 0; index < builder.length(); index++) {
for (Entry<String, Integer> entry : emoticons.entrySet()) {
int length = entry.getKey().length();
if (index + length > builder.length())
continue;
if (builder.subSequence(index, index + length).toString().equals(entry.getKey())) {
builder.setSpan(new ImageSpan(context, entry.getValue()), index, index + length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
index += length - 1;
break;
}
}
}
return builder;
}
#Override
public int getPositionForSection(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getSectionForPosition(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object[] getSections() {
// TODO Auto-generated method stub
return null;
}
}
everything work well before i add relative layout,I want to add image view center with other imageview but I get error log
java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams
Problem with
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
This line Change this line to
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view.getLayoutParams();
Because you forgot to Add
</LinearLayout>
</LinearLayout>
at the end of your xml.
Use this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/tv1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:gravity="center_horizontal"
android:paddingLeft="10dip" />
<LinearLayout
android:id="#+id/ll_chat_item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
<LinearLayout
android:id="#+id/wrapper"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:layout_weight="1"
android:cacheColorHint="#android:color/transparent"
android:gravity="left"
android:orientation="vertical" >
<TextView
android:id="#+id/tv3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
<LinearLayout
android:id="#+id/rowFile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/img_dilvChat"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_margin="3dp"
android:background="#drawable/buble_kanan"
android:contentDescription="#string/descGambar" />
<ImageView
android:id="#+id/img_btn_play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:contentDescription="#string/descGambar"
android:src="#drawable/play_icon" />
</RelativeLayout>
<TextView
android:id="#+id/tv4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:gravity="center_horizontal"
android:paddingLeft="10dip" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>

How to draw a circle in center in android

I want the circular image to be in the centre.
How to have it in the centre of the device?
I don't want to use a relative layout. I have all ready tried that, but it needs a hard coded value for the circle; hence. it won't work on all the devices.
I am trying to achieve it by LinearLayout (using android:layout_weight property)
I have tried android:layout_gravity="center",android:gravity="center"
but the circle still won't make it to the centre.
I have attached the screen for reference
I want the circle to be in parent center
My xml is:
<?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/com.example.dd"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/LinearLayout02"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal" >
<Button
android:id="#+id/Button04"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="left1" >
</Button>
<com.example.dd.CircularImageView
android:id="#+id/round"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/buttonarea"
app:border="true"
app:border_color="#323232"
app:border_width="55dp"
app:shadow="true" />
<Button
android:id="#+id/Button08"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="right" >
</Button>
</LinearLayout>
</LinearLayout>
My circular class is:
public class CircularImageView extends ImageView {
private int borderWidth;
private int canvasSize;
private Bitmap image;
private Paint paint;
private Paint paintBorder;
public CircularImageView(final Context context) {
this(context, null);
}
public CircularImageView(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.circularImageViewStyle);
}
public CircularImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// init paint
paint = new Paint();
paint.setAntiAlias(true);
paintBorder = new Paint();
paintBorder.setAntiAlias(true);
// load the styled attributes and set their properties
TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.CircularImageView, defStyle, 0);
if(attributes.getBoolean(R.styleable.CircularImageView_border, true)) {
int defaultBorderSize = (int) (4 * getContext().getResources().getDisplayMetrics().density + 0.5f);
setBorderWidth(attributes.getDimensionPixelOffset(R.styleable.CircularImageView_border_width, defaultBorderSize));
setBorderColor(attributes.getColor(R.styleable.CircularImageView_border_color, Color.WHITE));
}
if(attributes.getBoolean(R.styleable.CircularImageView_shadow, false))
addShadow();
}
public void setBorderWidth(int borderWidth) {
Log.d("TAG","::::::::::::borderWidth"+borderWidth);
this.borderWidth = borderWidth;
this.requestLayout();
this.invalidate();
}
public void setBorderColor(int borderColor) {
if (paintBorder != null)
paintBorder.setColor(borderColor);
this.invalidate();
}
public void addShadow() {
setLayerType(LAYER_TYPE_SOFTWARE, paintBorder);
paintBorder.setShadowLayer(4.0f, 0.0f, 2.0f, Color.BLACK);
}
#Override
public void onDraw(Canvas canvas) {
// load the bitmap
image = drawableToBitmap(getDrawable());
// init shader
if (image != null) {
canvasSize = canvas.getWidth();
Log.d("TAG","::::::::::::canvasSize"+canvasSize);
if(canvas.getHeight()<canvasSize)
canvasSize = canvas.getHeight();
BitmapShader shader = new BitmapShader(Bitmap.createScaledBitmap(image, canvasSize, canvasSize, false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
paint.setShader(shader);
// circleCenter is the x or y of the view's center
// radius is the radius in pixels of the cirle to be drawn
// paint contains the shader that will texture the shape
int circleCenter = (canvasSize - (borderWidth * 2)) / 2;
canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, ((canvasSize - (borderWidth * 2)) / 2) + borderWidth - 4.0f, paintBorder);
canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, ((canvasSize - (borderWidth * 2)) / 2) - 4.0f, paint);
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = measureWidth(widthMeasureSpec);
int height = measureHeight(heightMeasureSpec);
setMeasuredDimension(width, height);
}
private int measureWidth(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
// The parent has determined an exact size for the child.
result = specSize;
} else if (specMode == MeasureSpec.AT_MOST) {
// The child can be as large as it wants up to the specified size.
result = specSize;
} else {
// The parent has not imposed any constraint on the child.
result = canvasSize;
}
return result;
}
private int measureHeight(int measureSpecHeight) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpecHeight);
int specSize = MeasureSpec.getSize(measureSpecHeight);
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else if (specMode == MeasureSpec.AT_MOST) {
// The child can be as large as it wants up to the specified size.
result = specSize;
} else {
// Measure the text (beware: ascent is a negative number)
result = canvasSize;
}
return (result + 2);
}
public Bitmap drawableToBitmap(Drawable drawable) {
if (drawable == null) {
return null;
} else if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
my attrs.xml goes in values:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CircularImageView">
<attr name="border" format="boolean"></attr>
<attr name="border_width" format="dimension"></attr>
<attr name="border_color" format="color"></attr>
<attr name="shadow" format="boolean"></attr>
</declare-styleable>
<declare-styleable name="Theme">
<attr name="circularImageViewStyle" format="reference"></attr>
</declare-styleable>
</resources>
Use some fake layouts and set the visibility to invisible. This should do the trick.
<?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/com.example.dd"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/LinearLayout02"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="horizontal" >
<Button
android:id="#+id/Button04"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="left1" >
</Button>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical" >
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical"
android:text="dummy"
android:visibility="invisible" >
</Button>
<Button
android:id="#+id/round"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#android:drawable/star_on"
app:shadow="true" />
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical"
android:text="dummy"
android:visibility="invisible" >
</Button>
</LinearLayout>
<Button
android:id="#+id/Button08"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="right" >
</Button>
</LinearLayout>
</LinearLayout>
try this
<?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/com.example.dd"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/LinearLayout02"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:orientation="horizontal" >
<Button
android:id="#+id/Button04"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="left1" >
</Button>
<com.example.dd.CircularImageView
android:id="#+id/round"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/buttonarea"
android:layout_gravity="center"
app:border="true"
app:border_color="#323232"
app:border_width="55dp"
app:shadow="true" />
<Button
android:id="#+id/Button08"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="right" >
</Button>
</LinearLayout>
Try this:
<com.example.dd.CircularImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/myCircularImageView"
android:src="#drawable/buttonarea"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
One way to do it would be to set your LinearLayout height to match_parent, then set the layout_gravity on the circle to center_vertical.
EDIT: Just tested, this works for me:
<?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:layout_gravity="center"
android:orientation="vertical">
<LinearLayout
android:id="#+id/LinearLayout02"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="horizontal">
<Button
android:id="#+id/Button04"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="left1">
</Button>
<com.example.dd.CircularImageView
android:id="#+id/round"
android:layout_width="fill_parent"
android:layout_gravity="center_vertical"
android:layout_height="wrap_content"
android:background="#android:color/black"
android:layout_weight="1"/>
<Button
android:id="#+id/Button08"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="right">
</Button>
</LinearLayout>
</LinearLayout>
Ignore the background color and missing app: attributes, the general idea stays the same.

EditText get hide when keyboard open

/*This is my mainActivity.class*/
public class MainActivity extends ActionBarActivity{
attachFragments();
}
private void attachFragments() {
CustomFragment chatFragment=new CustomFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.first, chatFragment);
transaction.commit();
}
}
/*mainActivity.xml*/
<?xml version="1.0" encoding="utf-8"?>
< com.prospus.poms.layout.CustomSlidingLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mainLayout"
android:layout_height="match_parent"
android:layout_width="match_parent">
<RelativeLayout
android:id="#+id/first"
android:layout_width="wrap_content"
android:layout_height="match_parent" >
</RelativeLayout>
<RelativeLayout
android:id="#+id/second"
android:layout_width="wrap_content"
android:layout_height="match_parent" >
</RelativeLayout>
<RelativeLayout
android:id="#+id/third"
android:layout_width="wrap_content"
android:layout_height="match_parent" >
</RelativeLayout>
</com.prospus.poms.layout.CustomSlidingLayout>
CustomSlidingLayout.java
public class CustomSlidingLayout extends LinearLayout {
private static final int SLIDING_DURATION = 500;
private static final int QUERY_INTERVAL = 16;
int mainLayoutWidth;
private View menuRight;
private View content;
private enum MenuState {
HIDING, HIDDEN, SHOWING, SHOWN,
};
private int contentXOffset;
private int menuWidth;
private int rightMenuOffset;
private MenuState currentMenuState = MenuState.HIDDEN;
private Scroller menuScroller = new Scroller(this.getContext(),
new EaseInInterpolator());
private Runnable rightMenuRunnable = new MenuRightRunnable();
private Handler menuHandler = new Handler();
public CustomSlidingLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomSlidingLayout(Context context) {
super(context);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mainLayoutWidth = MeasureSpec.getSize(widthMeasureSpec);
menuWidth=mainLayoutWidth;
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
content = this.getChildAt(0);
menuRight = getChildAt(1);
menuRight.setVisibility(View.GONE);
}
#Override
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
if (changed) {
LayoutParams contentLayoutParams = (LayoutParams) content
.getLayoutParams();
contentLayoutParams.height = this.getHeight();
contentLayoutParams.width = this.getWidth();
LayoutParams menuLayoutParams = (LayoutParams) menuRight.getLayoutParams();
menuLayoutParams.height = this.getHeight();
menuLayoutParams.width = this.getWidth();
}
menuRight.layout(right - rightMenuOffset, top, right - rightMenuOffset
+ menuWidth, bottom);
content.layout(left, top, right, bottom);
}
#SuppressLint("NewApi")
public void toggleRightMenu() {
if (currentMenuState == MenuState.HIDING
|| currentMenuState == MenuState.SHOWING)
return;
switch (currentMenuState) {
case HIDDEN:
currentMenuState = MenuState.SHOWING;
menuRight.setVisibility(View.VISIBLE);
menuScroller.startScroll(0, 0,
-menuRight.getLayoutParams().width, 0, SLIDING_DURATION);
contentXOffset = 0;
rightMenuOffset = 0;
invalidate();
break;
case SHOWN:
currentMenuState = MenuState.HIDING;
menuScroller.startScroll(contentXOffset, 0, -contentXOffset, 0,
SLIDING_DURATION);
break;
default:
break;
}
menuHandler.postDelayed(rightMenuRunnable, QUERY_INTERVAL);
this.invalidate();
}
protected class MenuRightRunnable implements Runnable {
#Override
public void run() {
boolean isScrolling = menuScroller.computeScrollOffset();
adjustRightContentPosition(isScrolling);
}
}
#SuppressLint("NewApi")
private void adjustRightContentPosition(boolean isScrolling) {
int scrollerXOffset = menuScroller.getCurrX();
menuRight.offsetLeftAndRight(scrollerXOffset - contentXOffset);
rightMenuOffset += (contentXOffset-scrollerXOffset );
contentXOffset = scrollerXOffset;
this.invalidate();
if (isScrolling)
menuHandler.postDelayed(rightMenuRunnable, QUERY_INTERVAL);
else
this.onMenuSlidingComplete();
}
private void onMenuSlidingComplete() {
switch (currentMenuState) {
case SHOWING:
currentMenuState = MenuState.SHOWN;
break;
case HIDING:
currentMenuState = MenuState.HIDDEN;
break;
default:
return;
}
}
protected class EaseInInterpolator implements Interpolator {
#Override
public float getInterpolation(float t) {
return (float) Math.pow(t - 1, 5) + 1;
}
}
public boolean isMenuShown() {
return currentMenuState == MenuState.SHOWN;
}
}
/*I am using this customlayout in main activity and in each sub layout attching a fragment. */
/* Layout file of fragment: */
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:fillViewport="true" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="#+id/title_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<include layout="#layout/header_layout" />
</LinearLayout>
<LinearLayout
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/bottomLayout"
android:layout_below="#id/title_layout"
android:orientation="horizontal" >
<ListView
android:id="#+id/chatList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:cacheColorHint="#android:color/transparent"
android:divider="#android:color/black"
android:fadeScrollbars="false"
android:fadingEdge="none"
android:isScrollContainer="false"
android:listSelector="#android:color/transparent"
android:overScrollMode="never"
android:scrollbarStyle="insideInset"
android:scrollbars="vertical"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll" >
</ListView>
</LinearLayout>
<LinearLayout
android:id="#id/bottomLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#color/title_background"
android:orientation="horizontal" >
<RelativeLayout
android:id="#+id/upload"
android:layout_width="#dimen/BASE_50_DP"
android:layout_height="match_parent"
android:layout_gravity="bottom" >
<ImageView
android:id="#+id/upload_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#drawable/ic_launcher" />
</RelativeLayout>
<EditText
android:id="#+id/chattext"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginBottom="#dimen/BASE_5_DP"
android:layout_marginTop="#dimen/BASE_5_DP"
android:layout_weight="1"
android:background="#android:color/white"
android:maxHeight="#dimen/EditTextHeight"
android:minHeight="#dimen/BASE_45_DP"
android:padding="#dimen/BASE_5_DP"
android:selectAllOnFocus="true"
android:singleLine="false" />
<RelativeLayout
android:layout_width="#dimen/BASE_50_DP"
android:layout_height="match_parent"
android:layout_gravity="bottom" >
<ImageView
android:id="#+id/done"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#drawable/ic_launcher" />
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
</ScrollView>
kayboard hide the editText but when keyboard hides, editText comes in middle of screen. Exactly opposite the requirement. I know main problem is my custom layout. Please tell me what is wrong in this customlayout. Everything works fine if i replace the customLayout with relativeLayoot. but i have to use this layout. Please help me.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/title_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<include layout="#layout/header_layout" />
</LinearLayout>
<LinearLayout
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/bottomLayout"
android:layout_below="#id/title_layout"
android:orientation="horizontal" >
<ListView
android:id="#+id/chatList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:cacheColorHint="#android:color/transparent"
android:divider="#android:color/black"
android:fadeScrollbars="false"
android:fadingEdge="none"
android:listSelector="#android:color/transparent"
android:overScrollMode="never"
android:scrollbarStyle="insideInset"
android:scrollbarThumbVertical="#drawable/scrollbar_thumb"
android:scrollbarTrackVertical="#drawable/scrollbar_vertical_track"
android:scrollbars="vertical"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll" >
</ListView>
</LinearLayout>
<LinearLayout
android:id="#id/bottomLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#color/title_background"
android:orientation="horizontal" >
<RelativeLayout
android:id="#+id/upload"
android:layout_width="#dimen/BASE_50_DP"
android:layout_height="match_parent"
android:layout_gravity="bottom" >
<ImageView
android:id="#+id/upload_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#drawable/upload_icon" />
</RelativeLayout>
<EditText
android:id="#+id/chattext"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginBottom="#dimen/BASE_5_DP"
android:layout_marginTop="#dimen/BASE_5_DP"
android:layout_weight="1"
android:background="#android:color/white"
android:maxHeight="#dimen/EditTextHeight"
android:minHeight="#dimen/BASE_45_DP"
android:padding="#dimen/BASE_5_DP"
android:selectAllOnFocus="true"
android:singleLine="false" />
<RelativeLayout
android:layout_width="#dimen/BASE_50_DP"
android:layout_height="match_parent"
android:layout_gravity="bottom" >
<ImageView
android:id="#+id/done"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#drawable/input_done_icon" />
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
</ScrollView>
put all view is scrollview
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/title_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<include layout="#layout/header_layout" />
</LinearLayout>
.....
</RelativeLayout>
</ScrollView>
Just wrap the whole Relative layout inside a ScrollView.
also
NOTE that scrollview can only have 1 child view
and that will be your outermost reletive layout.
ans the above link to documentation for scrollview methods that can be used to set different properties in java file.

Custom view made not visible the elements above in xml

i have a custom view to show a gif animated image. The problem born when i put in my linearlayout the custom view, the other elements under my custom view aren't displayed. this is my view:
public class GIFView extends View{
private Movie movie;
private InputStream is;
private long moviestart;
private long duration;
public GIFView(Context context) {
super(context);
is=getResources().openRawResource(R.drawable.anim_cerca);
movie=Movie.decodeStream(is);
duration = movie.duration();
}
public GIFView(Context context,AttributeSet set){
super(context,set);
is=getResources().openRawResource(R.drawable.anim_cerca);
movie=Movie.decodeStream(is);
duration = movie.duration();
}
public GIFView(Context context,AttributeSet set,int def){
super(context,set,def);
is=getResources().openRawResource(R.drawable.anim_cerca);
movie=Movie.decodeStream(is);
duration = movie.duration();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
long now=android.os.SystemClock.uptimeMillis();
Paint p = new Paint();
p.setAntiAlias(true);
if (moviestart == 0)
moviestart = now;
int relTime = (int)((now - moviestart) % duration);
movie.setTime(relTime);
movie.draw(canvas,0,0);
this.invalidate();
}
}
and this is my layout xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent" android:background="#drawable/sfondo">
<LinearLayout android:id="#+id/linearLayout2"
android:layout_height="wrap_content" android:layout_width="match_parent"
android:orientation="vertical">
<LinearLayout android:id="#+id/linearLayout1"
android:layout_height="fill_parent" android:weightSum="1"
android:layout_width="fill_parent" android:orientation="horizontal">
<ImageView android:layout_height="73dp" android:id="#+id/imageView1"
android:layout_weight="0.25" android:src="#drawable/trovachiavi"
android:layout_width="256dip"></ImageView>
<ImageButton android:id="#+id/infoButton"
android:background="#null" android:layout_height="47dp"
android:layout_marginLeft="10dip" android:layout_weight="0.25"
android:layout_marginTop="15dip" android:src="#drawable/info_mini"
android:layout_width="47dp"></ImageButton>
</LinearLayout>
</LinearLayout>
<LinearLayout android:id="#+id/layoutGIF"
android:layout_height="wrap_content" android:layout_width="wrap_content"
android:orientation="vertical"
android:layout_gravity="center">
</LinearLayout>
<ImageButton android:id="#+id/avvia_cerca"
android:layout_height="wrap_content" android:layout_width="wrap_content"
android:layout_marginTop="10dp" android:layout_gravity="center|bottom"
android:background="#null"></ImageButton>
</LinearLayout>
in the activity i add the custom view to layout with id layoutGIF in this way:
LinearLayout lg = (LinearLayout)findViewById(R.id.layoutGIF);
lg.setGravity(Gravity.CENTER);
gif = new GIFView(this);
lg.addView(gif, new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT));
what can i do? i need the elements under this!
best way is using animation.. don't think that gif is solution.. is not supported from every android device!

difficulty using AttributeSet.getAttributeIntValue()

My app needs the height and width of the extended ImageView. I thought this should work:
package my.android.test;
public class TestImageView extends ImageView
{
private int mWidth=0;
private int mHeight=0;
public TestImageView(Context context, AttributeSet as)
{
super(context, as);
final String xmlns="http://schemas.android.com/apk/res/android";
mWidth = as.getAttributeIntValue(xmlns, "layout_width", 0);
mHeight = as.getAttributeIntValue(xmlns, "layout_height", 0);
}
#Override
protected void onDraw(Canvas canvas)
{
//do stuff
}
}
but it doesn't work. 0 is returned by getAttributeIntValue() eventhough the layout_height is defined in the layout XML:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
android:background="#fffcb95a"
<LinearLayout android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
<FrameLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="6dip"
<my.android.test.TestImageView
android:id="#+id/TestImageViewID"
android:layout_width="100dip"
android:layout_height="100dip"
android:src="#drawable/icon"
android:scaleType="centerCrop" />
</RelativeLayout
</FrameLayout
</LinearLayout
</ScrollView
what to do ?
Note an explanation for why the original attempt doesn't work -- layout_width and layout_height are not actually holding integers, they are holding dimensions. You need to retrieve these via Context/Theme.obtainStyledAttributes, so you can get them as a TypedValue that can be converted to pixels.
Just call getWidth() and getHeight().

Categories

Resources