getSupportActionBar returns null

回眸只為那壹抹淺笑 提交于 2020-01-05 03:32:15

问题


I'm trying to use the ActionBarSherlock library for using Action Bar in older devices. My application run on Android(4.2-Real device). But, when I tried it to open in my older galaxy tab which ran on Android 2.3.4 it crashes. This is what I found from logcat

and here is the code of General Activity

    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 number 82 is

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

Here some of data of manifest file

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

Now, Another weird this is if it's run on android 4.2 it don't show the color as I describe by

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

Another thing I need to mention, I am getting NullPointerException below classes I defined tab inside tabactivity. I have another class to show data from a listview, in that class ABS working fine. As, I am using tab navigation in Android.Here is my Tab class. (If you need that)

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);
    }

}

Here is my style file

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

回答1:


If you are using ABS, then why are you using TabHost? You can use fragments in ABS to create tabs. And moreover, getSupportActionBar should be imported from import android.support.v7.app.ActionBar




回答2:


Action bar with tab:

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;
}

}



来源:https://stackoverflow.com/questions/18755349/getsupportactionbar-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!