如何在android lollipop中获取操作栏标题textview引用

时间:2015-06-26 19:02:41

标签: android android-actionbar android-5.0-lollipop android-support-library android-actionbar-compat

我正在开发演示应用,我想在操作栏标题textview上应用点击监听器。我的下面的代码在Android 5.0下工作正常,它找到正确的操作栏标题textview引用和点击监听器也工作正常但在Android棒棒糖上我在这里得到空TextView abTitleTV = (TextView) findViewById(abTitleId);

如何在android lollipop中获取操作栏标题引用?

public class HomeActivity extends ActionBarActivity {

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

        // find the view of actionbar title
        // set the onclick listener so when you click on it
        try {
            int abTitleId = 0;
            if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) {
                abTitleId = getResources().getIdentifier("action_bar_title", "id", "android");
            }
            else {
              // This is the id is from your app's generated R class when ActionBarActivity is used for SupportActionBar
                abTitleId = R.id.action_bar_title;
            }

            TextView abTitleTV = (TextView) findViewById(abTitleId);
            abTitleTV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(HomeActivity.this, TestActivity.class));
                }
            });

            TypedValue tv = new TypedValue();
            if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
                abTitleTV.setHeight(TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics()));
            }

            abTitleTV.setWidth((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, getResources().getDisplayMetrics()));


            // setting the gravity to center
            abTitleTV.setGravity(Gravity.CENTER_VERTICAL);

        } catch(Exception e) {
            Logger.e(TAG, e.getMessage());
        }
    }
}

0 个答案:

没有答案