我正在创建一个应用程序。我有一个登录页面。登录后,我显示从firebase中检索到的用户列表,点击任何用户,显示聊天屏幕。我使用Fragments完成了这个。我有UsersListFragment.java
和ChatFragment.java
,活动为HomeActivity.java
。
我的应用程序适用于手机。我现在正试图为平板电脑制作它。对于手机,我在不同的屏幕上显示用户列表和聊天。但是对于平板电脑,我希望它们都在同一个屏幕上。当我点击某个用户时,该用户的相应聊天应显示在另一个片段中。
我已经提到了这一切。但是我仍然无法得到如何继续。
1)https://developer.android.com/training/basics/fragments/fragment-ui.html#AddAtRuntime
2)https://developer.android.com/training/basics/fragments/communicating.html#Deliver
3)https://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity
4)http://www.vogella.com/tutorials/AndroidFragments/article.html
参考代码。
actvity_home.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:background="#FFFFFF"
tools:context=".Activity.HomeActivity">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="0dp"
android:layout_height="match_parent"
android:id="@+id/framecontainerMain"
android:layout_weight="1"
android:orientation="horizontal"
>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="0dp"
android:layout_height="match_parent"
android:id="@+id/framecontainer"
android:layout_gravity="left"
android:layout_weight="0.5"
android:orientation="horizontal"
>
</FrameLayout>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="0dp"
android:layout_height="match_parent"
android:id="@+id/framecontainerTab"
android:layout_weight="0.5"
android:layout_gravity="right"
android:orientation="horizontal"
>
</FrameLayout>
</LinearLayout>
</LinearLayout>
HomeActivity.java
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
Log.d(TAG,String.valueOf(height));
if (width > 1023 || height > 1184){
//code for big screen (like tablet)
FrameLayout layout1 = (FrameLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.VISIBLE);
FrameLayout layout2 = (FrameLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.VISIBLE);
mItemsFragment = new UsersListFragment();
mItemsFragment.initlizeval(this);
android.support.v4.app.FragmentTransaction fts = getSupportFragmentManager().beginTransaction();
fts.add(R.id.framecontainer, mItemsFragment).commit();
//Instantiate some stuff here like view components
Fragment fragmentOne = new ChatFragment();
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.framecontainerTab, fragmentOne).commit();
}else{
FrameLayout layout1 = (FrameLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.GONE);
FrameLayout layout2 = (FrameLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.GONE);
layout2.removeAllViews();
mItemsFragment = new UsersListFragment();
mItemsFragment.initlizeval(this);
setFragment(mItemsFragment);
//code for small screen (like smartphone)
}
}
public void setFragment(Fragment frag)
{
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.framecontainerMain, frag).commit();
}
@Override
public void onFragmentInteraction(String uri) {
FrameLayout layout1 = (FrameLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.GONE);
FrameLayout layout2 = (FrameLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.GONE);
}
@Override
public void onBackPressed() {
super.onBackPressed();
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
if (width > 1023 || height > 1184) {
Fragment fragmentOne = new ChatFragment();
FrameLayout layout1 = (FrameLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.VISIBLE);
FrameLayout layout2 = (FrameLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.VISIBLE);
}
}
UsersListFragment.java
public void onButtonPressed(Uri uri) {
if (mListener != null) {
String val = "'";
mListener.onFragmentInteraction(val);
}
}
public void initlizeval(Context context) {
mListener = (OnFragmentInteractionListener) context;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(String val);
}
ChatFragment.java
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
chatMessages = new ArrayList<>();
view = inflater.inflate(R.layout.fragment_chat, container, false);
listView = (ListView) view.findViewById(R.id.list_msg);
adapter = new MessageAdapter(getActivity(), R.layout.item_chat_left, chatMessages);
listView.setAdapter(adapter);
setHasOptionsMenu(true);
actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayUseLogoEnabled(false);
ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#72B94F"));
actionBar.setBackgroundDrawable(colorDrawable);
actionBar.setHomeAsUpIndicator(R.drawable.ic_backarrow);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
String[] strings = {Global.getInstance().someData, Global.getInstance().ownerId};
Arrays.sort(strings);
Arrays.sort(strings);
String first = strings[0];
String second = strings[1];
chatKey = first + "_" + second;
final FirebaseUtil utils = new FirebaseUtil(getContext());
String timeaTab = Global.getInstance().time;
chatMessages.clear();
utils.startListeningMsgs(chatKey, timeaTab, new CallBack() {
@Override
public void onCallback(Map<String, Object> response, String Success) {
Map<String, Object> sentByMe = (Map<String, Object>) response.get("value");
Double chat_time = (Double) response.get("last_sent");
// String timeString = String.valueOf(chat_time);
String sentBy = (String) sentByMe.get("sent_by");
String ownerId = Global.getInstance().ownerId;
synchronized (this) {
ChatMessage chat;
if (sentBy.equals(ownerId)) {
String msg = (String) sentByMe.get("msg");
chat = new ChatMessage();
chat.setContent(msg);
String mine = "false";
chat.setIsMine(mine);
chat.setTime(chat_time);
} else {
String msg = (String) sentByMe.get("msg");
chat = new ChatMessage();
chat.setContent(msg);
String mine = "true";
chat.setIsMine(mine);
chat.setTime(chat_time);
}
chatMessages.add(chat);
}
adapter.notifyDataSetChanged();
}
});
mEmailSignInButton = (Button) view.findViewById(R.id.btn_chat_send);
editText = (EditText) view.findViewById(R.id.msg_type);
//event for button SEND
mEmailSignInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), String.valueOf( Global.getInstance().unreadMessageUsers.size()) , Toast.LENGTH_SHORT).show();
if (editText.getText().toString().trim().equals("")) {
Toast.makeText(getActivity(), "Type some message...", Toast.LENGTH_SHORT).show();
} else {
Map<String, Object> val = new HashMap<String, Object>();
val.put("msg", editText.getText().toString());
val.put("sent_by", Global.getInstance().ownerId);
val.put("sent_to", Global.getInstance().someData);
val.put("type", "chat");
FirebaseUtil utilMsg = new FirebaseUtil(getContext());
utilMsg.setNewMessageNotification(Global.getInstance().ownerId, Global.getInstance().someData, "chat");
utilMsg.sendMessageRequestChatKeyValue(chatKey, val);
editText.setText("");
}
}
});
return view;
}
}
对于平板电脑,登录应用程序崩溃后。我猜我无法设置视图。
日志
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rider.project/com.rider.project.Activity.HomeActivity}: java.lang.NullPointerException: rhs == null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: rhs == null
at java.lang.String.compareTo(Native Method)
at java.lang.String.compareTo(String.java:335)
at java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:286)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:153)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:142)
at java.util.Arrays.sort(Arrays.java:1957)
at com.rider.project.Fragments.ChatFragment.onCreateView(ChatFragment.java:189)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2080)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1290)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:801)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1677)
at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:388)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:604)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:178)
at com.rider.project.Activity.HomeActivity.onStart(HomeActivity.java:172)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1237)
at android.app.Activity.performStart(Activity.java:6253)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
请有人告诉我,我能做些什么。新的android。 提前谢谢。
答案 0 :(得分:1)
试试这个:
2个不同的布局文件夹:layout,其中包含智能手机的actvity_home.xml,片段布局等; layout-large,包含用于平板电脑的actvity_home.xml。
在HomeActivity.java中,用以下内容替换您发布的代码:
// Part of onCreate()
setContentView(R.layout.activity_home);
FrameLayout layout1 = (FrameLayout) findViewById(R.id.framecontainer);
FrameLayout layout2 = (FrameLayout) findViewById(R.id.framecontainerTab);
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Initialize UserListFragment
// and setTag, UserList. [Both smartphone and tablet]
mItemsFragment = new UsersListFragment();
mItemsFragment.initlizeval(this);
ft.add(R.id.framecontainer, frag, "UserList").commit();
if (layout2 != null){
// Tablet, initiallly no user selected and layout is GONE.
layout2.setVisibility(View.GONE);
}
}
@Override
public void onFragmentInteraction(String uri) {
FrameLayout layout2 = (FrameLayout) findViewById(R.id.framecontainerTab);
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ChatFragment fragmentOne = new ChatFragment();
if(layout2 == null){ // Smartphone, replace fragment.
ft.replace(R.id.framecontainer, fragmentOne, "Chat");
ft.addToBackStack(null);
ft.commit();
}else{ // Tablet, add fragment and show on UI.
ft.add(R.id.framecontainerTab, fragmentOne, "Chat").commit();
layout2.setVisibility(View.VISIBLE);
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
FrameLayout layout2 = (FrameLayout) findViewById(R.id.framecontainerTab);
if (layout2 != null) { // Tablet
if(layout2.isShown()){
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
ChatFragment fragmentOne = (ChatFragment) fm.findFragmentByTag("Chat");
fm.beginTransaction().remove(fragmentOne).commit();
layout2.setVisibility(View.GONE);
}
}
}
希望有所帮助!
答案 1 :(得分:0)
您是否已将HomeActivity添加到清单文件中