首页 \ 问答 \ 如何在片段中实现按钮SetOnClickListener?(How to implement button SetOnClickListener in a fragment?)

如何在片段中实现按钮SetOnClickListener?(How to implement button SetOnClickListener in a fragment?)

我正在做一个小项目,我想使用滑块菜单。 长话短说我碰巧在某个网站上使用抽屉找到滑块菜单的源代码,它在我的设备上运行良好。 但是我有点困惑将我之前的活动迁移到这个滑块菜单中,因为它们对listView上的每个单独的项使用片段。

为了简单起见,我想迁移一个能够执行Ping功能的活动。 它的xml文件包含一个EditText,一个Button和一个用于显示输出的TextView。

现在,我确实设法“成功”将该活动迁移到此片段中。 抽屉运行良好,但我卡住了,因为我点击ping按钮后应用程序始终强制关闭。

PS:我还没有更改课程名称,原谅我

以下是我的代码:

这是我最初的Ping活动:

package my.jlm;

import java.io.IOException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class Ping extends Activity {
    EditText edit;
    TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ping);
    edit = (EditText)findViewById(R.id.editText1);
    edit.setText("192.168.1.1");
    text = (TextView)findViewById(R.id.textView1);
    Button button = (Button)findViewById(R.id.button1);
    button.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub

    Editable host = edit.getText();
    try {
    String pingCmd = "ping -c 5 " + host;
    String pingResult = "";
    Runtime r = Runtime.getRuntime();
    Process p = r.exec(pingCmd);
    BufferedReader in = new BufferedReader(new
    InputStreamReader(p.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
    System.out.println(inputLine);
    text.setText(inputLine + "\n\n");
    pingResult += inputLine;
    text.setText(pingResult);
    }
    in.close();
    }//try
    catch (IOException e) {
    System.out.println(e);
    }


    }
    });
    }}

这个FindPeopleFragment.java(这应该是PingFragment.java)。 我认为这是一次成功的尝试,因为日食没有显示任何红色标记,但如果我错了请指正。

package info.androidhive.slidingmenu;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class FindPeopleFragment extends Fragment 
        implements OnClickListener
{
        EditText edit;
        TextView text;
        Button button;





    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.activity_ping, container, false);


        EditText edit = (EditText) rootView.findViewById(R.id.editText1);
        edit.setText("192.168.1.1");
        text = (TextView) rootView.findViewById(R.id.textView1);
        button = (Button)rootView.findViewById(R.id.button1);
        button.setOnClickListener(onClickListener);





        return rootView;
    }

    @Override
    public void onClick(View v) {
        Editable host = edit.getText();
        try {
        String pingCmd = "ping -c 5 " + host;
        String pingResult = "";
        Runtime r = Runtime.getRuntime();
        Process p = r.exec(pingCmd);
        BufferedReader in = new BufferedReader(new
        InputStreamReader(p.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
        System.out.println(inputLine);
        text.setText(inputLine + "\n\n");
        pingResult += inputLine;
        text.setText(pingResult);
        }
        in.close();
        }//try
        catch (IOException e) {
        System.out.println(e);
        }

    }

};;

最后这是我上面项目的清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="info.androidhive.slidingmenu"
    android:versionCode="1"
    android:versionName="1.0" >

    <permission
        android:name="my.jlm.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="museumjakarta.source.permission.MAPS_RECEIVE"/>    
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>


      <uses-permission android:name="android.permission.CALL_PHONE" />
      <uses-permission android:name="android.permission.READ_PHONE_STATE" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="info.androidhive.slidingmenu.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>




    </application>

</manifest>

这是我的LogCat错误日志:

03-15 09:07:41.160: E/AndroidRuntime(1267): FATAL EXCEPTION: main
03-15 09:07:41.160: E/AndroidRuntime(1267): Process: info.androidhive.slidingmenu, PID: 1267
03-15 09:07:41.160: E/AndroidRuntime(1267): java.lang.NullPointerException
03-15 09:07:41.160: E/AndroidRuntime(1267):     at info.androidhive.slidingmenu.FindPeopleFragment.onClick(FindPeopleFragment.java:53)
03-15 09:07:41.160: E/AndroidRuntime(1267):     at android.view.View.performClick(View.java:4424)
03-15 09:07:41.160: E/AndroidRuntime(1267):     at android.view.View$PerformClick.run(View.java:18383)
03-15 09:07:41.160: E/AndroidRuntime(1267):     at android.os.Handler.handleCallback(Handler.java:733)
03-15 09:07:41.160: E/AndroidRuntime(1267):     at android.os.Handler.dispatchMessage(Handler.java:95)
03-15 09:07:41.160: E/AndroidRuntime(1267):     at android.os.Looper.loop(Looper.java:137)
03-15 09:07:41.160: E/AndroidRuntime(1267):     at android.app.ActivityThread.main(ActivityThread.java:4998)
03-15 09:07:41.160: E/AndroidRuntime(1267):     at java.lang.reflect.Method.invokeNative(Native Method)
03-15 09:07:41.160: E/AndroidRuntime(1267):     at java.lang.reflect.Method.invoke(Method.java:515)
03-15 09:07:41.160: E/AndroidRuntime(1267):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
03-15 09:07:41.160: E/AndroidRuntime(1267):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
03-15 09:07:41.160: E/AndroidRuntime(1267):     at dalvik.system.NativeStart.main(Native Method)

这里简化的就是我所经历的:在我从Drawer ListView中单击后会显示Ping xml页面,但是当我单击其中的Ping按钮时,应用程序崩溃,导致上面的错误日志。 帮我解决这个问题,非常感谢你。

PS:我正在使用eclipse adt,因为我不能在我的AMD处理器上运行AS。

编辑:认为它可能会有所帮助,我将为此片段发布mainActivity.java:

package info.androidhive.slidingmenu;

import info.androidhive.slidingmenu.adapter.NavDrawerListAdapter;
import info.androidhive.slidingmenu.model.NavDrawerItem;

import java.util.ArrayList;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

public class MainActivity extends Activity {
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    // nav drawer title
    private CharSequence mDrawerTitle;

    // used to store app title
    private CharSequence mTitle;

    // slide menu items
    private String[] navMenuTitles;
    private TypedArray navMenuIcons;

    private ArrayList<NavDrawerItem> navDrawerItems;
    private NavDrawerListAdapter adapter;

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

        mTitle = mDrawerTitle = getTitle();

        // load slide menu items
        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

        // nav drawer icons from resources
        navMenuIcons = getResources()
                .obtainTypedArray(R.array.nav_drawer_icons);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

        navDrawerItems = new ArrayList<NavDrawerItem>();

        // adding nav drawer items to array
        // Home
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
        // Find People
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
        // Photos
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
        // Communities, Will add a counter here
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
        // Pages
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
        // What's hot, We  will add a counter here
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));


        // Recycle the typed array
        navMenuIcons.recycle();

        mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

        // setting the nav drawer list adapter
        adapter = new NavDrawerListAdapter(getApplicationContext(),
                navDrawerItems);
        mDrawerList.setAdapter(adapter);

        // enabling action bar app icon and behaving it as toggle button
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, //nav menu toggle icon
                R.string.app_name, // nav drawer open - description for accessibility
                R.string.app_name // nav drawer close - description for accessibility
        ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                // calling onPrepareOptionsMenu() to show action bar icons
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                // calling onPrepareOptionsMenu() to hide action bar icons
                invalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            // on first time display view for first nav item
            displayView(0);
        }
    }

    /**
     * Slide menu item click listener
     * */
    private class SlideMenuClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            // display view for selected nav drawer item
            displayView(position);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // toggle nav drawer on selecting action bar app icon/title
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action bar actions click
        switch (item.getItemId()) {
        case R.id.action_settings:
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    /* *
     * Called when invalidateOptionsMenu() is triggered
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // if nav drawer is opened, hide the action items
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    /**
     * Diplaying fragment view for selected nav drawer list item
     * */
    private void displayView(int position) {
        // update the main content by replacing fragments
        Fragment fragment = null;
        switch (position) {
        case 0:
            fragment = new HomeFragment();
            break;
        case 1:
            fragment = new FindPeopleFragment();
            break;
        case 2:
            fragment = new PhotosFragment();
            break;
        case 3:
            fragment = new CommunityFragment();
            break;
        case 4:
            fragment = new PagesFragment();
            break;
        case 5:
            fragment = new WhatsHotFragment();
            break;

        default:
            break;
        }

        if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frame_container, fragment).commit();

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

}

I'm working on a small project and I want to use a Slider Menu. Long story short I happen to find a source code of a slider menu using drawer from some website and it works very well on my device. However I'm a little bit confused migrating my previous activity into this slider menu because they use fragment for each individual item on the listView.

To simple things up I want to migrate an activity that capable of do a Ping function. it's xml file consist of one EditText, a Button, and a TextView for showing the output.

Now I did manage to "successfully" migrating that activity into this fragment. The drawer runs well, but I got stuck because the app always force close after I click on the ping button.

PS: I haven't change the class name yet, pardon me

Below are my code:

this is my original Ping activity:

package my.jlm;

import java.io.IOException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class Ping extends Activity {
    EditText edit;
    TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ping);
    edit = (EditText)findViewById(R.id.editText1);
    edit.setText("192.168.1.1");
    text = (TextView)findViewById(R.id.textView1);
    Button button = (Button)findViewById(R.id.button1);
    button.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub

    Editable host = edit.getText();
    try {
    String pingCmd = "ping -c 5 " + host;
    String pingResult = "";
    Runtime r = Runtime.getRuntime();
    Process p = r.exec(pingCmd);
    BufferedReader in = new BufferedReader(new
    InputStreamReader(p.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
    System.out.println(inputLine);
    text.setText(inputLine + "\n\n");
    pingResult += inputLine;
    text.setText(pingResult);
    }
    in.close();
    }//try
    catch (IOException e) {
    System.out.println(e);
    }


    }
    });
    }}

this FindPeopleFragment.java (this should be the PingFragment.java). I thought this was a successful attempt because eclipse didn't show any red mark, but if Im wrong please correct me.

package info.androidhive.slidingmenu;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class FindPeopleFragment extends Fragment 
        implements OnClickListener
{
        EditText edit;
        TextView text;
        Button button;





    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.activity_ping, container, false);


        EditText edit = (EditText) rootView.findViewById(R.id.editText1);
        edit.setText("192.168.1.1");
        text = (TextView) rootView.findViewById(R.id.textView1);
        button = (Button)rootView.findViewById(R.id.button1);
        button.setOnClickListener(onClickListener);





        return rootView;
    }

    @Override
    public void onClick(View v) {
        Editable host = edit.getText();
        try {
        String pingCmd = "ping -c 5 " + host;
        String pingResult = "";
        Runtime r = Runtime.getRuntime();
        Process p = r.exec(pingCmd);
        BufferedReader in = new BufferedReader(new
        InputStreamReader(p.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
        System.out.println(inputLine);
        text.setText(inputLine + "\n\n");
        pingResult += inputLine;
        text.setText(pingResult);
        }
        in.close();
        }//try
        catch (IOException e) {
        System.out.println(e);
        }

    }

};;

and finally this is my Manifest for above project

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="info.androidhive.slidingmenu"
    android:versionCode="1"
    android:versionName="1.0" >

    <permission
        android:name="my.jlm.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="museumjakarta.source.permission.MAPS_RECEIVE"/>    
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>


      <uses-permission android:name="android.permission.CALL_PHONE" />
      <uses-permission android:name="android.permission.READ_PHONE_STATE" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="info.androidhive.slidingmenu.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>




    </application>

</manifest>

and this is my LogCat error log:

03-15 09:07:41.160: E/AndroidRuntime(1267): FATAL EXCEPTION: main
03-15 09:07:41.160: E/AndroidRuntime(1267): Process: info.androidhive.slidingmenu, PID: 1267
03-15 09:07:41.160: E/AndroidRuntime(1267): java.lang.NullPointerException
03-15 09:07:41.160: E/AndroidRuntime(1267):     at info.androidhive.slidingmenu.FindPeopleFragment.onClick(FindPeopleFragment.java:53)
03-15 09:07:41.160: E/AndroidRuntime(1267):     at android.view.View.performClick(View.java:4424)
03-15 09:07:41.160: E/AndroidRuntime(1267):     at android.view.View$PerformClick.run(View.java:18383)
03-15 09:07:41.160: E/AndroidRuntime(1267):     at android.os.Handler.handleCallback(Handler.java:733)
03-15 09:07:41.160: E/AndroidRuntime(1267):     at android.os.Handler.dispatchMessage(Handler.java:95)
03-15 09:07:41.160: E/AndroidRuntime(1267):     at android.os.Looper.loop(Looper.java:137)
03-15 09:07:41.160: E/AndroidRuntime(1267):     at android.app.ActivityThread.main(ActivityThread.java:4998)
03-15 09:07:41.160: E/AndroidRuntime(1267):     at java.lang.reflect.Method.invokeNative(Native Method)
03-15 09:07:41.160: E/AndroidRuntime(1267):     at java.lang.reflect.Method.invoke(Method.java:515)
03-15 09:07:41.160: E/AndroidRuntime(1267):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
03-15 09:07:41.160: E/AndroidRuntime(1267):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
03-15 09:07:41.160: E/AndroidRuntime(1267):     at dalvik.system.NativeStart.main(Native Method)

to simplify here is what I experienced: the Ping xml page shows up after I click from the Drawer ListView, however when I click the Ping Button inside it, the application crashed, resulting the above error log. Help me resolve this problem and thank you very much.

PS: I'm using eclipse adt because I can't run AS on my AMD processor.

edit: thought it may help, i will post the mainActivity.java for this fragment:

package info.androidhive.slidingmenu;

import info.androidhive.slidingmenu.adapter.NavDrawerListAdapter;
import info.androidhive.slidingmenu.model.NavDrawerItem;

import java.util.ArrayList;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

public class MainActivity extends Activity {
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    // nav drawer title
    private CharSequence mDrawerTitle;

    // used to store app title
    private CharSequence mTitle;

    // slide menu items
    private String[] navMenuTitles;
    private TypedArray navMenuIcons;

    private ArrayList<NavDrawerItem> navDrawerItems;
    private NavDrawerListAdapter adapter;

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

        mTitle = mDrawerTitle = getTitle();

        // load slide menu items
        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

        // nav drawer icons from resources
        navMenuIcons = getResources()
                .obtainTypedArray(R.array.nav_drawer_icons);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

        navDrawerItems = new ArrayList<NavDrawerItem>();

        // adding nav drawer items to array
        // Home
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
        // Find People
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
        // Photos
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
        // Communities, Will add a counter here
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
        // Pages
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
        // What's hot, We  will add a counter here
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));


        // Recycle the typed array
        navMenuIcons.recycle();

        mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

        // setting the nav drawer list adapter
        adapter = new NavDrawerListAdapter(getApplicationContext(),
                navDrawerItems);
        mDrawerList.setAdapter(adapter);

        // enabling action bar app icon and behaving it as toggle button
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, //nav menu toggle icon
                R.string.app_name, // nav drawer open - description for accessibility
                R.string.app_name // nav drawer close - description for accessibility
        ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                // calling onPrepareOptionsMenu() to show action bar icons
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                // calling onPrepareOptionsMenu() to hide action bar icons
                invalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            // on first time display view for first nav item
            displayView(0);
        }
    }

    /**
     * Slide menu item click listener
     * */
    private class SlideMenuClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            // display view for selected nav drawer item
            displayView(position);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // toggle nav drawer on selecting action bar app icon/title
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action bar actions click
        switch (item.getItemId()) {
        case R.id.action_settings:
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    /* *
     * Called when invalidateOptionsMenu() is triggered
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // if nav drawer is opened, hide the action items
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    /**
     * Diplaying fragment view for selected nav drawer list item
     * */
    private void displayView(int position) {
        // update the main content by replacing fragments
        Fragment fragment = null;
        switch (position) {
        case 0:
            fragment = new HomeFragment();
            break;
        case 1:
            fragment = new FindPeopleFragment();
            break;
        case 2:
            fragment = new PhotosFragment();
            break;
        case 3:
            fragment = new CommunityFragment();
            break;
        case 4:
            fragment = new PagesFragment();
            break;
        case 5:
            fragment = new WhatsHotFragment();
            break;

        default:
            break;
        }

        if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frame_container, fragment).commit();

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

}

原文:https://stackoverflow.com/questions/29063082
更新时间:2022-08-15 20:08

最满意答案

该文件在网络负载方面不会变小。 如果你无论如何都控制了源代码(php),那么为什么不在没有javascript开销的情况下完全剥离它呢?

试试http://php.net/manual/en/domdocument.loadhtml.php

[编辑]如果您想通过id找到特定的elemt,请使用方法http://php.net/manual/en/domdocument.getelementbyid.php


The below code solved it for me, it overwrites the content completely

$dir = "path";
$line = 'texttochange';
$line2 = 'towhatever';
$contents = file_get_contents($dir);
$contents = str_replace($line, $line2, $contents);
file_put_contents($dir, $contents);

相关问答

更多
  • 使用cURL 。 该函数是file_get_contents的替代方法。 function url_get_contents ($Url) { if (!function_exists('curl_init')){ die('CURL is not installed!'); } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $Url); curl_setopt($ch, CURLOPT_RETUR ...
  • Mike的答案将允许您覆盖文件的内容,但不能以您想象的方式以线条导向的方式进行覆盖。 您无法调整文件的内部内容,以便在插入内容时,以后会推送现有的后续数据,如果删除内容,现有的后续数据将被提取到删除点之后。 您有两个基本操作可用:您可以截断一定长度的文件,可能为0,丢弃该点之后的任何旧数据。 您可以在某个位置写入数据。 如果该位置已有数据,则会被覆盖(即丢失)。 如果您要写入的字节范围超出文件末尾,则会扩展该文件。 但是,任何既没有截断也没有覆盖的旧数据仍然存在。 在任何情况下都不会移动。 因此,如果您想要 ...
  • 如果URL正确,您应该已经获得纯XML。 如果遇到问题,可能是该网址希望您登录或者有类似的东西。 使用var_dump($ str),然后查看该页面上的源代码,以查看返回的内容。 无论哪种方式,从XML获取任何链接内容都没有什么神奇的方法。 所有你会得到的是XML本身,并需要更多的PHP代码来处理和获取它的任何链接/图像/数据。 You should already be getting the pure XML if the URL is correct. If you're having trouble ...
  • 该文件在网络负载方面不会变小。 如果你无论如何都控制了源代码(php),那么为什么不在没有javascript开销的情况下完全剥离它呢? 试试http://php.net/manual/en/domdocument.loadhtml.php [编辑]如果您想通过id找到特定的elemt,请使用方法http://php.net/manual/en/domdocument.getelementbyid.php The below code solved it for me, it overwrites the ...
  • 您必须以追加模式打开文件: fileobject = open('completed.txt', 'a') 用于打开文件的Python文档 “在处理文件对象时使用with关键字是一个好习惯。这样做的好处是文件在套件完成后正确关闭,即使在途中引发了异常。它也比编写等效的试验要短得多。 - 最终阻止。“ 来自Python文档 with open('completed.txt', 'a') as fileobject: fileobject.write(date + ' \n') You have t ...
  • 使用"r+"模式打开文件而不是"a+" (二进制的b是可选的,在POSIX系统上基本上不相关): - #include #include int main(void){ FILE *fp = fopen("file.txt", "r+"); fseek(fp, 10, SEEK_SET); fwrite("ABCD", 1, 4, fp); fclose(fp); return 0; } Use "r+" mode to ...
  • Would suggest to use either xcopy or robocopy for Overwriting folders Xcopy /E /Y会覆盖文件夹, 请找更多选项Xcopy /? 请注意,我提到这个选项只是为了覆盖而不是移动文件夹。 Would suggest to use either xcopy or robocopy for Overwriting folders Xcopy /E /Y would Overwrite folder , please find More ...
  • 我建议在循环中设置你的time_limit。 设置时间限制将在给定的时间内“延长”超时; '.$string.''; // extend the time-limit with this amount of tim ...
  • 当您打开文件时,您可以通过构造函数的第二个参数设置数据应该如何写入文件的模式 std::wfstream cSrcFileOutput(m_cstrFile, std::wfstream::out | std::wfstream::trunc); 其中std :: wfstream :: trunc意味着覆盖现有内容(有关构造函数文档,请参阅std :: basic_fstream :: basic_fstream )。 When you open the file, you set the mode f ...
  • 您正在开发Web应用程序,并且将从Web服务器提供文件。 因此,尝试相对于应用程序的上下文而不是使用绝对路径来创建路径。 尝试使用ServletContext#getRealPath()方法,该方法返回包含给定虚拟路径的实际路径的String。 将output.txt文件放在项目的war / webapp文件夹中,并尝试下面的代码: String filePath = request.getServletContext().getRealPath("output.txt"); 注意:始终尽量避免使用Scr ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)