簡體   English   中英

在Android中為菜單項設置自定義字體

[英]Set custom font for menu items in Android

我試圖實現自定義菜單。 我用了這個問題給出的答案。 在我的代碼中,名稱是ExpandedMenuItem,但在所有示例中都是IconMenuItemView。 那里發生了什么? 我怎么能糾正這個?

這是我的代碼。

    public class MyActivity extends PreferenceActivity {

         @Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.proximity_alert_menu, menu);
    getLayoutInflater().setFactory(new Factory() {

        @Override
        public View onCreateView(String name, Context context, AttributeSet attrs) {         

                        //if(name.equalsIgnoreCase("com.android.internal.view.menu.MenuItem")) {}
                        try {
                           LayoutInflater li = LayoutInflater.from(context);
                           final View view = li.createView(name, null, attrs);
                           new Handler().post(new Runnable() {
                           public void run() {
                            TextView tView = (TextView) view;
                            tView.setTypeface(Config.set_font);
                            tView.setTextColor(Color.RED);
                           }
                    });
                    return view;
                 } catch (InflateException e) {
                   e.printStackTrace();
                 } catch (ClassNotFoundException e) {
                   e.printStackTrace();
                 }
                 return null;
      }
        });
    return super.onCreateOptionsMenu(menu);
        }
    }

例外表明

      java.lang.ClassCastException:com.android.internal.view.menu.ExpandedMenuView cannot be cast to android.widget.TextView

我如何將其轉換為TextView?

您可以按如下方式檢查View是否為TextView ...

if (view instanceof TextView) {
    TextView tView = (TextView) view;
    tView.setTypeface(Config.set_font);
    tView.setTextColor(Color.RED);
}

如果視圖是TextView ,則將更改FontColor

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);

    tf = Typeface.createFromAsset(MainActivity.this.getAssets(),
            "MuseoSansCyrl.otf");
    MenuItem i = menu.findItem(R.id.item1);
    TextView itemuser = (TextView) i.getActionView();

           Typeface tf= Typeface.createFromAsset(this.getAssets(), "MuseoSansCyrl.otf");
           itemuser.setTypeface(tf);
           itemuser.setText("Item1");
           itemuser.setBackgroundColor(Color.TRANSPARENT);
           retun true;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM