android.support.v7.app.ActionBarActivity问题

时间:2016-07-21 09:58:11

标签: java android android-actionbaractivity appcompatactivity

我在编译代码时遇到问题,说实话我不太清楚这里出了什么问题。我正在使用我在网上找到的教程来学习如何创建Android Chat应用程序。我虽然没有红线?

以下是我的MainActivity代码:

package com.example.brian.chatapp;

import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import android.widget.TextView;

import com.example.brian.fragments.Chats;

import java.util.Locale;

public class MainActivity extends AppCompatActivity {

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

  FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
  fab.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
          Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                  .setAction("Action", null).show();
      }
  });

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}




/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {public SectionsPagerAdapter(FragmentManager fm) {
    super(fm);
}@Override
public Fragment getItem(int position) {
    if (position == 1) {
        return new Chats();
    } else
        return PlaceholderFragment.newInstance(position + 1);
}@Override
public int getCount() {
// Show 3 total pages.
    return 3;
}@Override
public CharSequence getPageTitle(int position) {
    Locale l = Locale.getDefault();
    switch (position) {
        case 0:
            return getString(R.string.title_section1).toUpperCase(l);
        case 1:
            return getString(R.string.title_section2).toUpperCase(l);
        case 2:
            return getString(R.string.title_section3).toUpperCase(l);
    }
    return null;
}
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }
}
}

以下是聊天活动的代码:

package com.example.brian.fragments;

import java.util.ArrayList;
import java.util.Random;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;

import com.example.brian.chatapp.ChatAdapter;
import com.example.brian.chatapp.ChatMessage;
import com.example.brian.chatapp.CommonMethods;
import com.example.brian.chatapp.R;

public class Chats extends Fragment implements OnClickListener {

private EditText msg_edittext;
private String user1 = "khushi", user2 = "khushi1";
private Random random;
public static ArrayList<ChatMessage> chatlist;
public static ChatAdapter chatAdapter;
ListView msgListView;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.chat_layout, container, false);
    random = new Random();
    ((ActionBarActivity) getActivity()).getSupportActionBar().setTitle(
            "Chats");
    msg_edittext = (EditText) view.findViewById(R.id.messageEditText);
    msgListView = (ListView) view.findViewById(R.id.msgListView);
    ImageButton sendButton = (ImageButton) view
            .findViewById(R.id.sendMessageButton);
    sendButton.setOnClickListener(this);

    // ----Set autoscroll of listview when a new message arrives----//
    msgListView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
    msgListView.setStackFromBottom(true);

    chatlist = new ArrayList<ChatMessage>();
    chatAdapter = new ChatAdapter(getActivity(), chatlist);
    msgListView.setAdapter(chatAdapter);
    return view;
}

@Override
public void onSaveInstanceState(Bundle outState) {
}

public void sendTextMessage(View v) {
    String message = msg_edittext.getEditableText().toString();
    if (!message.equalsIgnoreCase("")) {
        final ChatMessage chatMessage = new ChatMessage(user1, user2,
                message, "" + random.nextInt(1000), true);
        chatMessage.setMsgID();
        chatMessage.body = message;
        chatMessage.Date = CommonMethods.getCurrentDate();
        chatMessage.Time = CommonMethods.getCurrentTime();
        msg_edittext.setText("");
        chatAdapter.add(chatMessage);
        chatAdapter.notifyDataSetChanged();
    }
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.sendMessageButton:
            sendTextMessage(v);

    }
}

}

这是我收到的错误:

07-21 04:43:39.605 3063-3063/com.example.brian.chatapp E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.brian.chatapp, PID: 3063
                                                                     java.lang.ClassCastException: com.example.brian.chatapp.MainActivity cannot be cast to android.support.v7.app.ActionBarActivity
                                                                         at com.example.brian.fragments.Chats.onCreateView(Chats.java:35)
                                                                         at android.support.v4.app.Fragment.performCreateView(Fragment.java:2074)
                                                                         at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
                                                                         at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1286)
                                                                         at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:758)
                                                                         at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1632)
                                                                         at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:637)
                                                                         at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
                                                                         at android.support.v4.view.ViewPager.populate(ViewPager.java:1235)
                                                                         at android.support.v4.view.ViewPager.populate(ViewPager.java:1083)
                                                                         at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1609)
                                                                         at android.view.View.measure(View.java:17430)
                                                                         at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
                                                                         at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:669)
                                                                         at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:89)
                                                                         at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1319)
                                                                         at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:734)
                                                                         at android.view.View.measure(View.java:17430)
                                                                         at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
                                                                         at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
                                                                         at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
                                                                         at android.view.View.measure(View.java:17430)
                                                                         at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
                                                                         at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
                                                                         at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
                                                                         at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
                                                                         at android.view.View.measure(View.java:17430)
                                                                         at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
                                                                         at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
                                                                         at android.view.View.measure(View.java:17430)
                                                                         at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
                                                                         at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
                                                                         at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
                                                                         at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
                                                                         at android.view.View.measure(View.java:17430)
                                                                         at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
                                                                         at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
                                                                         at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2560)
                                                                         at android.view.View.measure(View.java:17430)
                                                                         at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2001)
                                                                         at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1166)
                                                                         at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1372)
                                                                         at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054)
                                                                         at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5779)
                                                                         at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
                                                                         at android.view.Choreographer.doCallbacks(Choreographer.java:580)
                                                                         at android.view.Choreographer.doFrame(Choreographer.java:550)
                                                                         at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
                                                                         at android.os.Handler.handleCallback(Handler.java:739)
                                                                         at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                         at android.os.Looper.loop(Looper.java:135)
                                                                         at android.app.ActivityThread.main(ActivityThread.java:5221)
                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                         at java.lang.reflect.Method.invoke(Method.java:372)
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller

以下是教程的链接,供参考(如果需要): Chat App Tutorial

1 个答案:

答案 0 :(得分:7)

在片段的onCreateView中,当您尝试通过强制转换父Activity来更改标题ActionBar时,您执行了以下操作:

((ActionBarActivity) getActivity()).getSupportActionBar().setTitle("Chats");

而您的父级活动是AppCompatActivity而不是ActionBarActivity。你应该这样投:

((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Chats");