当前位置: 首页 > 知识库问答 >
问题:

Android抽屉菜单图片

云浩然
2023-03-14

你好,我有一个关于Android导航抽屉的问题。我在我的应用程序中包含了导航抽屉,一切都很顺利,但我想将图像添加到列表中的每个菜单中。

我是Android新手,所以如果有人能帮助我,我将不胜感激,这是导航抽屉的源代码

http://javatechig.com/android/navigation-drawer-android-example

这是我的WebViewFragments文件

public class WebViewFragment extends Fragment {
    private WebView mWebView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        // Retrieving the currently selected item number
        int position = getArguments().getInt("position");

        String url = getArguments().getString("url");

        // List of rivers
        String[] menus = getResources().getStringArray(R.array.menus);

        // Creating view corresponding to the fragment
        View v = inflater.inflate(R.layout.activity_main, container, false);

        // Updating the action bar title
        getActivity().getActionBar().setTitle(menus[position]);

        //Initializing and loading url in webview








        WebView wv = (WebView) getActivity().findViewById(R.id.webView1);
        wv.getSettings().setJavaScriptEnabled(true);
        CookieSyncManager.createInstance(getActivity()); 
        CookieSyncManager.getInstance().startSync();
        wv.loadUrl(url);
        wv.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });


        return v;
    }

    @Override
    public void onResume() {
        super.onResume();
        CookieSyncManager.getInstance().stopSync();

    }
    @Override
    public void onPause() {
        super.onPause();
        CookieSyncManager.getInstance().sync();
    }


}

这是我的主要活动

public class MainActivity extends Activity {

    // Within which the entire activity is enclosed
    private DrawerLayout mDrawerLayout;

    // ListView represents Navigation Drawer
    private ListView mDrawerList;

    // ActionBarDrawerToggle indicates the presence of Navigation Drawer in the action bar
    private ActionBarDrawerToggle mDrawerToggle;

    // Title of the action bar
    private String mTitle = "";

    static boolean active = false;
    private String possibleEmail2;
    private WebView mWebView;

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        CookieSyncManager.createInstance(this); 
        CookieSyncManager.getInstance().startSync();

        Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
        Account[] accounts = AccountManager.get(getBaseContext()).getAccounts();
        for (Account account : accounts) {
            if (emailPattern.matcher(account.name).matches()) {
                possibleEmail2 = account.name;


            }
        }

        String finalurl = "http://google.ro/?mail=" + possibleEmail2;

        if (isNetworkAvailable(getBaseContext()))
        {



            mWebView = (WebView) findViewById(R.id.webView1);
            mWebView.getSettings().setJavaScriptEnabled(true);
            try
            {
                Method mWebView = MainActivity.class.getDeclaredMethod("setCacheDisabled", boolean.class);
                mWebView.setAccessible(true);
                mWebView.invoke(null, true);
            }
            catch (Throwable e)
            {
                Log.i("myapp","Reflection failed", e);
            }
            mWebView.loadUrl(finalurl);




        }
        else
        {
            mWebView = new WebView(this);   
            new AlertDialog.Builder(this)
            .setTitle("Connection Error")
            .setMessage("You dont have an active network connection")
            .setPositiveButton("Exit", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) { 
                    finish();
                    System.exit(0);
                }
            })
            .setNegativeButton("Retry", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) { 
                    Intent i = getBaseContext().getPackageManager()
                            .getLaunchIntentForPackage( getBaseContext().getPackageName() );
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            })

            .setIcon(R.drawable.ic_launcher)
            .show();


        }


        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if(url.startsWith("setup:"))
                {
                    Intent settupx = new Intent(MainActivity.this, settup.class);
                    startActivity(settupx); 
                }
                if (url.startsWith("tel:")) { 
                    Intent intent = new Intent(Intent.ACTION_DIAL,
                            Uri.parse(url)); 
                    startActivity(intent); 
                }else if(url.startsWith("http:") || url.startsWith("https:")) {

                    view.loadUrl(url);

                }

                return true;



            }



        });










        mTitle = "Buy Me";
        getActionBar().setTitle(mTitle);

        // Getting reference to the DrawerLayout
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        mDrawerList = (ListView) findViewById(R.id.drawer_list);

        // Getting reference to the ActionBarDrawerToggle
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, R.string.drawer_open,
                R.string.drawer_close) {

            /** Called when drawer is closed */
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu();

            }

            /** Called when a drawer is opened */
            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle("Meniu");
                invalidateOptionsMenu();
            }

        };

        // Setting DrawerToggle on DrawerLayout
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        // Creating an ArrayAdapter to add items to the listview mDrawerList
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), 
                R.layout.drawer_list_item, getResources().getStringArray(R.array.menus));


        // Setting the adapter on mDrawerList

        mDrawerList.setAdapter(adapter);


        // Enabling Home button
        getActionBar().setHomeButtonEnabled(true);

        // Enabling Up navigation
        getActionBar().setDisplayHomeAsUpEnabled(true);

        // Setting item click listener for the listview mDrawerList
        mDrawerList.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                // Getting an array of rivers
                String[] menuItems = getResources().getStringArray(R.array.menus);

                // Currently selected river
                mTitle = menuItems[position];

                // Creating a fragment object
                WebViewFragment rFragment = new WebViewFragment();

                // Passing selected item information to fragment
                Bundle data = new Bundle();
                data.putInt("position", position);
                data.putString("url", getUrl(position));
                rFragment.setArguments(data);


                // Getting reference to the FragmentManager
                FragmentManager fragmentManager = getFragmentManager();

                // Creating a fragment transaction
                FragmentTransaction ft = fragmentManager.beginTransaction();

                // Adding a fragment to the fragment transaction
                ft.replace(R.id.content_frame, rFragment);

                // Committing the transaction
                ft.commit();

                // Closing the drawer
                mDrawerLayout.closeDrawer(mDrawerList);

            }
        });
    }


    public static boolean isNetworkAvailable(Context context) 
    {
        return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();

         inflater.inflate(R.menu.main_activity_actions, menu);
        return super.onCreateOptionsMenu(menu);



    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.action_settings:
            Intent settupx = new Intent(MainActivity.this, settup.class);
            startActivity(settupx);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    public static void trimCache(Context context) {
        try {
            File dir = context.getCacheDir();
            if (dir != null && dir.isDirectory()) {
                deleteDir(dir);

            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }

        // <uses-permission
        // android:name="android.permission.CLEAR_APP_CACHE"></uses-permission>
        // The directory is now empty so delete it

        return dir.delete();
    }



    @Override
    public boolean onKeyDown(final int keyCode, final KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onDestroy() {
        // closing Entire Application
        android.os.Process.killProcess(android.os.Process.myPid());
        Editor editor = getSharedPreferences("clear_cache", Context.MODE_PRIVATE).edit();
        editor.clear();
        editor.commit();
        trimCache(this);
        super.onDestroy();
    }


    @Override
    protected void onResume() {
        super.onResume();
        CookieSyncManager.getInstance().stopSync();
}
@Override
protected void onPause() {
    super.onPause();
    CookieSyncManager.getInstance().sync();
}


protected String getUrl(int position) {
    switch (position) {
    case 0:
        return "http://www.muvieplus.com/ab/olxx/register.php";
    case 1:
        return "http://www.muvieplus.com/ab/olxx/addAnunt.php";
    case 2:
        return "http://www.muvieplus.com/ab/olxx/register.php";
    case 3:
        Intent settupx = new Intent(MainActivity.this, settup.class);
        startActivity(settupx); 
    case 4:
        return "http://javatechig.com/category/sencha-touch/";
    case 5:
        return "http://javatechig.com/category/phonegap/";
    case 6:
        return "http://javatechig.com/category/java/";
    default:
        return "http://javatechig.com";
    }
}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    mDrawerToggle.syncState();
}



/** Called whenever we call invalidateOptionsMenu() */
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    // If the drawer is open, hide action items related to the content view
    boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);

    menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
    return super.onPrepareOptionsMenu(menu);
}

}

共有1个答案

淳于涛
2023-03-14

完成这个和这个教程。

 类似资料:
  • 我是android新手,我将设计这种对我来说很复杂的布局。这是主_活动的代码。xml文件: 基本上,我的主要活动中有一个导航抽屉和3个选项卡。这是一张照片: 一切按我的意愿进行,我很高兴。 当我点击导航抽屉项目时,我开始了一个新的意图来打开一个新的活动,这很好,但抽屉当然会消失(因为新活动没有抽屉)。我想把抽屉一直放在屏幕上。 为了把抽屉放在屏幕上,我想我可以把上面XML的TabLayout作为一

  • 本文向大家介绍Android组件之DrawerLayout实现抽屉菜单,包括了Android组件之DrawerLayout实现抽屉菜单的使用技巧和注意事项,需要的朋友参考一下 DrawerLayout组件同样是V4包中的组件,也是直接继承于ViewGroup类,所以这个类也是一个容器类。 抽屉菜单的摆放和布局通过android:layout_gravity属性来控制,可选值为left、right或

  • 我只想创建一个导航抽屉活动。当我右击应用程序时

  • 我在我的应用程序中以稍微不同的方式实现了抽屉菜单。但是抽屉不能顺利地打开或关闭。它在两者之间滞后。在谷歌应用程序中,抽屉菜单是如此流畅。我是如何实现的?这个问题已经在这里问过了,但它没有满足我的需求。请帮助! XML Java语言

  • 这是点击事件。 这是xml 结果将显示在片段中,但抽屉菜单仍然显示。我该怎么做才能关闭它?任何人都给我建议,如何解决这个问题,任何帮助非常感谢。谢谢你。

  • 问题内容: 我有一个导航图,该导航图将此片段用作主活动XML中的主页。 我有一个带有菜单的Drawer布局,单击导航抽屉按钮时,我无法设法使导航正常工作(它可以从主要片段工作,但是当我单击Drawer按钮时,不能工作),如果我使用的是旧方法使用:对导航抽屉编程,我的navcontroller丢失了!!我得到类似的错误 navcontroller无法识别目标片段,因为即使不是这种情况,控制器也会看到