我正在开发一个聊天应用程序,我正在尝试实现图像按钮,当点击这些按钮时,确切的图像将作为消息发送。这就像发送自定义表情符号。这些图像按钮是从drawable文件夹中的图像资源调用的。到目前为止界面看起来像这样:
https://i.stack.imgur.com/D2uF3.png
涉及的源代码是:
activity_main.xml中
<?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-auto"
xmlns:emojicon="http://schemas.android.com/apk/res-auto"
android:id="@+id/contentRoot"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/background">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<android.support.v7.widget.RecyclerView
android:id="@+id/messageRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none" />
<View
android:layout_width="match_parent"
android:layout_height="4dp"
android:layout_gravity="bottom"
android:background="@drawable/shadow_top" />
</FrameLayout>
<RelativeLayout xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:padding="15dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="horizontal">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="bottom">
<ImageButton
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/bath"
tools:ignore="DuplicateIds"/>
<ImageButton
android:id="@+id/icon2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/bite"
tools:ignore="DuplicateIds" />
<ImageButton
android:id="@+id/icon3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/bite1"
tools:ignore="DuplicateIds"/>
<ImageButton
android:id="@+id/icon4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/blow"
tools:ignore="DuplicateIds"/>
<ImageButton
android:id="@+id/icon5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/brush_hair"
tools:ignore="DuplicateIds"/>
<ImageButton
android:id="@+id/icon6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/build"
tools:ignore="DuplicateIds"/>
<ImageButton
android:id="@+id/icon7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/catch1"
tools:ignore="DuplicateIds"/>
<ImageButton
android:id="@+id/icon8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/change_channel"
tools:ignore="DuplicateIds"/>
<ImageButton
android:id="@+id/icon9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/wipe_face"
tools:ignore="DuplicateIds"/>
<ImageButton
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/drink"
tools:ignore="DuplicateIds"/>
<ImageButton
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/eat"
tools:ignore="DuplicateIds"/>
<ImageButton
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/go"
tools:ignore="DuplicateIds"/>
<ImageButton
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/go_in"
tools:ignore="DuplicateIds"/>
<ImageButton
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/go_out"
tools:ignore="DuplicateIds"/>
<ImageButton
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/knock_it_down"
tools:ignore="DuplicateIds"/>
<ImageButton
android:id="@+id/icon16"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/no"/>
<ImageButton
android:id="@+id/icon17"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/pull"/>
<ImageButton
android:id="@+id/icon18"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/push"/>
<ImageButton
android:id="@+id/icon19"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/roll"/>
<ImageButton
android:id="@+id/icon20"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/sit"/>
<ImageButton
android:id="@+id/icon21"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/sleep"/>
<ImageButton
android:id="@+id/icon22"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/stand"/>
<ImageButton
android:id="@+id/icon23"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/stand_up"/>
<ImageButton
android:id="@+id/icon24"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/throw1"/>
</LinearLayout>
</HorizontalScrollView>
</RelativeLayout>
<RelativeLayout
android:background="#fff"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="2dp">
<ImageView
android:id="@+id/buttonEmoji"
android:layout_width="40dp"
android:layout_height="40dp"
android:padding="4dp"
android:src="@drawable/smiley"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignBottom="@+id/editTextMessage"
/>
<hani.momanii.supernova_emoji_library.Helper.EmojiconEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editTextMessage"
android:layout_toStartOf="@+id/buttonMessage"
android:layout_toRightOf="@+id/buttonEmoji"
android:layout_toEndOf="@+id/buttonEmoji"
emojicon:emojiconSize="28sp"/>
<ImageView
android:id="@+id/buttonMessage"
android:src="@android:drawable/ic_menu_send"
android:layout_width="40dp"
android:layout_height="40dp"
android:padding="4dp"
android:layout_alignBottom="@+id/editTextMessage"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
/>
</RelativeLayout>
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, View.OnClickListener, ClickListenerChatFirebase {
private static final int IMAGE_GALLERY_REQUEST = 1;
private static final int IMAGE_CAMERA_REQUEST = 2;
private static final int PLACE_PICKER_REQUEST = 3;
static final String TAG = MainActivity.class.getSimpleName();
static final String CHAT_REFERENCE = "chatmodel";
//Firebase and GoogleApiClient
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;
private GoogleApiClient mGoogleApiClient;
private DatabaseReference mFirebaseDatabaseReference;
FirebaseStorage storage = FirebaseStorage.getInstance();
//CLass Model
private UserModel userModel;
//Views UI
private RecyclerView rvListMessage;
private LinearLayoutManager mLinearLayoutManager;
private ImageView btSendMessage,btEmoji,ivImage;
private ImageButton btPecs;
private EmojiconEditText edMessage;
private View contentRoot;
private EmojIconActions emojIcon;
//File
private File filePathImageCamera;
//Tabs
//private Toolbar toolbar;
//private TabLayout tabLayout;
//private ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
btPecs = (ImageButton)findViewById(R.id.icon);
//ivImage = (ImageView)findViewById(R.id.img_chat);
if (!Util.verificaConexao(this)){
Util.initToast(this,"You do not have an internet connection.");
finish();
}else{
bindViews();
verificaUsuarioLogado();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API)
.build();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
StorageReference storageRef = storage.getReferenceFromUrl(Util.URL_STORAGE_REFERENCE).child(Util.FOLDER_STORAGE_IMG);
if (requestCode == IMAGE_GALLERY_REQUEST){
if (resultCode == RESULT_OK){
Uri selectedImageUri = data.getData();
if (selectedImageUri != null){
sendFileFirebase(storageRef,selectedImageUri);
}else{
//URI IS NULL
}
}
}else if (requestCode == IMAGE_CAMERA_REQUEST){
if (resultCode == RESULT_OK){
if (filePathImageCamera != null && filePathImageCamera.exists()){
StorageReference imageCameraRef = storageRef.child(filePathImageCamera.getName()+"_camera");
sendFileFirebase(imageCameraRef,filePathImageCamera);
}else{
//IS NULL
}
}
}else if (requestCode == PLACE_PICKER_REQUEST){
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(this, data);
if (place!=null){
LatLng latLng = place.getLatLng();
MapModel mapModel = new MapModel(latLng.latitude+"",latLng.longitude+"");
ChatModel chatModel = new ChatModel(userModel,Calendar.getInstance().getTime().getTime()+"",mapModel);
mFirebaseDatabaseReference.child(CHAT_REFERENCE).push().setValue(chatModel);
}else{
//PLACE IS NULL
}
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.sendPhoto:
photoCameraIntent();
break;
case R.id.sendPhotoGallery:
photoGalleryIntent();
break;
case R.id.sign_out:
signOut();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.d(TAG, "onConnectionFailed:" + connectionResult);
Util.initToast(this,"Google Play Services error.");
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.buttonMessage:
sendMessageFirebase();
case R.id.icon:
sendMessageFirebase();
ivImage.setImageResource(R.drawable.bath);
break;
}
}
@Override
public void clickImageChat(View view, int position,String nameUser,String urlPhotoUser,String urlPhotoClick) {
Intent intent = new Intent(this,FullScreenImageActivity.class);
intent.putExtra("nameUser",nameUser);
intent.putExtra("urlPhotoUser",urlPhotoUser);
intent.putExtra("urlPhotoClick",urlPhotoClick);
startActivity(intent);
}
@Override
public void clickImageMapChat(View view, int position,String latitude,String longitude) {
String uri = String.format("geo:%s,%s?z=17&q=%s,%s", latitude,longitude,latitude,longitude);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(intent);
}
/**
* Envia o arvquivo para o firebase
*/
private void sendFileFirebase(StorageReference storageReference, final Uri file){
if (storageReference != null){
final String name = DateFormat.format("yyyy-MM-dd_hhmmss", new Date()).toString();
StorageReference imageGalleryRef = storageReference.child(name+"_gallery");
UploadTask uploadTask = imageGalleryRef.putFile(file);
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e(TAG,"onFailure sendFileFirebase "+e.getMessage());
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.i(TAG,"onSuccess sendFileFirebase");
Uri downloadUrl = taskSnapshot.getDownloadUrl();
FileModel fileModel = new FileModel("img",downloadUrl.toString(),name,"");
ChatModel chatModel = new ChatModel(userModel,"",Calendar.getInstance().getTime().getTime()+"",fileModel);
mFirebaseDatabaseReference.child(CHAT_REFERENCE).push().setValue(chatModel);
}
});
}else{
//IS NULL
}
}
/**
* Envia o arvquivo para o firebase
*/
private void sendFileFirebase(StorageReference storageReference, final File file){
if (storageReference != null){
UploadTask uploadTask = storageReference.putFile(Uri.fromFile(file));
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e(TAG,"onFailure sendFileFirebase "+e.getMessage());
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.i(TAG,"onSuccess sendFileFirebase");
Uri downloadUrl = taskSnapshot.getDownloadUrl();
FileModel fileModel = new FileModel("img",downloadUrl.toString(),file.getName(),file.length()+"");
ChatModel chatModel = new ChatModel(userModel,"",Calendar.getInstance().getTime().getTime()+"",fileModel);
mFirebaseDatabaseReference.child(CHAT_REFERENCE).push().setValue(chatModel);
}
});
}else{
//IS NULL
}
}
/**
* Obter local do usuario
*/
private void locationPlacesIntent(){
try {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
/**
* Enviar foto tirada pela camera
*/
private void photoCameraIntent(){
String nomeFoto = DateFormat.format("yyyy-MM-dd_hhmmss", new Date()).toString();
filePathImageCamera = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), nomeFoto+"camera.jpg");
Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
it.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(filePathImageCamera));
startActivityForResult(it, IMAGE_CAMERA_REQUEST);
}
/**
* Enviar foto pela galeria
*/
private void photoGalleryIntent(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, getString(R.string.select_picture_title)), IMAGE_GALLERY_REQUEST);
}
/**
* Enviar msg de texto simples para chat
*/
private void sendMessageFirebase(){
ChatModel model = new ChatModel(userModel,edMessage.getText().toString(), Calendar.getInstance().getTime().getTime()+"",null);
mFirebaseDatabaseReference.child(CHAT_REFERENCE).push().setValue(model);
edMessage.setText(null);
}
/**
* Ler collections chatmodel Firebase
*/
private void lerMessagensFirebase(){
mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
final ChatFirebaseAdapter firebaseAdapter = new ChatFirebaseAdapter(mFirebaseDatabaseReference.child(CHAT_REFERENCE),userModel.getName(),this);
firebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
int friendlyMessageCount = firebaseAdapter.getItemCount();
int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
if (lastVisiblePosition == -1 ||
(positionStart >= (friendlyMessageCount - 1) &&
lastVisiblePosition == (positionStart - 1))) {
rvListMessage.scrollToPosition(positionStart);
}
}
});
rvListMessage.setLayoutManager(mLinearLayoutManager);
rvListMessage.setAdapter(firebaseAdapter);
}
/**
* Verificar se usuario está logado
*/
private void verificaUsuarioLogado(){
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
if (mFirebaseUser == null){
startActivity(new Intent(this, LoginActivity.class));
finish();
}else{
userModel = new UserModel(mFirebaseUser.getDisplayName(), mFirebaseUser.getPhotoUrl() != null ? mFirebaseUser.getPhotoUrl().toString() : null, mFirebaseUser.getUid() );
lerMessagensFirebase();
}
}
/**
* Vincular views com Java API
*/
private void bindViews(){
contentRoot = findViewById(R.id.contentRoot);
edMessage = (EmojiconEditText)findViewById(R.id.editTextMessage);
btSendMessage = (ImageView)findViewById(R.id.buttonMessage);
btSendMessage.setOnClickListener(this);
btPecs = (ImageButton)findViewById(R.id.icon);
btPecs.setOnClickListener(this);
btEmoji = (ImageView)findViewById(R.id.buttonEmoji);
emojIcon = new EmojIconActions(this,contentRoot,edMessage,btEmoji);
emojIcon.ShowEmojIcon();
rvListMessage = (RecyclerView)findViewById(R.id.messageRecyclerView);
mLinearLayoutManager = new LinearLayoutManager(this);
mLinearLayoutManager.setStackFromEnd(true);
}
/**
* Sign Out no login
*/
private void signOut(){
mFirebaseAuth.signOut();
Auth.GoogleSignInApi.signOut(mGoogleApiClient);
startActivity(new Intent(this, LoginActivity.class));
finish();
}
}
我已经制作了界面,但我真的不知道如何使按钮工作..请我真的需要帮助
编辑:这是处理消息发送的ChatModel.java
import example.asuspc.prospect.model.FileModel;
import example.asuspc.prospect.model.MapModel;
/**
* Created by asus pc on 1/23/2017.
*/
public class ChatModel {
private String id;
private UserModel userModel;
private String message;
private String timeStamp;
private FileModel file;
private MapModel mapModel;
public ChatModel() {
}
public ChatModel(UserModel userModel, String message, String timeStamp, FileModel file) {
this.userModel = userModel;
this.message = message;
this.timeStamp = timeStamp;
this.file = file;
}
public ChatModel(UserModel userModel, String timeStamp, MapModel mapModel) {
this.userModel = userModel;
this.timeStamp = timeStamp;
this.mapModel = mapModel;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public UserModel getUserModel() {
return userModel;
}
public void setUserModel(UserModel userModel) {
this.userModel = userModel;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public FileModel getFile() {
return file;
}
public void setFile(FileModel file) {
this.file = file;
}
public MapModel getMapModel() {
return mapModel;
}
public void setMapModel(MapModel mapModel) {
this.mapModel = mapModel;
}
@Override
public String toString() {
return "ChatModel{" +
"mapModel=" + mapModel +
", file=" + file +
", timeStamp='" + timeStamp + '\'' +
", message='" + message + '\'' +
", userModel=" + userModel +
'}';
}
}