getSupportActionBar返回null

时间:2013-09-12 04:25:13

标签: java android android-actionbar actionbarsherlock

我正在尝试使用ActionBarSherlock库在旧设备中使用Action Bar。我的应用程序在Android(4.2-Real device)上运行。但是,当我尝试在Android 2.3.4上运行的旧星系标签中打开时,它会崩溃。这是我在logcat

中找到的

enter image description here

这是一般活动的代码

    TextView text;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_general);

        /*initial UI*/

        initialUI();

        /*Read file*/
        String raw=readRawTextFile(this, R.raw.information);

        /**/
        MarkdownProcessor markDownPro = new MarkdownProcessor();

        /**/
        String getMarkDown = markDownPro.markdown(raw);

        /**/
        CharSequence cs = Html.fromHtml(getMarkDown);

        /**/
        text.setText(cs);

    }

    private void initialUI(){
        text = (TextView)findViewById(R.id.text);
    }

    /**/

    public static String readRawTextFile(Context ctx, int resId) {
        InputStream inputStream=ctx.getResources().openRawResource(resId);
        InputStreamReader inputreader=new InputStreamReader(inputStream);
        BufferedReader buffreader=new BufferedReader(inputreader);
        String line;
        StringBuilder text=new StringBuilder();

        try {
          while ((line=buffreader.readLine())!=null) {
            text.append(line);
            text.append('\n');
          }
        }
        catch (IOException e) {
          return null;
        }
        return text.toString();
      }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        MenuInflater inflater = getSupportMenuInflater();

        inflater.inflate(R.menu.general, menu);

        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#003f84")));

        return true;
    }
}

GeneralActivity编号82是

 getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#003f84")));

这里有一些清单文件的数据

<uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="17" />

<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/Theme.Sherlock.Light.DarkActionBar" >

现在,另一个奇怪的是,如果它在Android 4.2上运行,它不会显示我所描述的颜色

getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#003f84")));

我需要提一下的另一件事是,我在NullPointerException内定义标签的类下面tabactivity。我有另一个类来显示listview中的数据,在那个类ABS工作正常。因为,我在Android中使用标签导航。这是我的Tab类。 (如果你需要的话)

public class Tabs extends TabActivity {
/** Called when the activity is first created. */

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        setTabs() ;
    }
    private void setTabs()
    {
        addTab("Info", R.drawable.tab_home, GeneralActivity.class);
        addTab("Program", R.drawable.tab_search, ScheduleMainActivity.class);

        addTab("Abstracts", R.drawable.tab_home,AbstractActivity.class);
        addTab("Map", R.drawable.tab_map,LocationMarkers.class);
    }

    private void addTab(String labelId, int drawableId, Class<?> c)
    {
        TabHost tabHost = getTabHost();
        Intent intent = new Intent(this, c);
        TabHost.TabSpec spec = tabHost.newTabSpec("tab" + labelId); 

        View tabIndicator = LayoutInflater.from(this).inflate(R.layout.tab_indicator, getTabWidget(), false);
        TextView title = (TextView) tabIndicator.findViewById(R.id.title);
        title.setText(labelId);
        ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
        icon.setImageResource(drawableId);

        spec.setIndicator(tabIndicator);
        spec.setContent(intent);
        tabHost.addTab(spec);
    }

}

这是我的样式文件

<resources>

    <!--
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
    -->
    <style name="AppBaseTheme" parent="android:Theme.Light">
        <!--
            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.
        -->
    </style>

    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    </style>

</resources>

2 个答案:

答案 0 :(得分:0)

带标签的操作栏:

import static com.actionbarsherlock.app.ActionBar.NAVIGATION_MODE_TABS;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.TabListener;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;

public class Activitytest extends SherlockFragmentActivity implements OnPageChangeListener, TabListener {

private String TAG="TestActivity: ";
private FileCache fileCache;
private ViewPager mPager;
private ActionBar ab;
private static final int COUNT = 3;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.property_add);
    mPager = (ViewPager) findViewById(R.id.pager);
    mPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
    mPager.setOnPageChangeListener(this);
    ab = getSupportActionBar();

     if (Utils.hasHoneycomb()) {
         ab.setDisplayShowTitleEnabled(false);
         ab.setDisplayHomeAsUpEnabled(false);
         getSupportActionBar().setDisplayShowHomeEnabled(false);
        }else{
            ab.setDisplayShowTitleEnabled(false);
            ab.setDisplayShowHomeEnabled(false);
        }
    ab.setNavigationMode(NAVIGATION_MODE_TABS);

    ab.addTab(ab.newTab().setText("TAB").setTabListener(this));
    ab.addTab(ab.newTab().setText("TAB 1").setTabListener(this));
    ab.addTab(ab.newTab().setText("TAB 2").setTabListener(this));

}       
@Override
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
    // TODO Auto-generated method stub
    com.actionbarsherlock.view.MenuInflater inflater = getSupportMenuInflater();
    inflater.inflate(R.menu.home, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
    // TODO Auto-generated method stub
   switch (item.getItemId()) {
   case android.R.id.home:
       NavUtils.navigateUpFromSameTask(this);
       return true;
   }
   return super.onOptionsItemSelected(item);
}
@Override
public void onPageScrolled(int position, float positionOffset,int positionOffsetPixels) {}
@Override
public void onPageSelected(int position) {
    getSupportActionBar().setSelectedNavigationItem(position);
}

@Override
public void onPageScrollStateChanged(int state) {}

@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
    mPager.setCurrentItem(this.getSupportActionBar().getSelectedNavigationIndex()); 
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {}

public class MyAdapter extends FragmentPagerAdapter {
    public MyAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public int getCount() {
        return COUNT;
    }

    @Override
    public Fragment getItem(int position) {
        Fragment f = new Fragment();
        switch (position) {
        case 0:
            f = Add1FragmentActivity.newInstance(position);
            break;
        case 1:
            f = Add2FragmentActivity.newInstance(position);
            break;
        case 2:
            f = Add3FragmentActivity.newInstance(position);
            break;
        default:
            AppLog.logString(TAG+"Default");
            throw new IllegalArgumentException("not this many fragments: " + position);
        }
        return f;
    }
}
}



public class Utils {
private Utils() {};
public static boolean hasFroyo() {
    // Can use static final constants like FROYO, declared in later versions
    // of the OS since they are inlined at compile time. This is guaranteed behavior.
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
}

public static boolean hasGingerbread() {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
}

public static boolean hasHoneycomb() {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
}

public static boolean hasHoneycombMR1() {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1;
}

public static boolean hasJellyBean() {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
}

}

答案 1 :(得分:0)

如果您使用ABS,那么为什么使用TabHost?您可以在ABS中使用片段来创建选项卡。 此外,getSupportActionBar应从import android.support.v7.app.ActionBar

导入