1

我正在使用下面的代码,并且我有一个未显示的按钮。我认为它与“SetContentView”有关,因为如果我删除其中一个,按钮就会出现。我不知道如何解决这个问题,以便一切都显示出来?谢谢!

import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

import android.widget.Button;
import android.widget.TextView;

public class TestActivity extends Activity {
/** Called when the activity is first created. 
 * @return */



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

    setContentView(R.layout.main);
    Button OffWifi = (Button)findViewById(R.id.offwifi);
    OffWifi.setOnClickListener(new OnClickListener() { 
      public void onClick(View v) {                 
          WifiManager wifiManager = (WifiManager)getBaseContext().getSystemService(Context.WIFI_SERVICE);
            wifiManager.setWifiEnabled(false);          
          }        
      });



    TextView tv = new TextView(this);       
    TextView status = new TextView(this);                  


    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); 
    WifiConfiguration wc = new WifiConfiguration();  
    wc.SSID = "\"Test\""; //IMP! This should be in Quotes!! 

    wc.hiddenSSID = true; 
    wc.status = WifiConfiguration.Status.ENABLED;      
    wc.priority = 10; 
    wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); 
    wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);  
    wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA); 
    wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); 
    wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED); 
    wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); 
    wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); 
    wc.preSharedKey = "\"Password\""; 
    WifiManager  wifiManag = (WifiManager) this.getSystemService(WIFI_SERVICE); 
    boolean res1 = wifiManag.setWifiEnabled(true); 
    int res = wifi.addNetwork(checkPreviousConfiguration(wc)); 
    Log.d("WifiPreference", "add Network returned " + res ); 
    boolean es = wifi.saveConfiguration(); 
    Log.d("WifiPreference", "saveConfiguration returned " + es ); 
    boolean b = wifi.enableNetwork(res, true);    
    Log.d("WifiPreference", "enableNetwork returned " + b );   

    tv.setText("You are now connected!  " +
            "Version 1.1");

    status.setText("The was an error connecting, please try again.");

       //@Override

    try {

        Thread.sleep(5000);

         ConnectivityManager connec = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); 

         if (connec != null && (connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED) ||(connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED)){  
                //You are connected, do something online. 
                setContentView(tv);

            }else if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED ||  connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED ) {              
                //Not connected.         
               setContentView(status);
            }  

    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }





}

public WifiConfiguration checkPreviousConfiguration(WifiConfiguration wc) {
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); 
 List<WifiConfiguration> configs = wifi.getConfiguredNetworks();     
    for(WifiConfiguration config : configs) {         
        if(config.SSID.equals(wc.SSID)) return config;     
        }     
    return wc; 
    } 

}

主 XML 文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

<TextView
android:id="@+id/tv"
android:layout_width="246dp"
android:layout_height="wrap_content" />


<Button
android:id="@+id/offwifi"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Turn Wifi Off" />

</LinearLayout>
4

3 回答 3

1

您需要在 main.xml 布局文件中获取根对象,即

LinearLayout layout = (LinearLayout) findViewById( R.id.linearlayout1 );

然后你可以添加到那个布局(它可能没有被命名为linearlayout1)

layout.addView ( status );
于 2012-04-19T18:35:28.083 回答
1

setContentView() 不会将视图添加到显示中,它会替换它们。这就是你的按钮消失的原因。

在你的 XML 布局中使用现有的电视而不是创建一个新的,并且只调用一次 setContentReview()。

像这样:

super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button OffWifi = (Button)findViewById(R.id.offwifi);
OffWifi.setOnClickListener(new OnClickListener() { 
  public void onClick(View v) {                 
      WifiManager wifiManager = (WifiManager)getBaseContext().getSystemService(Context.WIFI_SERVICE);
        wifiManager.setWifiEnabled(false);          
      }        
  });


// remove these lines
// TextView tv = new TextView(this);       
// TextView status = new TextView(this);                  

// add this line
TextView tv= (TextView) findViewById(R.id.tv);


WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); 
WifiConfiguration wc....

 ect.ect. 

Log.d("WifiPreference", "enableNetwork returned " + b );   

// let's do this later
//tv.setText("You are now connected!  " +
//        "Version 1.1");

//status.setText("The was an error connecting, please try again.");

   //@Override

try {

    Thread.sleep(5000);

     ConnectivityManager connec = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); 

     if (connec != null && (connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED) ||(connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED)){  

            //You are connected, do something online. 

            // setting the ContentView replaces everything, so don't do that
            //setContentView(tv);

            tv.setText("You are now connected!  " +
               "Version 1.1");



        }else if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED ||  connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED ) {              
            //Not connected.         


           //setContentView(status);
           tv.setText("The was an error connecting, please try again.");
        }  

} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

}

于 2012-04-19T19:25:15.983 回答
1

您开始您的活动,将其内容视图设置为至少有一个按钮的东西。然后您创建 TextViews 的新实例。然后稍后在 OnCreate 中,将内容视图设置为文本视图之一。如果已连接,则视图将替换为 TextView,如果未连接,则视图将替换为 TextView。如果您删除其中一个额外设置的内容调用,您将看到该按钮,具体取决于您是否已连接。

这种行为可能是您想要的,或者您可能想要做的是将 TextViews 添加到布局中,并使用 FindViewById 以与按钮句柄相同的方式获取它们的句柄。然后,您可以避免使用 try 块中的所有内容,因为 textviews 已经使用新文本进行了更新。您的代码当前所做的是将整个布局替换为文本视图。

于 2012-04-19T17:51:44.880 回答