WebView WebView1 = (WebView) findViewById(R.id.webView1);

//Only hide the scrollbar, not disables the scrolling:
WebView1.setVerticalScrollBarEnabled(false);
WebView1.setHorizontalScrollBarEnabled(false);

//Only disabled the horizontal scrolling:
WebView1.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);

//To disabled the horizontal and vertical scrolling:
webview.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return (event.getAction() == MotionEvent.ACTION_MOVE);
}
});

 

Android Chat Bubble

In this Android tutorial, we will see about how to create an Android (bubble) layout for a chat application. We will use Android ListView with adapter to create the Android chat bubble layout.

Chat bubbles are background image that expands horizontally and vertically as required based on the message posted.

Android-Chat-Bubble

Nine-patch Image

In creating Android chat bubbles, nine-patch image plays a crucial role. Nine-patch image is a bitmap which stretches to fit the content posted in the View where it is applied as a background.

A NinePatch drawable is a standard PNG image that includes an extra 1-pixel-wide border. It must be saved with the extension .9.png, and saved into the res/drawable/ directory of your project. The border is used to define the stretchable and static areas of the image. You indicate a stretchable section by drawing one (or more) 1-pixel-wide black line(s) in the left and top part of the border (the other border pixels should be fully transparent or white). You can have as many stretchable sections as you want: their relative size stays the same, so the largest sections always remain the largest.

We can use the draw9patch tool provided with the Android-sdk to create a nine-patch image. There are lots of free online tools available to generate these images. Of course, we can use Photoshop and create ourselves.

bubble_a.9

bubble_b.9

Bubble ListView with Adapter

ListView will be the container to hold the chat conversation. We will customize the underlying Adapter which is responsible for each unit of the data that is displayed in the ListView. We will have a TextView for each of the rows in the list, with a nine-patch image background.

activity_chat_singlemessage.xml

<?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" >

    <LinearLayout
        android:id="@+id/singleMessageContainer"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/singleMessage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="5dip"
            android:background="@drawable/bubble_b"
            android:paddingLeft="10dip"
            android:text="Hello bubbles!"
            android:textColor="@android:color/primary_text_light" />
    </LinearLayout>

</LinearLayout>

activity_chat.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="80dp">
    </ListView>

    <RelativeLayout
        android:id="@+id/form"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:orientation="vertical" >

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="textMultiLine"
            android:ems="10"
            android:id="@+id/chatText"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_toLeftOf="@+id/buttonSend" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Send"
            android:id="@+id/buttonSend"
            android:layout_alignBottom="@+id/chatText"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />
    </RelativeLayout>

</RelativeLayout>

Chat Bubble Activity

We have a main Android Activity that is bind with the ListView coupled with the Adapter. For the sake of this example tutorial, I am changing the bubble background alternately. Those things can go in the business logic of you application.

ChatBubbleActivity.java

package com.javapapers.android.chat;

import android.app.Activity;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

public class ChatBubbleActivity extends Activity {
    private static final String TAG = "ChatActivity";

    private ChatArrayAdapter chatArrayAdapter;
    private ListView listView;
    private EditText chatText;
    private Button buttonSend;

    Intent intent;
    private boolean side = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent i = getIntent();
        setContentView(R.layout.activity_chat);

        buttonSend = (Button) findViewById(R.id.buttonSend);

        listView = (ListView) findViewById(R.id.listView1);

        chatArrayAdapter = new ChatArrayAdapter(getApplicationContext(), R.layout.activity_chat_singlemessage);
        listView.setAdapter(chatArrayAdapter);

        chatText = (EditText) findViewById(R.id.chatText);
        chatText.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    return sendChatMessage();
                }
                return false;
            }
        });
        buttonSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                sendChatMessage();
            }
        });

        listView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
        listView.setAdapter(chatArrayAdapter);

        //to scroll the list view to bottom on data change
        chatArrayAdapter.registerDataSetObserver(new DataSetObserver() {
            @Override
            public void onChanged() {
                super.onChanged();
                listView.setSelection(chatArrayAdapter.getCount() - 1);
            }
        });
    }

    private boolean sendChatMessage(){
        chatArrayAdapter.add(new ChatMessage(side, chatText.getText().toString()));
        chatText.setText("");
        side = !side;
        return true;
    }

}

ChatArrayAdapter.java

package com.javapapers.android.chat;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class ChatArrayAdapter extends ArrayAdapter {

	private TextView chatText;
	private List chatMessageList = new ArrayList();
	private LinearLayout singleMessageContainer;

	@Override
	public void add(ChatMessage object) {
		chatMessageList.add(object);
		super.add(object);
	}

	public ChatArrayAdapter(Context context, int textViewResourceId) {
		super(context, textViewResourceId);
	}

	public int getCount() {
		return this.chatMessageList.size();
	}

	public ChatMessage getItem(int index) {
		return this.chatMessageList.get(index);
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View row = convertView;
		if (row == null) {
			LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			row = inflater.inflate(R.layout.activity_chat_singlemessage, parent, false);
		}
		singleMessageContainer = (LinearLayout) row.findViewById(R.id.singleMessageContainer);
		ChatMessage chatMessageObj = getItem(position);
		chatText = (TextView) row.findViewById(R.id.singleMessage);
		chatText.setText(chatMessageObj.message);
		chatText.setBackgroundResource(chatMessageObj.left ? R.drawable.bubble_a : R.drawable.bubble_b);
		singleMessageContainer.setGravity(chatMessageObj.left ? Gravity.LEFT : Gravity.RIGHT);
		return row;
	}

	public Bitmap decodeToBitmap(byte[] decodedByte) {
		return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
	}

}

ChatMessage.java

package com.javapapers.android.chat;

public class ChatMessage {
	public boolean left;
	public String message;

	public ChatMessage(boolean left, String message) {
		super();
		this.left = left;
		this.message = message;
	}
}

Download the Android Studio project Chat Bubble

Thanks to Vijay for asking me to try out Android Studio. It is built on the IntelliJ Idea platform. My first experience with Android Studio is good and it is better than my favorite Eclipse. I am going to stick with Android Studio for all Android projects and tutorials. But Eclipse will continue be my IDE for Java development.

 

출처:http://javapapers.com/android/android-chat-bubble/


나인패치(9patch)를 써보자



ㆍ 개발자들도 필수적으로 알아야되는 나인패치를 사용해보도록 

    하겠습니다.

ㆍ 뭐 설명보다는 써보면서 이해하는게 빠를 것 같으므로 

    바로 시작해보겠습니다.





텍스트 입력이 가능한

버튼에 이미지를

background로

입히는 경우가 있습니다.


뭐 이런식으로 들어가겠죠


그런데

버튼에 들어가는

Text가 고정이 아니라

동적으로

변하는 경우면 어떨까요?


만약 텍스트양이 많아지면?


이런식으로

꼴보기 싫게 변합니다


하지만!!

여기서 나인패치를

적용한다면?

다음과 같은

결과물을 얻을수 있습니다.


텍스트의 길이에 상관없이

깔끔한 버튼이미지를

유지할 수 있습니다.


바로 사용법을

알아보도록 하겠습니다.


기본적으로 나인패치는

[sdk]-[tools]-[draw9patch.bat]

에서 실행시킬 수 있습니다.


하지만 요즘은 고맙게도

웹에서 바로 사용할 수 있습니다.

http://romannurik.github.io/AndroidAssetStudio/nine-patches.html



자 먼저 사용할

이미지를 준비합니다

(.png)


그리고 사이즈는 보통

1글자 들어갔을때의

사이즈로 잡아주시면 됩니다


저는 포토샵을 못쓰므로

파워포인트에서 png파일을

만들었습니다.


위에 버튼이미지도 파포로..ㅎㅎ.


본론으로

넘어가서

사이트에 접속후

Select 버튼을 눌러서

이미지를 가져옵니다


가져오면

이런식으로

나타납니다.

(파포수준 ㅠ)


자 이렇게

나오면 두가지를

설정해보도록

하겠습니다.


처음에는

CONTENT PADDING

입니다


여기서는 말그대로

글자가 들어갈 위치를

잡아줍니다.

패딩값을 잡아주는거죠


요론식으로 좌표값을

보면서 하면

더 정확하게 만들 수 있답니다.


요기도 22 

슉슉


22 4콤보 완료


자 두번째는

STRETCH REGIONS

입니다


여기서는 늘려줄 부분을

설정해줍니다.


아 이부분은

도형이 너무 쉬워서.

음 애매하지만..

저 검정색 십자가부분이

늘어나는 부분입니다.

가로든 세로든 증가할때

저 빨간색부분이 길어지는 겁니다


급하게

다른 도형들 하나 예를 들면


이런식으로 위와 비슷하게

STRETCH REGIONS

를 잡아주게 되면

저 아래로 내려오는 뾰족한

부분은 크기가 안변한답니다

이런 식의 결과를

얻을 수 있죠


만약 범위를

이렇게 잡는다면?

아래쪽 가로는

뾰족한 오른쪽 부분


위쪽 가로는 

일자


왼쪽,오른쪽 세로는

색깔이 섞이고도 

해괴한 모양으로

늘어날 것 같군요.


어느 정도 이해가

가실거라..생각하고 

마무리를 하자면

범위를 다 정하고 나면

압축형태로

다운을 받습니다


압축을 풀고

나면


확장자도 특이한

9.png 파일이 생성됩니다

여기서 .9 지우면 

안됩니다.

.9가 있어야 나인패치

효과가 적용됩니다


이제 복사를 해서

프로젝트 drawable

폴더에 넣어서 쓰시면

완료~

 

출처:http://itpangpang.xyz/169

+ Recent posts