본문 바로가기
프로그래밍 놀이터/안드로이드, Java

[Android] 이미지와 텍스트 함께 배치하기. ( 신문기사처럼 )

by 돼지왕 왕돼지 2014. 4. 11.
반응형


 [Android] 이미지와 텍스트 함께 배치하기. ( 신문기사처럼 )

 

[Android] 이미지와 텍스트 함께 배치하기. ( 신문기사처럼 )


http://gmariotti.blogspot.de/2014/03/snippet-align-textview-around-image.html


LeadingMarginSpan.LeadingMarginSpan2 를 이용하면 가능하다.


class MyLeadingMarginSpan2 implements LeadingMarginSpan.LeadingMarginSpan2 {


private int margin;

private int lines;


MyLeadingMarginSpan2(int lines, int margin) {

this.margin = margin;

this.lines = lines;

}


/**

 * Apply the margin

 *

 * @param first

 * @return

 */

@Override

public int getLeadingMargin(boolean first) {

if (first) {

return margin;

} else {

return 0;

}

}


@Override

public void drawLeadingMargin(Canvas c, Paint p, int x, int dir,int top, int baseline, int bottom, CharSequence text, int start, int end, boolean first, Layout layout) {}



@Override

public int getLeadingMarginLineCount() {

return lines;

}

};


getLeadingMargingetLeadingMarginLineCount 를 구현하여,

leading margin 을 주고 싶은 line 수와, leading margin 값을 return 해주면 된다.


[Android] 이미지와 텍스트 함께 배치하기. ( 신문기사처럼 )

코드 적용은 아래와 같다.


public class MainActivity extends Activity {


    private int finalWidth, finalHeight;


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        mTextView = (TextView) findViewById(R.id.text);

        mImageView = (ImageView) findViewById(R.id.icon);



        final ViewTreeObserver vto = mImageView.getViewTreeObserver();

        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override

            public void onGlobalLayout() {

                mImageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);

                finalHeight = mImageView.getMeasuredHeight();

                finalWidth = mImageView.getMeasuredWidth();

                makeSpan();

            }

        });

    }

}


**

 * This method builds the text layout

 */

private void makeSpan() {


String plainText=getResources().getString(R.string.text_sample);


float fontSpacing=mTextView.getPaint().getFontSpacing();

int lines = (int) (finalHeight/fontSpacing);


MyLeadingMarginSpan2 span = new MyLeadingMarginSpan2(lines, finalWidth +10 );

mSpannableString.setSpan(span, 0, plainText.length() - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);


mTextView.setText(mSpannableString);

}






반응형

댓글