0

我有一个包含 3 个片段的 ViewPager 的活动。每个片段都包含一个列表视图,我希望在单击列表项时启动一个新活动。

我无法从 onItemClickListener 运行 startActivity() 方法。帮助!

BTListDevice.java

package com.example.pager;

import java.util.Set;
import android.support.v4.app.Fragment;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class BTListDevice extends FragmentActivity {

    // Fragments
    AppSectionsPagerAdapter mAppSectionsPagerAdapter;
    ViewPager mViewPager;

    // Debugging
    private static final String TAG = "BluetoothChat";
    private static final boolean D = true;

    // Message types sent from the BluetoothChatService Handler
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;

    // Key names received from the BluetoothChatService Handler
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";

    // Intent request codes
    private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
    private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;    

    // Return Intent extra
    public static String DEVICE_DET = "dev";
    private static final int REQUEST_ENABLE_BT = 7;

    // Member fields
    private static BluetoothAdapter mBtAdapter;
    private static DevicesCursor devicesAdapter; 
    private static ChatDBHelper dbHelper;
    private static ListView pairedListView;
    private ListView newDevicesListView;
    private static ListView homeList;
    private static HomeListAdapter iAdap;

    boolean buttonState;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //Get Default Adapter for the device
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        dbHelper = new ChatDBHelper(this);

        if (mBtAdapter.isEnabled())
            buttonState=true;
        else
            buttonState=false;
        invalidateOptionsMenu();

        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.activity_navigator);

        // Create the adapter that will return a fragment for each of the three primary sections
        // of the app.
        mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());        

        // Set up the ViewPager, attaching the adapter and setting up a listener for when the
        // user swipes between sections.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mAppSectionsPagerAdapter);
        mViewPager.setCurrentItem(1);        

        // Set result CANCELED in case the user backs out
        setResult(Activity.RESULT_CANCELED);             


    }

    @Override
    protected void onResume() { 
        super.onResume();
        if (mBtAdapter.isEnabled())
            buttonState=true;
        else
            buttonState=false;
        invalidateOptionsMenu();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // Make sure we're not doing discovery anymore
        if (mBtAdapter != null) {
            mBtAdapter.cancelDiscovery();
        }

        // Unregister broadcast listeners
        this.unregisterReceiver(mReceiver);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.home_screen_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        switch(item.getItemId()) {
            case R.id.menu_BT :
                {
                    if (!mBtAdapter.isEnabled()) {          
                        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                        //Toast.makeText(getApplicationContext(), "Enabling Bluetooth..", Toast.LENGTH_SHORT).show();                                   
                    }                                                                           
                    else {
                        if (mBtAdapter.isEnabled()) {
                            mBtAdapter.disable();
                        buttonState=false;
                        invalidateOptionsMenu();
                            //Toast.makeText(getApplicationContext(), "Disabling Bluetooth..", Toast.LENGTH_SHORT).show();
                        }                               
                    }
                }
                return true;
            default :
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        MenuItem BT = menu.findItem(R.id.menu_BT);
        if(buttonState)
        {
            BT.setIcon(R.drawable.bt_on);
            return true;
        }
        else
            BT.setIcon(R.drawable.bt_off);
        return super.onPrepareOptionsMenu(menu);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub

        switch(requestCode)
        {
        case REQUEST_ENABLE_BT : {      
            if(resultCode==RESULT_OK)
            {               
                buttonState=true;
                invalidateOptionsMenu();

                // Get a set of currently paired devices
                Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();

                String text = String.valueOf(pairedDevices.size());
                Toast.makeText(getApplicationContext(),text, Toast.LENGTH_SHORT).show();

                if (pairedDevices.size() > 0)
                {            
                    dbHelper.DTdelAllData();                    
                    for (BluetoothDevice device : pairedDevices) 
                    {
                        dbHelper.DTinsertData(device.getAddress(), device.getName());
                    }                    
                }
            }
            else
            {
                buttonState=false;
                invalidateOptionsMenu();
            }
        }
        break;
        }
    }

    public void searchForDevices(View v)
    {
        if (mBtAdapter == null) {
               Toast.makeText(getApplicationContext(), "Device not supported!", Toast.LENGTH_LONG).show();
               return;
             }
             else
             {
                if (!mBtAdapter.isEnabled()) {
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                    //Toast.makeText(getApplicationContext(), "Enabling Bluetooth..", Toast.LENGTH_LONG).show();                            
                }
                else
                {
                    doDiscovery();
                    v.setVisibility(View.GONE);
                }
             }                          
    }

    private void doDiscovery() {
        //if (D) Log.d(TAG, "doDiscovery()");

        // Indicate scanning in the title
        setProgressBarIndeterminateVisibility(true);
        setTitle("Scanning");        

        // If we're already discovering, stop it
        if (mBtAdapter.isDiscovering()) {
            mBtAdapter.cancelDiscovery();
        }

        // Request discover from BluetoothAdapter
        mBtAdapter.startDiscovery();
    }

    // The on-click listener for all devices in the ListViews
    static OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
        @Override        
        public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
            // Cancel discovery because it's costly and we're about to connect
            mBtAdapter.cancelDiscovery();

            Cursor c = dbHelper.DTgetAllData();            
            c.moveToPosition(arg2);
            String device = c.getString(0);

            // Create the result Intent and include the MAC address
            Intent intent = new Intent(BTListDevice.this,ChatActivity.class);
            intent.putExtra(DEVICE_DET, device);            

            // Set result and finish this Activity
            BTListDevice.this.startActivity(intent);
        }
    };


    public class AppSectionsPagerAdapter extends FragmentPagerAdapter {

        Fragment frag;

            public AppSectionsPagerAdapter(FragmentManager fm) {
                super(fm);
            }

            @Override
            public Fragment getItem(int i) {
                switch (i) {
                    case 0 :
                        frag = new PairedDevicesFragment();
                        break;

                    case 2 :
                        frag = new NewDevicesFragment();
                        break;

                    case 1 :
                        frag = new HomeScreenFragment();
                        break;

                    default :
                        frag = new HomeScreenFragment();                                                
                }
                return frag;
            }

            @Override
            public int getCount() {
                return 3;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                String title = null;
                switch(position)
                {
                    case 0 : title = "Paired Devices";
                            break;
                    case 1 : title = "Chats";
                            break;
                    case 2 : title = "New Devices";
                            break;
                }
                return (CharSequence)title;
            }
        }

    public static class PairedDevicesFragment extends Fragment {        

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.paired_devices, container, false);

            // Find and set up the ListView for paired devices
            pairedListView = (ListView) rootView.findViewById(R.id.paired_devices);                
            pairedListView.setOnItemClickListener(mDeviceClickListener);

            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    devicesAdapter = new DevicesCursor(getActivity().getApplicationContext(), dbHelper.DTgetAllData());
                    pairedListView.setAdapter(devicesAdapter);
                }
            });

            return rootView;            
        }   
    }

    public static class NewDevicesFragment extends Fragment {



        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.new_devices, container, false);

            // Find and set up the ListView for paired devices
            pairedListView = (ListView) rootView.findViewById(R.id.new_devices);                
            pairedListView.setOnItemClickListener(BTListDevice.mDeviceClickListener);

            return rootView;            
        }               
    }

    public static class HomeScreenFragment extends Fragment {

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.home_screen, container, false);           

            homeList = (ListView)rootView.findViewById(android.R.id.list);  
            Cursor cur =  dbHelper.CTgetChatDevices();
            cur.moveToFirst();

            if(cur.getCount()>0)
            {
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        iAdap = new HomeListAdapter(getActivity().getApplicationContext());
                        homeList.setAdapter(iAdap);
                    }
                });
            }
            else
            {
                TextView empty = (TextView)rootView.findViewById(android.R.id.empty);
                empty.setText("There is No Cheese!");
                empty.setVisibility(View.VISIBLE);
                homeList.setVisibility(View.GONE);
            }

            return rootView;
        }       
    }


}

编辑:当我尝试调用 startActivity() 时,我在 onItemClickListener 中收到此错误。

Cannot make a static reference to the non-static method startActivity(Intent) from the type Activity.
4

4 回答 4

1

试试这个,

而不是这样做, getActivity().startActivity(intent);

试试这个,

 BTListDevice.this.startActivity(intent);
于 2013-08-06T11:06:04.173 回答
1

只需更改每个片段的代码

 public static class PairedDevicesFragment extends Fragment {        

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.paired_devices, container, false);

        // Find and set up the ListView for paired devices
        pairedListView = (ListView) rootView.findViewById(R.id.paired_devices);                
        pairedListView.setOnItemClickListener(mDeviceClickListener);

        new Handler().post(new Runnable() {
            @Override
            public void run() {
                devicesAdapter = new DevicesCursor(getActivity().getApplicationContext(), dbHelper.DTgetAllData());
                pairedListView.setAdapter(devicesAdapter);
            }
        });

       pairedListView .setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            Cursor c = dbHelper.DTgetAllData();            
        c.moveToPosition(arg2);
        String device = c.getString(0);

        // Create the result Intent and include the MAC address
        Intent intent = new Intent(getActivity(),ChatActivity.class);
        intent.putExtra(DEVICE_DET, device);            

        // Set result and finish this Activity
        getActivity().startActivity(intent);

        }
    });

        return rootView;            
    }   
}
于 2013-08-06T11:08:47.457 回答
0

更改 onItemClick 代码如下

static OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
    @Override        
    public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
        // Cancel discovery because it's costly and we're about to connect
        mBtAdapter.cancelDiscovery();

        Cursor c = dbHelper.DTgetAllData();            
        c.moveToPosition(arg2);
        String device = c.getString(0);

        // Create the result Intent and include the MAC address
        Intent intent = new Intent(getActivity(),ChatActivity.class);
        intent.putExtra(DEVICE_DET, device);            

        // Set result and finish this Activity
        getActivity().startActivity(intent);
    }
};
于 2013-08-06T10:50:15.777 回答
0

试试这段代码

    // Create the result Intent and include the MAC address
    Intent intent = new Intent(getActivity(), ChatActivity.class);
    intent.putExtra(DEVICE_DET, device);            

    // Set result and finish this Activity
    startActivity(intent);
于 2013-08-06T10:50:39.173 回答