是否有一个不同的xml视图"扩展Fragment"?

时间:2015-05-07 20:11:08

标签: android xml fragment

我试图获取我的类XML屏幕,但没有成功, 到目前为止,我能够创建活动,并使用startActivity(activity.class) 但现在有一个问题。

在我的应用程序的主Java文件中,我调用FTDI类:

public void onFTDIClick(View view){
        startActivity(new Intent(this,FTDI.class));
    }

FTDI课程:

    package com.application.i;


import java.util.ArrayList;

import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;


import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.ftdi.j2xx.D2xxManager;
import com.ftdi.j2xx.FT_Device;




public class FTDI extends Fragment{


    static Context DeviceUARTContext;
    D2xxManager ftdid2xx;
    FT_Device ftDev = null;
    int DevCount = -1;
    int currentIndex = -1;
    int openIndex = 0;

    /*graphical objects*/
    EditText readText;
    EditText writeText;
    Spinner baudSpinner;;
    Spinner stopSpinner;
    Spinner dataSpinner;
    Spinner paritySpinner;
    Spinner flowSpinner;
    Spinner portSpinner;
    ArrayAdapter<CharSequence> portAdapter;

    Button configButton;
    Button openButton;
    Button readEnButton;
    Button writeButton;
    static int iEnableReadFlag = 1;

    /*local variables*/
    int baudRate; /*baud rate*/
    byte stopBit; /*1:1stop bits, 2:2 stop bits*/
    byte dataBit; /*8:8bit, 7: 7bit*/
    byte parity;  /* 0: none, 1: odd, 2: even, 3: mark, 4: space*/
    byte flowControl; /*0:none, 1: flow control(CTS,RTS)*/
    int portNumber; /*port number*/
    ArrayList<CharSequence> portNumberList;


    public static final int readLength = 512;
    public int readcount = 0;
    public int iavailable = 0;
    byte[] readData;
    char[] readDataToText;
    public boolean bReadThreadGoing = false;
    public readThread read_thread;

    boolean uart_configured = false;

    // Empty Constructor
    public FTDI()
    {
    }


    /* Constructor */
    public FTDI(Context parentContext , D2xxManager ftdid2xxContext)
    {
        DeviceUARTContext = parentContext;
        ftdid2xx = ftdid2xxContext;
    }
     public int getShownIndex() {
            return getArguments().getInt("index", 5);
        }
       @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
            if (container == null) {
                return null;
            }

            super.onCreate(savedInstanceState);

            View view = inflater.inflate(R.layout.ftdisub, container, false);

            readData = new byte[readLength];
            readDataToText = new char[readLength];

            readText = (EditText) view.findViewById(R.id.ReadValues);
            readText.setInputType(0);  

            /* by default it is 9600 */
            baudRate = 9600;

            /* default is stop bit 1 */
            stopBit = 1;

            /* default data bit is 8 bit */
            dataBit = 8;

            /* default is none */
            parity = 0;

            /* default flow control is is none */
            flowControl = 0;

            portNumber = 1; 


            return view;
       }


       public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);

        }

        @Override
        public void onStart() {
            super.onStart();
            createDeviceList();
        }

        @Override
        public void onStop()
        {
            disconnectFunction();
            super.onStop();
        }

        public void notifyUSBDeviceAttach()
        {
            createDeviceList();
        }

        public void notifyUSBDeviceDetach()
        {
            disconnectFunction();
        }   
        public void createDeviceList()
        {
            int tempDevCount = ftdid2xx.createDeviceInfoList(DeviceUARTContext);

            if (tempDevCount > 0)
            {
                if( DevCount != tempDevCount )
                {
                    DevCount = tempDevCount;
                updatePortNumberSelector();
                }
            }
            else
            {
                DevCount = -1;
                currentIndex = -1;
            }
        }

        public void disconnectFunction()
        {
            DevCount = -1;
            currentIndex = -1;
            bReadThreadGoing = false;
            try {
                Thread.sleep(50);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }

            if(ftDev != null)
            {
                synchronized(ftDev)
                {
                    if( true == ftDev.isOpen())
                    {
                        ftDev.close();
                    }
                }
            }
        }


        public void connectFunction()
        {
            int tmpProtNumber = openIndex + 1;

            if( currentIndex != openIndex )
            {
                if(null == ftDev)
                {
                    ftDev = ftdid2xx.openByIndex(DeviceUARTContext, openIndex);
                }
                else
                {
                    synchronized(ftDev)
                    {
                        ftDev = ftdid2xx.openByIndex(DeviceUARTContext, openIndex);
                    }
                }
                uart_configured = false;
            }
            else
            {
                Toast.makeText(DeviceUARTContext,"Device port " + tmpProtNumber + " is already opened",Toast.LENGTH_LONG).show();
                return;
            }

            if(ftDev == null)
            {
                Toast.makeText(DeviceUARTContext,"open device port("+tmpProtNumber+") NG, ftDev == null", Toast.LENGTH_LONG).show();
                return;
            }

            if (true == ftDev.isOpen())
            {
                currentIndex = openIndex;
                Toast.makeText(DeviceUARTContext, "open device port(" + tmpProtNumber + ") OK", Toast.LENGTH_SHORT).show();

                if(false == bReadThreadGoing)
                {
                    read_thread = new readThread(handler);
                    read_thread.start();
                    bReadThreadGoing = true;
                }
            }
            else 
            {           
                Toast.makeText(DeviceUARTContext, "open device port(" + tmpProtNumber + ") NG", Toast.LENGTH_LONG).show();
                //Toast.makeText(DeviceUARTContext, "Need to get permission!", Toast.LENGTH_SHORT).show();          
            }
        }


        public void updatePortNumberSelector()
        {

        }




        public void SetConfig(int baud, byte dataBits, byte stopBits, byte parity, byte flowControl)
         {
                if (ftDev.isOpen() == false) {
                    Log.e("j2xx", "SetConfig: device not open");
                    return;
                }

                // configure our port
                // reset to UART mode for 232 devices
                ftDev.setBitMode((byte) 0, D2xxManager.FT_BITMODE_RESET);

                ftDev.setBaudRate(baud);

                switch (dataBits) {
                case 7:
                    dataBits = D2xxManager.FT_DATA_BITS_7;
                    break;
                case 8:
                    dataBits = D2xxManager.FT_DATA_BITS_8;
                    break;
                default:
                    dataBits = D2xxManager.FT_DATA_BITS_8;
                    break;
                }

                switch (stopBits) {
                case 1:
                    stopBits = D2xxManager.FT_STOP_BITS_1;
                    break;
                case 2:
                    stopBits = D2xxManager.FT_STOP_BITS_2;
                    break;
                default:
                    stopBits = D2xxManager.FT_STOP_BITS_1;
                    break;
                }

                switch (parity) {
                case 0:
                    parity = D2xxManager.FT_PARITY_NONE;
                    break;
                case 1:
                    parity = D2xxManager.FT_PARITY_ODD;
                    break;
                case 2:
                    parity = D2xxManager.FT_PARITY_EVEN;
                    break;
                case 3:
                    parity = D2xxManager.FT_PARITY_MARK;
                    break;
                case 4:
                    parity = D2xxManager.FT_PARITY_SPACE;
                    break;
                default:
                    parity = D2xxManager.FT_PARITY_NONE;
                    break;
                }

                ftDev.setDataCharacteristics(dataBits, stopBits, parity);

                short flowCtrlSetting;
                switch (flowControl) {
                case 0:
                    flowCtrlSetting = D2xxManager.FT_FLOW_NONE;
                    break;
                case 1:
                    flowCtrlSetting = D2xxManager.FT_FLOW_RTS_CTS;
                    break;
                case 2:
                    flowCtrlSetting = D2xxManager.FT_FLOW_DTR_DSR;
                    break;
                case 3:
                    flowCtrlSetting = D2xxManager.FT_FLOW_XON_XOFF;
                    break;
                default:
                    flowCtrlSetting = D2xxManager.FT_FLOW_NONE;
                    break;
                }

                // TODO : flow ctrl: XOFF/XOM
                // TODO : flow ctrl: XOFF/XOM
                ftDev.setFlowControl(flowCtrlSetting, (byte) 0x0b, (byte) 0x0d);

                uart_configured = true;
                Toast.makeText(DeviceUARTContext, "Config done", Toast.LENGTH_SHORT).show();
            }
         public void EnableRead (){     
                iEnableReadFlag = (iEnableReadFlag + 1)%2;

                if(iEnableReadFlag == 1) {
                    ftDev.purge((byte) (D2xxManager.FT_PURGE_TX));
                    ftDev.restartInTask();
                    readEnButton.setText("Read Enabled");
                }
                else{
                    ftDev.stopInTask();
                    readEnButton.setText("Read Disabled");
                }
            }
         final Handler handler =  new Handler()
            {
                @Override
                public void handleMessage(Message msg)
                {
                    if(iavailable > 0)
                    {
                        readText.append(String.copyValueOf(readDataToText, 0, iavailable));
                    }
                }
            };
            private class readThread  extends Thread
            {
                Handler mHandler;

                readThread(Handler h){
                    mHandler = h;
                    this.setPriority(Thread.MIN_PRIORITY);
                }

                @Override
                public void run()
                {
                    int i;

                    while(true == bReadThreadGoing)
                    {
                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException e) {
                        }

                        synchronized(ftDev)
                        {
                            iavailable = ftDev.getQueueStatus();                
                            if (iavailable > 0) {

                                if(iavailable > readLength){
                                    iavailable = readLength;
                                }

                                ftDev.read(readData, iavailable);
                                for (i = 0; i < iavailable; i++) {
                                    readDataToText[i] = (char) readData[i];
                                }
                                Message msg = mHandler.obtainMessage();
                                mHandler.sendMessage(msg);
                            }
                        }
                    }
                }

            }



    @Override
    public void onResume() {
        super.onResume();
        DevCount = 0;
        createDeviceList();
        if(DevCount > 0)
        {
            connectFunction();
            SetConfig(baudRate, dataBit, stopBit, parity, flowControl);
        }       
    }
}

XML文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

     <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"

        android:id="@+id/PITCHING"
        android:textSize="15sp" />
  <TextView android:text = "Read Bytes" 
                android:textStyle="bold"
                android:gravity="center"
                android:id="@+id/ReadBytes"
                android:layout_height="fill_parent"
                android:layout_width="0dp"
                android:layout_weight="1"
                />

        <EditText
            android:id="@+id/ReadValues"
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:layout_margin="10dp"
            android:layout_weight="4"
            android:background="#708070"
            android:focusableInTouchMode="false"
            android:gravity="left|center_vertical"
            />



                    <Button android:id="@+id/readEnButton"
                    android:layout_height="fill_parent"
                    android:layout_width="fill_parent"
                    android:layout_margin="10dp"
                    android:gravity="center"
                    android:scaleType="centerInside"

                    android:layout_weight="1"
                    android:text="Read Enabled"
                    />              
</LinearLayout>

在清单文件中:

 <activity
            android:name=".FTDI"
            android:label="Reading Circuit Data"
            android:theme="@android:style/Theme.Holo" >
        </activity>

直到现在我才使用,在使用Frgment之前:

package com.application.i;


import android.app.Activity;
import android.os.Bundle;
public class FTDI extends Activity 
{
       public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ftdisub);

}
}   

当我按下主屏幕上的按钮时,它会卡住,孔应用程序完成错误。

编辑: 我的问题是我需要一个UI来检查这个类,然后把它作为Service,我知道如何Service它没有用户界面。 我将代码更改为activity,它看起来是:

package com.application.i;


import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.ftdi.j2xx.D2xxManager;
import com.ftdi.j2xx.FT_Device;




public class FTDI extends Activity{


    static Context DeviceUARTContext;
    D2xxManager ftdid2xx;
    FT_Device ftDev = null;
    int DevCount = -1;
    int currentIndex = -1;
    int openIndex = 0;

    /*graphical objects*/
    EditText readText;
    EditText writeText;
    Spinner baudSpinner;;
    Spinner stopSpinner;
    Spinner dataSpinner;
    Spinner paritySpinner;
    Spinner flowSpinner;
    Spinner portSpinner;
    ArrayAdapter<CharSequence> portAdapter;

    Button configButton;
    Button openButton;
    Button readEnButton;
    Button writeButton;
    static int iEnableReadFlag = 1;

    /*local variables*/
    int baudRate; /*baud rate*/
    byte stopBit; /*1:1stop bits, 2:2 stop bits*/
    byte dataBit; /*8:8bit, 7: 7bit*/
    byte parity;  /* 0: none, 1: odd, 2: even, 3: mark, 4: space*/
    byte flowControl; /*0:none, 1: flow control(CTS,RTS)*/
    int portNumber; /*port number*/
    ArrayList<CharSequence> portNumberList;


    public static final int readLength = 512;
    public int readcount = 0;
    public int iavailable = 0;
    byte[] readData;
    char[] readDataToText;
    public boolean bReadThreadGoing = false;
    public readThread read_thread;

    boolean uart_configured = false;

    // Empty Constructor
    public FTDI()
    {
    }


    /* Constructor */
    public FTDI(Context parentContext , D2xxManager ftdid2xxContext)
    {
        DeviceUARTContext = parentContext;
        ftdid2xx = ftdid2xxContext;
    }
//   public int getShownIndex() {
//          return getArguments().getInt("index", 5);
//      }
//     @Override
//      public View onCreateView(LayoutInflater inflater, ViewGroup container,
//          Bundle savedInstanceState) {
//          if (container == null) {
//              return null;
//          }
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ftdisub);



//          View view = inflater.inflate(R.layout.ftdisub, container, false);

            readData = new byte[readLength];
            readDataToText = new char[readLength];

            readText = (EditText) findViewById(R.id.ReadValues);
            readText.setInputType(0);  

            /* by default it is 9600 */
            baudRate = 9600;

            /* default is stop bit 1 */
            stopBit = 1;

            /* default data bit is 8 bit */
            dataBit = 8;

            /* default is none */
            parity = 0;

            /* default flow control is is none */
            flowControl = 0;

            portNumber = 1; 



       }


//     public void onActivityCreated(Bundle savedInstanceState) {
//          super.onActivityCreated(savedInstanceState);
//
//      }

        @Override
        public void onStart() {
            super.onStart();
            createDeviceList();
        }

        @Override
        public void onStop()
        {
            disconnectFunction();
            super.onStop();
        }

        public void notifyUSBDeviceAttach()
        {
            createDeviceList();
        }

        public void notifyUSBDeviceDetach()
        {
            disconnectFunction();
        }   
        public void createDeviceList()
        {
            int tempDevCount = ftdid2xx.createDeviceInfoList(DeviceUARTContext);

            if (tempDevCount > 0)
            {
                if( DevCount != tempDevCount )
                {
                    DevCount = tempDevCount;
                updatePortNumberSelector();
                }
            }
            else
            {
                DevCount = -1;
                currentIndex = -1;
            }
        }

        public void disconnectFunction()
        {
            DevCount = -1;
            currentIndex = -1;
            bReadThreadGoing = false;
            try {
                Thread.sleep(50);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }

            if(ftDev != null)
            {
                synchronized(ftDev)
                {
                    if( true == ftDev.isOpen())
                    {
                        ftDev.close();
                    }
                }
            }
        }


        public void connectFunction()
        {
            int tmpProtNumber = openIndex + 1;

            if( currentIndex != openIndex )
            {
                if(null == ftDev)
                {
                    ftDev = ftdid2xx.openByIndex(DeviceUARTContext, openIndex);
                }
                else
                {
                    synchronized(ftDev)
                    {
                        ftDev = ftdid2xx.openByIndex(DeviceUARTContext, openIndex);
                    }
                }
                uart_configured = false;
            }
            else
            {
                Toast.makeText(DeviceUARTContext,"Device port " + tmpProtNumber + " is already opened",Toast.LENGTH_LONG).show();
                return;
            }

            if(ftDev == null)
            {
                Toast.makeText(DeviceUARTContext,"open device port("+tmpProtNumber+") NG, ftDev == null", Toast.LENGTH_LONG).show();
                return;
            }

            if (true == ftDev.isOpen())
            {
                currentIndex = openIndex;
                Toast.makeText(DeviceUARTContext, "open device port(" + tmpProtNumber + ") OK", Toast.LENGTH_SHORT).show();

                if(false == bReadThreadGoing)
                {
                    read_thread = new readThread(handler);
                    read_thread.start();
                    bReadThreadGoing = true;
                }
            }
            else 
            {           
                Toast.makeText(DeviceUARTContext, "open device port(" + tmpProtNumber + ") NG", Toast.LENGTH_LONG).show();
                //Toast.makeText(DeviceUARTContext, "Need to get permission!", Toast.LENGTH_SHORT).show();          
            }
        }


        public void updatePortNumberSelector()
        {

        }




        public void SetConfig(int baud, byte dataBits, byte stopBits, byte parity, byte flowControl)
         {
                if (ftDev.isOpen() == false) {
                    Log.e("j2xx", "SetConfig: device not open");
                    return;
                }

                // configure our port
                // reset to UART mode for 232 devices
                ftDev.setBitMode((byte) 0, D2xxManager.FT_BITMODE_RESET);

                ftDev.setBaudRate(baud);

                switch (dataBits) {
                case 7:
                    dataBits = D2xxManager.FT_DATA_BITS_7;
                    break;
                case 8:
                    dataBits = D2xxManager.FT_DATA_BITS_8;
                    break;
                default:
                    dataBits = D2xxManager.FT_DATA_BITS_8;
                    break;
                }

                switch (stopBits) {
                case 1:
                    stopBits = D2xxManager.FT_STOP_BITS_1;
                    break;
                case 2:
                    stopBits = D2xxManager.FT_STOP_BITS_2;
                    break;
                default:
                    stopBits = D2xxManager.FT_STOP_BITS_1;
                    break;
                }

                switch (parity) {
                case 0:
                    parity = D2xxManager.FT_PARITY_NONE;
                    break;
                case 1:
                    parity = D2xxManager.FT_PARITY_ODD;
                    break;
                case 2:
                    parity = D2xxManager.FT_PARITY_EVEN;
                    break;
                case 3:
                    parity = D2xxManager.FT_PARITY_MARK;
                    break;
                case 4:
                    parity = D2xxManager.FT_PARITY_SPACE;
                    break;
                default:
                    parity = D2xxManager.FT_PARITY_NONE;
                    break;
                }

                ftDev.setDataCharacteristics(dataBits, stopBits, parity);

                short flowCtrlSetting;
                switch (flowControl) {
                case 0:
                    flowCtrlSetting = D2xxManager.FT_FLOW_NONE;
                    break;
                case 1:
                    flowCtrlSetting = D2xxManager.FT_FLOW_RTS_CTS;
                    break;
                case 2:
                    flowCtrlSetting = D2xxManager.FT_FLOW_DTR_DSR;
                    break;
                case 3:
                    flowCtrlSetting = D2xxManager.FT_FLOW_XON_XOFF;
                    break;
                default:
                    flowCtrlSetting = D2xxManager.FT_FLOW_NONE;
                    break;
                }

                // TODO : flow ctrl: XOFF/XOM
                // TODO : flow ctrl: XOFF/XOM
                ftDev.setFlowControl(flowCtrlSetting, (byte) 0x0b, (byte) 0x0d);

                uart_configured = true;
                Toast.makeText(DeviceUARTContext, "Config done", Toast.LENGTH_SHORT).show();
            }
         public void EnableRead (){     
                iEnableReadFlag = (iEnableReadFlag + 1)%2;

                if(iEnableReadFlag == 1) {
                    ftDev.purge((byte) (D2xxManager.FT_PURGE_TX));
                    ftDev.restartInTask();
                    readEnButton.setText("Read Enabled");
                }
                else{
                    ftDev.stopInTask();
                    readEnButton.setText("Read Disabled");
                }
            }
         final Handler handler =  new Handler()
            {
                @Override
                public void handleMessage(Message msg)
                {
                    if(iavailable > 0)
                    {
                        readText.append(String.copyValueOf(readDataToText, 0, iavailable));
                    }
                }
            };
            private class readThread  extends Thread
            {
                Handler mHandler;

                readThread(Handler h){
                    mHandler = h;
                    this.setPriority(Thread.MIN_PRIORITY);
                }

                @Override
                public void run()
                {
                    int i;

                    while(true == bReadThreadGoing)
                    {
                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException e) {
                        }

                        synchronized(ftDev)
                        {
                            iavailable = ftDev.getQueueStatus();                
                            if (iavailable > 0) {

                                if(iavailable > readLength){
                                    iavailable = readLength;
                                }

                                ftDev.read(readData, iavailable);
                                for (i = 0; i < iavailable; i++) {
                                    readDataToText[i] = (char) readData[i];
                                }
                                Message msg = mHandler.obtainMessage();
                                mHandler.sendMessage(msg);
                            }
                        }
                    }
                }

            }



    @Override
    public void onResume() {
        super.onResume();
        DevCount = 0;
        createDeviceList();
        if(DevCount > 0)
        {
            connectFunction();
            SetConfig(baudRate, dataBit, stopBit, parity, flowControl);
        }       
    }
}

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

要将片段附加到活动,您有两种方法:

1)在活动的布局文件中声明片段。

2)以编程方式将片段添加到现有的ViewGroup。

在我看来,你可以使用第二种方式,所以基本上你需要在活动中放置一个ViewGroup来放置Fragment;像布局这样的东西可能对此有好处。 如果有插入片段的位置,可以使用LayoutInfleter插入它。

Fragment fragment = new YourFragment();
getLayoutInflater.inflate(R.id.youLayoutContainer, fragment, false);

请查看下面的页面了解更多信息:

http://developer.android.com/guide/components/fragments.html